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 "frontends/alert.h"
81 #include "frontends/Delegates.h"
82 #include "frontends/WorkAreaManager.h"
84 #include "graphics/Previews.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;
123 namespace Alert = frontend::Alert;
124 namespace os = support::os;
128 // Do not remove the comment below, so we get merge conflict in
129 // independent branches. Instead add your own.
130 int const LYX_FORMAT = 412; // edwin: set tabular width
132 typedef map<string, bool> DepClean;
133 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
135 void showPrintError(string const & name)
137 docstring str = bformat(_("Could not print the document %1$s.\n"
138 "Check that your printer is set up correctly."),
139 makeDisplayPath(name, 50));
140 Alert::error(_("Print document failed"), str);
149 Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
160 /// search for macro in local (buffer) table or in children
161 MacroData const * getBufferMacro(docstring const & name,
162 DocIterator const & pos) const;
164 /// Update macro table starting with position of it \param it in some
166 void updateMacros(DocIterator & it, DocIterator & scope);
168 void setLabel(ParIterator & it, UpdateType utype) const;
170 /** If we have branches that use the file suffix
171 feature, return the file name with suffix appended.
173 support::FileName exportFileName() const;
180 mutable TexRow texrow;
182 /// need to regenerate .tex?
186 mutable bool lyx_clean;
188 /// is autosave needed?
189 mutable bool bak_clean;
191 /// is this an unnamed file (New...)?
197 /// name of the file the buffer is associated with.
200 /** Set to true only when the file is fully loaded.
201 * Used to prevent the premature generation of previews
202 * and by the citation inset.
204 bool file_fully_loaded;
207 mutable TocBackend toc_backend;
210 typedef pair<DocIterator, MacroData> ScopeMacro;
211 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
212 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
213 /// map from the macro name to the position map,
214 /// which maps the macro definition position to the scope and the MacroData.
215 NamePositionScopeMacroMap macros;
216 /// This seem to change the way Buffer::getMacro() works
217 mutable bool macro_lock;
219 /// positions of child buffers in the buffer
220 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
221 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
222 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
223 /// position of children buffers in this buffer
224 BufferPositionMap children_positions;
225 /// map from children inclusion positions to their scope and their buffer
226 PositionScopeBufferMap position_to_children;
228 /// Container for all sort of Buffer dependant errors.
229 map<string, ErrorList> errorLists;
231 /// timestamp and checksum used to test if the file has been externally
232 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
234 unsigned long checksum_;
237 frontend::WorkAreaManager * wa_;
239 frontend::GuiBufferDelegate * gui_;
244 /// A cache for the bibfiles (including bibfiles of loaded child
245 /// documents), needed for appropriate update of natbib labels.
246 mutable support::FileNameList bibfiles_cache_;
248 // FIXME The caching mechanism could be improved. At present, we have a
249 // cache for each Buffer, that caches all the bibliography info for that
250 // Buffer. A more efficient solution would be to have a global cache per
251 // file, and then to construct the Buffer's bibinfo from that.
252 /// A cache for bibliography info
253 mutable BiblioInfo bibinfo_;
254 /// whether the bibinfo cache is valid
255 mutable bool bibinfo_cache_valid_;
256 /// whether the bibfile cache is valid
257 mutable bool bibfile_cache_valid_;
258 /// Cache of timestamps of .bib files
259 map<FileName, time_t> bibfile_status_;
261 mutable RefCache ref_cache_;
263 /// our Text that should be wrapped in an InsetText
266 /// This is here to force the test to be done whenever parent_buffer
268 Buffer const * parent() const {
269 // if parent_buffer is not loaded, then it has been unloaded,
270 // which means that parent_buffer is an invalid pointer. So we
271 // set it to null in that case.
272 // however, the BufferList doesn't know about cloned buffers, so
273 // they will always be regarded as unloaded. in that case, we hope
275 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
277 return parent_buffer;
281 void setParent(Buffer const * pb) {
282 if (parent_buffer == pb)
285 if (!cloned_buffer_ && parent_buffer && pb)
286 LYXERR0("Warning: a buffer should not have two parents!");
288 if (!cloned_buffer_ && parent_buffer) {
289 parent_buffer->invalidateBibfileCache();
290 parent_buffer->invalidateBibinfoCache();
294 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
295 /// This one is useful for preview detached in a thread.
296 Buffer const * cloned_buffer_;
297 /// are we in the process of exporting this buffer?
298 mutable bool doing_export;
301 /// So we can force access via the accessors.
302 mutable Buffer const * parent_buffer;
307 /// Creates the per buffer temporary directory
308 static FileName createBufferTmpDir()
311 // We are in our own directory. Why bother to mangle name?
312 // In fact I wrote this code to circumvent a problematic behaviour
313 // (bug?) of EMX mkstemp().
314 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
315 convert<string>(count++));
317 if (!tmpfl.createDirectory(0777)) {
318 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
319 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
320 from_utf8(tmpfl.absFileName())));
326 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
327 Buffer const * cloned_buffer)
328 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
329 read_only(readonly_), filename(file), file_fully_loaded(false),
330 toc_backend(owner), macro_lock(false), timestamp_(0),
331 checksum_(0), wa_(0), gui_(0), undo_(*owner), bibinfo_cache_valid_(false),
332 bibfile_cache_valid_(false), cloned_buffer_(cloned_buffer),
333 doing_export(false), parent_buffer(0)
335 if (!cloned_buffer_) {
336 temppath = createBufferTmpDir();
337 lyxvc.setBuffer(owner_);
339 wa_ = new frontend::WorkAreaManager;
342 temppath = cloned_buffer_->d->temppath;
343 file_fully_loaded = true;
344 params = cloned_buffer_->d->params;
345 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
346 bibinfo_ = cloned_buffer_->d->bibinfo_;
347 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
348 bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
349 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
353 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
354 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
356 LYXERR(Debug::INFO, "Buffer::Buffer()");
358 d->inset = new InsetText(*cloned_buffer->d->inset);
359 d->inset->setBuffer(*this);
360 // FIXME: optimize this loop somewhat, maybe by creating a new
361 // general recursive Inset::setId().
362 DocIterator it = doc_iterator_begin(this);
363 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
364 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
365 it.paragraph().setId(cloned_it.paragraph().id());
367 d->inset = new InsetText(this);
368 d->inset->setAutoBreakRows(true);
369 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
375 LYXERR(Debug::INFO, "Buffer::~Buffer()");
376 // here the buffer should take care that it is
377 // saved properly, before it goes into the void.
379 // GuiView already destroyed
383 // No need to do additional cleanups for internal buffer.
388 // loop over children
389 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
390 Impl::BufferPositionMap::iterator end = d->children_positions.end();
391 for (; it != end; ++it) {
392 Buffer * child = const_cast<Buffer *>(it->first);
393 if (d->cloned_buffer_)
395 // The child buffer might have been closed already.
396 else if (theBufferList().isLoaded(child))
397 theBufferList().releaseChild(this, child);
401 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
402 msg += emergencyWrite();
403 Alert::warning(_("Attempting to close changed document!"), msg);
406 // clear references to children in macro tables
407 d->children_positions.clear();
408 d->position_to_children.clear();
410 if (!d->cloned_buffer_ && !d->temppath.destroyDirectory()) {
411 Alert::warning(_("Could not remove temporary directory"),
412 bformat(_("Could not remove the temporary directory %1$s"),
413 from_utf8(d->temppath.absFileName())));
423 Buffer * Buffer::clone() const
425 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
426 buffer_clone->d->macro_lock = true;
427 buffer_clone->d->children_positions.clear();
428 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
429 // math macro caches need to be rethought and simplified.
430 // I am not sure wether we should handle Buffer cloning here or in BufferList.
431 // Right now BufferList knows nothing about buffer clones.
432 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
433 Impl::BufferPositionMap::iterator end = d->children_positions.end();
434 for (; it != end; ++it) {
435 DocIterator dit = it->second.clone(buffer_clone);
436 dit.setBuffer(buffer_clone);
437 Buffer * child = const_cast<Buffer *>(it->first);
438 Buffer * child_clone = child->clone();
439 Inset * inset = dit.nextInset();
440 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
441 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
442 inset_inc->setChildBuffer(child_clone);
443 child_clone->d->setParent(buffer_clone);
444 buffer_clone->setChild(dit, child_clone);
446 buffer_clone->d->macro_lock = false;
451 bool Buffer::isClone() const
453 return d->cloned_buffer_;
457 void Buffer::changed(bool update_metrics) const
460 d->wa_->redrawAll(update_metrics);
464 frontend::WorkAreaManager & Buffer::workAreaManager() const
466 LASSERT(d->wa_, /**/);
471 Text & Buffer::text() const
473 return d->inset->text();
477 Inset & Buffer::inset() const
483 BufferParams & Buffer::params()
489 BufferParams const & Buffer::params() const
495 ParagraphList & Buffer::paragraphs()
497 return text().paragraphs();
501 ParagraphList const & Buffer::paragraphs() const
503 return text().paragraphs();
507 LyXVC & Buffer::lyxvc()
513 LyXVC const & Buffer::lyxvc() const
519 string const Buffer::temppath() const
521 return d->temppath.absFileName();
525 TexRow & Buffer::texrow()
531 TexRow const & Buffer::texrow() const
537 TocBackend & Buffer::tocBackend() const
539 return d->toc_backend;
543 Undo & Buffer::undo()
549 void Buffer::setChild(DocIterator const & dit, Buffer * child)
551 d->children_positions[child] = dit;
555 string Buffer::latexName(bool const no_path) const
557 FileName latex_name =
558 makeLatexName(d->exportFileName());
559 return no_path ? latex_name.onlyFileName()
560 : latex_name.absFileName();
564 FileName Buffer::Impl::exportFileName() const
566 docstring const branch_suffix =
567 params.branchlist().getFileNameSuffix();
568 if (branch_suffix.empty())
571 string const name = filename.onlyFileNameWithoutExt()
572 + to_utf8(branch_suffix);
573 FileName res(filename.onlyPath().absFileName() + "/" + name);
574 res.changeExtension(filename.extension());
580 string Buffer::logName(LogType * type) const
582 string const filename = latexName(false);
584 if (filename.empty()) {
590 string const path = temppath();
592 FileName const fname(addName(temppath(),
593 onlyFileName(changeExtension(filename,
596 // FIXME: how do we know this is the name of the build log?
597 FileName const bname(
598 addName(path, onlyFileName(
599 changeExtension(filename,
600 formats.extension(bufferFormat()) + ".out"))));
602 // Also consider the master buffer log file
603 FileName masterfname = fname;
605 if (masterBuffer() != this) {
606 string const mlogfile = masterBuffer()->logName(&mtype);
607 masterfname = FileName(mlogfile);
610 // If no Latex log or Build log is newer, show Build log
611 if (bname.exists() &&
612 ((!fname.exists() && !masterfname.exists())
613 || (fname.lastModified() < bname.lastModified()
614 && masterfname.lastModified() < bname.lastModified()))) {
615 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
618 return bname.absFileName();
619 // If we have a newer master file log or only a master log, show this
620 } else if (fname != masterfname
621 && (!fname.exists() && (masterfname.exists()
622 || fname.lastModified() < masterfname.lastModified()))) {
623 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
626 return masterfname.absFileName();
628 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
631 return fname.absFileName();
635 void Buffer::setReadonly(bool const flag)
637 if (d->read_only != flag) {
644 void Buffer::setFileName(FileName const & fname)
647 setReadonly(d->filename.isReadOnly());
653 int Buffer::readHeader(Lexer & lex)
655 int unknown_tokens = 0;
657 int begin_header_line = -1;
659 // Initialize parameters that may be/go lacking in header:
660 params().branchlist().clear();
661 params().preamble.erase();
662 params().options.erase();
663 params().master.erase();
664 params().float_placement.erase();
665 params().paperwidth.erase();
666 params().paperheight.erase();
667 params().leftmargin.erase();
668 params().rightmargin.erase();
669 params().topmargin.erase();
670 params().bottommargin.erase();
671 params().headheight.erase();
672 params().headsep.erase();
673 params().footskip.erase();
674 params().columnsep.erase();
675 params().fonts_cjk.erase();
676 params().listings_params.clear();
677 params().clearLayoutModules();
678 params().clearRemovedModules();
679 params().clearIncludedChildren();
680 params().pdfoptions().clear();
681 params().indiceslist().clear();
682 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
683 params().isbackgroundcolor = false;
684 params().fontcolor = lyx::rgbFromHexName("#000000");
685 params().isfontcolor = false;
686 params().notefontcolor = lyx::rgbFromHexName("#cccccc");
687 params().boxbgcolor = lyx::rgbFromHexName("#ff0000");
688 params().html_latex_start.clear();
689 params().html_latex_end.clear();
690 params().html_math_img_scale = 1.0;
691 params().output_sync_macro.erase();
693 for (int i = 0; i < 4; ++i) {
694 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
695 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
698 ErrorList & errorList = d->errorLists["Parse"];
707 if (token == "\\end_header")
711 if (token == "\\begin_header") {
712 begin_header_line = line;
716 LYXERR(Debug::PARSER, "Handling document header token: `"
719 string unknown = params().readToken(lex, token, d->filename.onlyPath());
720 if (!unknown.empty()) {
721 if (unknown[0] != '\\' && token == "\\textclass") {
722 Alert::warning(_("Unknown document class"),
723 bformat(_("Using the default document class, because the "
724 "class %1$s is unknown."), from_utf8(unknown)));
727 docstring const s = bformat(_("Unknown token: "
731 errorList.push_back(ErrorItem(_("Document header error"),
736 if (begin_header_line) {
737 docstring const s = _("\\begin_header is missing");
738 errorList.push_back(ErrorItem(_("Document header error"),
742 params().makeDocumentClass();
744 return unknown_tokens;
749 // changed to be public and have one parameter
750 // Returns true if "\end_document" is not read (Asger)
751 bool Buffer::readDocument(Lexer & lex)
753 ErrorList & errorList = d->errorLists["Parse"];
756 // remove dummy empty par
757 paragraphs().clear();
759 if (!lex.checkFor("\\begin_document")) {
760 docstring const s = _("\\begin_document is missing");
761 errorList.push_back(ErrorItem(_("Document header error"),
767 if (params().outputChanges) {
768 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
769 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
770 LaTeXFeatures::isAvailable("xcolor");
772 if (!dvipost && !xcolorulem) {
773 Alert::warning(_("Changes not shown in LaTeX output"),
774 _("Changes will not be highlighted in LaTeX output, "
775 "because neither dvipost nor xcolor/ulem are installed.\n"
776 "Please install these packages or redefine "
777 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
778 } else if (!xcolorulem) {
779 Alert::warning(_("Changes not shown in LaTeX output"),
780 _("Changes will not be highlighted in LaTeX output "
781 "when using pdflatex, because xcolor and ulem are not installed.\n"
782 "Please install both packages or redefine "
783 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
787 if (!params().master.empty()) {
788 FileName const master_file = makeAbsPath(params().master,
789 onlyPath(absFileName()));
790 if (isLyXFileName(master_file.absFileName())) {
792 checkAndLoadLyXFile(master_file, true);
794 // necessary e.g. after a reload
795 // to re-register the child (bug 5873)
796 // FIXME: clean up updateMacros (here, only
797 // child registering is needed).
798 master->updateMacros();
799 // set master as master buffer, but only
800 // if we are a real child
801 if (master->isChild(this))
803 // if the master is not fully loaded
804 // it is probably just loading this
805 // child. No warning needed then.
806 else if (master->isFullyLoaded())
807 LYXERR0("The master '"
809 << "' assigned to this document ("
811 << ") does not include "
812 "this document. Ignoring the master assignment.");
817 // assure we have a default index
818 params().indiceslist().addDefault(B_("Index"));
821 bool const res = text().read(lex, errorList, d->inset);
823 // inform parent buffer about local macros
825 Buffer const * pbuf = parent();
826 UserMacroSet::const_iterator cit = usermacros.begin();
827 UserMacroSet::const_iterator end = usermacros.end();
828 for (; cit != end; ++cit)
829 pbuf->usermacros.insert(*cit);
833 updateMacroInstances();
838 bool Buffer::readString(string const & s)
840 params().compressed = false;
845 FileName const fn = FileName::tempName("Buffer_readString");
848 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
849 if (ret_plf != ReadSuccess)
852 if (file_format != LYX_FORMAT) {
853 // We need to call lyx2lyx, so write the input to a file
854 ofstream os(fn.toFilesystemEncoding().c_str());
858 return readFile(fn) == ReadSuccess;
861 if (readDocument(lex))
867 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
874 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
875 if (ret_plf != ReadSuccess)
878 if (file_format != LYX_FORMAT) {
880 ReadStatus const ret_clf = convertLyXFormat(fn, tmpFile, file_format);
881 if (ret_clf != ReadSuccess)
883 return readFile(tmpFile);
886 // FIXME: InsetInfo needs to know whether the file is under VCS
887 // during the parse process, so this has to be done before.
888 lyxvc().file_found_hook(d->filename);
890 if (readDocument(lex)) {
891 Alert::error(_("Document format failure"),
892 bformat(_("%1$s ended unexpectedly, which means"
893 " that it is probably corrupted."),
894 from_utf8(fn.absFileName())));
895 return ReadDocumentFailure;
898 d->file_fully_loaded = true;
899 d->read_only = !d->filename.isWritable();
900 params().compressed = d->filename.isZippedFile();
906 bool Buffer::isFullyLoaded() const
908 return d->file_fully_loaded;
912 void Buffer::setFullyLoaded(bool value)
914 d->file_fully_loaded = value;
918 void Buffer::updatePreviews() const
920 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
921 thePreviews().generateBufferPreviews(*this);
925 void Buffer::removePreviews() const
927 thePreviews().removeLoader(*this);
931 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
932 FileName const & fn, int & file_format) const
934 if(!lex.checkFor("\\lyxformat")) {
935 Alert::error(_("Document format failure"),
936 bformat(_("%1$s is not a readable LyX document."),
937 from_utf8(fn.absFileName())));
938 return ReadNoLyXFormat;
944 // LyX formats 217 and earlier were written as 2.17. This corresponds
945 // to files from LyX versions < 1.1.6.3. We just remove the dot in
946 // these cases. See also: www.lyx.org/trac/changeset/1313.
947 size_t dot = tmp_format.find_first_of(".,");
948 if (dot != string::npos)
949 tmp_format.erase(dot, 1);
951 file_format = convert<int>(tmp_format);
956 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
957 FileName & tmpfile, int from_format)
959 tmpfile = FileName::tempName("Buffer_convertLyXFormat");
960 if(tmpfile.empty()) {
961 Alert::error(_("Conversion failed"),
962 bformat(_("%1$s is from a different"
963 " version of LyX, but a temporary"
964 " file for converting it could"
966 from_utf8(fn.absFileName())));
967 return LyX2LyXNoTempFile;
970 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
971 if (lyx2lyx.empty()) {
972 Alert::error(_("Conversion script not found"),
973 bformat(_("%1$s is from a different"
974 " version of LyX, but the"
975 " conversion script lyx2lyx"
976 " could not be found."),
977 from_utf8(fn.absFileName())));
978 return LyX2LyXNotFound;
982 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
983 ostringstream command;
984 command << os::python()
985 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
986 << " -t " << convert<string>(LYX_FORMAT)
987 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
988 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
989 string const command_str = command.str();
991 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
993 cmd_ret const ret = runCommand(command_str);
994 if (ret.first != 0) {
995 if (from_format < LYX_FORMAT) {
996 Alert::error(_("Conversion script failed"),
997 bformat(_("%1$s is from an older version"
998 " of LyX and the lyx2lyx script"
999 " failed to convert it."),
1000 from_utf8(fn.absFileName())));
1001 return LyX2LyXOlderFormat;
1003 Alert::error(_("Conversion script failed"),
1004 bformat(_("%1$s is from a newer version"
1005 " of LyX and the lyx2lyx script"
1006 " failed to convert it."),
1007 from_utf8(fn.absFileName())));
1008 return LyX2LyXNewerFormat;
1015 // Should probably be moved to somewhere else: BufferView? GuiView?
1016 bool Buffer::save() const
1018 docstring const file = makeDisplayPath(absFileName(), 20);
1019 d->filename.refresh();
1021 // check the read-only status before moving the file as a backup
1022 if (d->filename.exists()) {
1023 bool const read_only = !d->filename.isWritable();
1025 Alert::warning(_("File is read-only"),
1026 bformat(_("The file %1$s cannot be written because it "
1027 "is marked as read-only."), file));
1032 // ask if the disk file has been externally modified (use checksum method)
1033 if (fileName().exists() && isExternallyModified(checksum_method)) {
1035 bformat(_("Document %1$s has been externally modified. "
1036 "Are you sure you want to overwrite this file?"), file);
1037 int const ret = Alert::prompt(_("Overwrite modified file?"),
1038 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1043 // We don't need autosaves in the immediate future. (Asger)
1044 resetAutosaveTimers();
1046 FileName backupName;
1047 bool madeBackup = false;
1049 // make a backup if the file already exists
1050 if (lyxrc.make_backup && fileName().exists()) {
1051 backupName = FileName(absFileName() + '~');
1052 if (!lyxrc.backupdir_path.empty()) {
1053 string const mangledName =
1054 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1055 backupName = FileName(addName(lyxrc.backupdir_path,
1059 // Except file is symlink do not copy because of #6587.
1060 // Hard links have bad luck.
1061 if (fileName().isSymLink())
1062 madeBackup = fileName().copyTo(backupName);
1064 madeBackup = fileName().moveTo(backupName);
1067 Alert::error(_("Backup failure"),
1068 bformat(_("Cannot create backup file %1$s.\n"
1069 "Please check whether the directory exists and is writable."),
1070 from_utf8(backupName.absFileName())));
1071 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1075 if (writeFile(d->filename)) {
1079 // Saving failed, so backup is not backup
1081 backupName.moveTo(d->filename);
1087 bool Buffer::writeFile(FileName const & fname) const
1089 if (d->read_only && fname == d->filename)
1092 bool retval = false;
1094 docstring const str = bformat(_("Saving document %1$s..."),
1095 makeDisplayPath(fname.absFileName()));
1098 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1100 if (params().compressed) {
1101 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1102 retval = ofs && write(ofs);
1104 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1105 retval = ofs && write(ofs);
1109 message(str + _(" could not write file!"));
1114 // removeAutosaveFile();
1117 message(str + _(" done."));
1123 docstring Buffer::emergencyWrite()
1125 // No need to save if the buffer has not changed.
1129 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1131 docstring user_message = bformat(
1132 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1134 // We try to save three places:
1135 // 1) Same place as document. Unless it is an unnamed doc.
1137 string s = absFileName();
1140 if (writeFile(FileName(s))) {
1142 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1143 return user_message;
1145 user_message += " " + _("Save failed! Trying again...\n");
1149 // 2) In HOME directory.
1150 string s = addName(package().home_dir().absFileName(), absFileName());
1152 lyxerr << ' ' << s << endl;
1153 if (writeFile(FileName(s))) {
1155 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1156 return user_message;
1159 user_message += " " + _("Save failed! Trying yet again...\n");
1161 // 3) In "/tmp" directory.
1162 // MakeAbsPath to prepend the current
1163 // drive letter on OS/2
1164 s = addName(package().temp_dir().absFileName(), absFileName());
1166 lyxerr << ' ' << s << endl;
1167 if (writeFile(FileName(s))) {
1169 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1170 return user_message;
1173 user_message += " " + _("Save failed! Bummer. Document is lost.");
1176 return user_message;
1180 bool Buffer::write(ostream & ofs) const
1183 // Use the standard "C" locale for file output.
1184 ofs.imbue(locale::classic());
1187 // The top of the file should not be written by params().
1189 // write out a comment in the top of the file
1190 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1191 << " created this file. For more info see http://www.lyx.org/\n"
1192 << "\\lyxformat " << LYX_FORMAT << "\n"
1193 << "\\begin_document\n";
1195 /// For each author, set 'used' to true if there is a change
1196 /// by this author in the document; otherwise set it to 'false'.
1197 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1198 AuthorList::Authors::const_iterator a_end = params().authors().end();
1199 for (; a_it != a_end; ++a_it)
1200 a_it->setUsed(false);
1202 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1203 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1204 for ( ; it != end; ++it)
1205 it->checkAuthors(params().authors());
1207 // now write out the buffer parameters.
1208 ofs << "\\begin_header\n";
1209 params().writeFile(ofs);
1210 ofs << "\\end_header\n";
1213 ofs << "\n\\begin_body\n";
1215 ofs << "\n\\end_body\n";
1217 // Write marker that shows file is complete
1218 ofs << "\\end_document" << endl;
1220 // Shouldn't really be needed....
1223 // how to check if close went ok?
1224 // Following is an attempt... (BE 20001011)
1226 // good() returns false if any error occured, including some
1227 // formatting error.
1228 // bad() returns true if something bad happened in the buffer,
1229 // which should include file system full errors.
1234 lyxerr << "File was not closed properly." << endl;
1241 bool Buffer::makeLaTeXFile(FileName const & fname,
1242 string const & original_path,
1243 OutputParams const & runparams_in,
1244 bool output_preamble, bool output_body) const
1246 OutputParams runparams = runparams_in;
1248 // This is necessary for LuaTeX/XeTeX with tex fonts.
1249 // See FIXME in BufferParams::encoding()
1250 if (runparams.isFullUnicode())
1251 runparams.encoding = encodings.fromLyXName("utf8-plain");
1253 string const encoding = runparams.encoding->iconvName();
1254 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1257 try { ofs.reset(encoding); }
1258 catch (iconv_codecvt_facet_exception & e) {
1259 lyxerr << "Caught iconv exception: " << e.what() << endl;
1260 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1261 "verify that the support software for your encoding (%1$s) is "
1262 "properly installed"), from_ascii(encoding)));
1265 if (!openFileWrite(ofs, fname))
1268 //TexStream ts(ofs.rdbuf(), &texrow());
1269 ErrorList & errorList = d->errorLists["Export"];
1271 bool failed_export = false;
1272 otexstream os(ofs, d->texrow);
1274 os.texrow().reset();
1275 writeLaTeXSource(os, original_path,
1276 runparams, output_preamble, output_body);
1278 catch (EncodingException & e) {
1279 odocstringstream ods;
1280 ods.put(e.failed_char);
1282 oss << "0x" << hex << e.failed_char << dec;
1283 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1284 " (code point %2$s)"),
1285 ods.str(), from_utf8(oss.str()));
1286 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1287 "representable in the chosen encoding.\n"
1288 "Changing the document encoding to utf8 could help."),
1289 e.par_id, e.pos, e.pos + 1));
1290 failed_export = true;
1292 catch (iconv_codecvt_facet_exception & e) {
1293 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1294 _(e.what()), -1, 0, 0));
1295 failed_export = true;
1297 catch (exception const & e) {
1298 errorList.push_back(ErrorItem(_("conversion failed"),
1299 _(e.what()), -1, 0, 0));
1300 failed_export = true;
1303 lyxerr << "Caught some really weird exception..." << endl;
1309 failed_export = true;
1310 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1314 return !failed_export;
1318 void Buffer::writeLaTeXSource(otexstream & os,
1319 string const & original_path,
1320 OutputParams const & runparams_in,
1321 bool const output_preamble, bool const output_body) const
1323 // The child documents, if any, shall be already loaded at this point.
1325 OutputParams runparams = runparams_in;
1327 // Classify the unicode characters appearing in math insets
1328 Encodings::initUnicodeMath(*this);
1330 // validate the buffer.
1331 LYXERR(Debug::LATEX, " Validating buffer...");
1332 LaTeXFeatures features(*this, params(), runparams);
1334 LYXERR(Debug::LATEX, " Buffer validation done.");
1336 // The starting paragraph of the coming rows is the
1337 // first paragraph of the document. (Asger)
1338 if (output_preamble && runparams.nice) {
1339 os << "%% LyX " << lyx_version << " created this file. "
1340 "For more info, see http://www.lyx.org/.\n"
1341 "%% Do not edit unless you really know what "
1344 LYXERR(Debug::INFO, "lyx document header finished");
1346 // Don't move this behind the parent_buffer=0 code below,
1347 // because then the macros will not get the right "redefinition"
1348 // flag as they don't see the parent macros which are output before.
1351 // fold macros if possible, still with parent buffer as the
1352 // macros will be put in the prefix anyway.
1353 updateMacroInstances();
1355 // There are a few differences between nice LaTeX and usual files:
1356 // usual is \batchmode and has a
1357 // special input@path to allow the including of figures
1358 // with either \input or \includegraphics (what figinsets do).
1359 // input@path is set when the actual parameter
1360 // original_path is set. This is done for usual tex-file, but not
1361 // for nice-latex-file. (Matthias 250696)
1362 // Note that input@path is only needed for something the user does
1363 // in the preamble, included .tex files or ERT, files included by
1364 // LyX work without it.
1365 if (output_preamble) {
1366 if (!runparams.nice) {
1367 // code for usual, NOT nice-latex-file
1368 os << "\\batchmode\n"; // changed from \nonstopmode
1370 if (!original_path.empty()) {
1372 // We don't know the encoding of inputpath
1373 docstring const inputpath = from_utf8(support::latex_path(original_path));
1374 docstring uncodable_glyphs;
1375 Encoding const * const enc = runparams.encoding;
1377 for (size_t n = 0; n < inputpath.size(); ++n) {
1378 docstring const glyph =
1379 docstring(1, inputpath[n]);
1380 if (enc->latexChar(inputpath[n], true) != glyph) {
1381 LYXERR0("Uncodable character '"
1383 << "' in input path!");
1384 uncodable_glyphs += glyph;
1389 // warn user if we found uncodable glyphs.
1390 if (!uncodable_glyphs.empty()) {
1391 frontend::Alert::warning(_("Uncodable character in file path"),
1392 support::bformat(_("The path of your document\n"
1394 "contains glyphs that are unknown in the\n"
1395 "current document encoding (namely %2$s).\n"
1396 "This will likely result in incomplete output.\n\n"
1397 "Choose an appropriate document encoding (such as utf8)\n"
1398 "or change the file path name."), inputpath, uncodable_glyphs));
1400 os << "\\makeatletter\n"
1401 << "\\def\\input@path{{"
1402 << inputpath << "/}}\n"
1403 << "\\makeatother\n";
1407 // get parent macros (if this buffer has a parent) which will be
1408 // written at the document begin further down.
1409 MacroSet parentMacros;
1410 listParentMacros(parentMacros, features);
1412 runparams.use_polyglossia = features.usePolyglossia();
1413 // Write the preamble
1414 runparams.use_babel = params().writeLaTeX(os, features,
1415 d->filename.onlyPath());
1417 runparams.use_japanese = features.isRequired("japanese");
1423 os << "\\begin{document}\n";
1425 // output the parent macros
1426 MacroSet::iterator it = parentMacros.begin();
1427 MacroSet::iterator end = parentMacros.end();
1428 for (; it != end; ++it) {
1429 int num_lines = (*it)->write(os.os(), true);
1430 os.texrow().newlines(num_lines);
1433 } // output_preamble
1435 os.texrow().start(paragraphs().begin()->id(), 0);
1437 LYXERR(Debug::INFO, "preamble finished, now the body.");
1439 // if we are doing a real file with body, even if this is the
1440 // child of some other buffer, let's cut the link here.
1441 // This happens for example if only a child document is printed.
1442 Buffer const * save_parent = 0;
1443 if (output_preamble) {
1444 save_parent = d->parent();
1449 latexParagraphs(*this, text(), os, runparams);
1451 // Restore the parenthood if needed
1452 if (output_preamble)
1453 d->setParent(save_parent);
1455 // add this just in case after all the paragraphs
1457 os.texrow().newline();
1459 if (output_preamble) {
1460 os << "\\end{document}\n";
1461 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1463 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1465 runparams_in.encoding = runparams.encoding;
1467 // Just to be sure. (Asger)
1468 os.texrow().newline();
1470 //for (int i = 0; i<d->texrow.rows(); i++) {
1472 // if (d->texrow.getIdFromRow(i+1,id,pos) && id>0)
1473 // lyxerr << i+1 << ":" << id << ":" << getParFromID(id).paragraph().asString()<<"\n";
1476 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1477 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
1481 bool Buffer::isLatex() const
1483 return params().documentClass().outputType() == LATEX;
1487 bool Buffer::isLiterate() const
1489 return params().documentClass().outputType() == LITERATE;
1493 bool Buffer::isDocBook() const
1495 return params().documentClass().outputType() == DOCBOOK;
1499 void Buffer::makeDocBookFile(FileName const & fname,
1500 OutputParams const & runparams,
1501 bool const body_only) const
1503 LYXERR(Debug::LATEX, "makeDocBookFile...");
1506 if (!openFileWrite(ofs, fname))
1509 writeDocBookSource(ofs, fname.absFileName(), runparams, body_only);
1513 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1517 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1518 OutputParams const & runparams,
1519 bool const only_body) const
1521 LaTeXFeatures features(*this, params(), runparams);
1526 DocumentClass const & tclass = params().documentClass();
1527 string const top_element = tclass.latexname();
1530 if (runparams.flavor == OutputParams::XML)
1531 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1534 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1537 if (! tclass.class_header().empty())
1538 os << from_ascii(tclass.class_header());
1539 else if (runparams.flavor == OutputParams::XML)
1540 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1541 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1543 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1545 docstring preamble = from_utf8(params().preamble);
1546 if (runparams.flavor != OutputParams::XML ) {
1547 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1548 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1549 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1550 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1553 string const name = runparams.nice
1554 ? changeExtension(absFileName(), ".sgml") : fname;
1555 preamble += features.getIncludedFiles(name);
1556 preamble += features.getLyXSGMLEntities();
1558 if (!preamble.empty()) {
1559 os << "\n [ " << preamble << " ]";
1564 string top = top_element;
1566 if (runparams.flavor == OutputParams::XML)
1567 top += params().language->code();
1569 top += params().language->code().substr(0, 2);
1572 if (!params().options.empty()) {
1574 top += params().options;
1577 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1578 << " file was created by LyX " << lyx_version
1579 << "\n See http://www.lyx.org/ for more information -->\n";
1581 params().documentClass().counters().reset();
1585 sgml::openTag(os, top);
1587 docbookParagraphs(text(), *this, os, runparams);
1588 sgml::closeTag(os, top_element);
1592 void Buffer::makeLyXHTMLFile(FileName const & fname,
1593 OutputParams const & runparams,
1594 bool const body_only) const
1596 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1599 if (!openFileWrite(ofs, fname))
1602 writeLyXHTMLSource(ofs, runparams, body_only);
1606 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1610 void Buffer::writeLyXHTMLSource(odocstream & os,
1611 OutputParams const & runparams,
1612 bool const only_body) const
1614 LaTeXFeatures features(*this, params(), runparams);
1616 updateBuffer(UpdateMaster, OutputUpdate);
1617 d->bibinfo_.makeCitationLabels(*this);
1619 updateMacroInstances();
1622 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1623 << "<!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"
1624 // FIXME Language should be set properly.
1625 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
1627 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
1628 // FIXME Presumably need to set this right
1629 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1631 docstring const & doctitle = features.htmlTitle();
1633 << (doctitle.empty() ? from_ascii("LyX Document") : doctitle)
1636 os << "\n<!-- Text Class Preamble -->\n"
1637 << features.getTClassHTMLPreamble()
1638 << "\n<!-- Preamble Snippets -->\n"
1639 << from_utf8(features.getPreambleSnippets());
1641 os << "\n<!-- Layout-provided Styles -->\n";
1642 docstring const styleinfo = features.getTClassHTMLStyles();
1643 if (!styleinfo.empty()) {
1644 os << "<style type='text/css'>\n"
1648 os << "</head>\n<body>\n";
1652 params().documentClass().counters().reset();
1653 xhtmlParagraphs(text(), *this, xs, runparams);
1655 os << "</body>\n</html>\n";
1659 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1660 // Other flags: -wall -v0 -x
1661 int Buffer::runChktex()
1665 // get LaTeX-Filename
1666 FileName const path(temppath());
1667 string const name = addName(path.absFileName(), latexName());
1668 string const org_path = filePath();
1670 PathChanger p(path); // path to LaTeX file
1671 message(_("Running chktex..."));
1673 // Generate the LaTeX file if neccessary
1674 OutputParams runparams(¶ms().encoding());
1675 runparams.flavor = OutputParams::LATEX;
1676 runparams.nice = false;
1677 runparams.linelen = lyxrc.plaintext_linelen;
1678 makeLaTeXFile(FileName(name), org_path, runparams);
1681 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
1682 int const res = chktex.run(terr); // run chktex
1685 Alert::error(_("chktex failure"),
1686 _("Could not run chktex successfully."));
1687 } else if (res > 0) {
1688 ErrorList & errlist = d->errorLists["ChkTeX"];
1690 bufferErrors(terr, errlist);
1701 void Buffer::validate(LaTeXFeatures & features) const
1703 params().validate(features);
1707 for_each(paragraphs().begin(), paragraphs().end(),
1708 bind(&Paragraph::validate, _1, ref(features)));
1710 if (lyxerr.debugging(Debug::LATEX)) {
1711 features.showStruct();
1716 void Buffer::getLabelList(vector<docstring> & list) const
1718 // If this is a child document, use the master's list instead.
1720 masterBuffer()->getLabelList(list);
1725 Toc & toc = d->toc_backend.toc("label");
1726 TocIterator toc_it = toc.begin();
1727 TocIterator end = toc.end();
1728 for (; toc_it != end; ++toc_it) {
1729 if (toc_it->depth() == 0)
1730 list.push_back(toc_it->str());
1735 void Buffer::updateBibfilesCache(UpdateScope scope) const
1737 // FIXME This is probably unnecssary, given where we call this.
1738 // If this is a child document, use the parent's cache instead.
1739 if (parent() && scope != UpdateChildOnly) {
1740 masterBuffer()->updateBibfilesCache();
1744 d->bibfiles_cache_.clear();
1745 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1746 if (it->lyxCode() == BIBTEX_CODE) {
1747 InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
1748 support::FileNameList const bibfiles = inset.getBibFiles();
1749 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1752 } else if (it->lyxCode() == INCLUDE_CODE) {
1753 InsetInclude & inset = static_cast<InsetInclude &>(*it);
1754 Buffer const * const incbuf = inset.getChildBuffer();
1757 support::FileNameList const & bibfiles =
1758 incbuf->getBibfilesCache(UpdateChildOnly);
1759 if (!bibfiles.empty()) {
1760 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1766 d->bibfile_cache_valid_ = true;
1767 d->bibinfo_cache_valid_ = false;
1771 void Buffer::invalidateBibinfoCache() const
1773 d->bibinfo_cache_valid_ = false;
1774 // also invalidate the cache for the parent buffer
1775 Buffer const * const pbuf = d->parent();
1777 pbuf->invalidateBibinfoCache();
1781 void Buffer::invalidateBibfileCache() const
1783 d->bibfile_cache_valid_ = false;
1784 d->bibinfo_cache_valid_ = false;
1785 // also invalidate the cache for the parent buffer
1786 Buffer const * const pbuf = d->parent();
1788 pbuf->invalidateBibfileCache();
1792 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1794 // FIXME This is probably unnecessary, given where we call this.
1795 // If this is a child document, use the master's cache instead.
1796 Buffer const * const pbuf = masterBuffer();
1797 if (pbuf != this && scope != UpdateChildOnly)
1798 return pbuf->getBibfilesCache();
1800 if (!d->bibfile_cache_valid_)
1801 this->updateBibfilesCache(scope);
1803 return d->bibfiles_cache_;
1807 BiblioInfo const & Buffer::masterBibInfo() const
1809 Buffer const * const tmp = masterBuffer();
1811 return tmp->masterBibInfo();
1816 void Buffer::checkIfBibInfoCacheIsValid() const
1818 // use the master's cache
1819 Buffer const * const tmp = masterBuffer();
1821 tmp->checkIfBibInfoCacheIsValid();
1825 // compare the cached timestamps with the actual ones.
1826 FileNameList const & bibfiles_cache = getBibfilesCache();
1827 FileNameList::const_iterator ei = bibfiles_cache.begin();
1828 FileNameList::const_iterator en = bibfiles_cache.end();
1829 for (; ei != en; ++ ei) {
1830 time_t lastw = ei->lastModified();
1831 time_t prevw = d->bibfile_status_[*ei];
1832 if (lastw != prevw) {
1833 d->bibinfo_cache_valid_ = false;
1834 d->bibfile_status_[*ei] = lastw;
1840 void Buffer::reloadBibInfoCache() const
1842 // use the master's cache
1843 Buffer const * const tmp = masterBuffer();
1845 tmp->reloadBibInfoCache();
1849 checkIfBibInfoCacheIsValid();
1850 if (d->bibinfo_cache_valid_)
1853 d->bibinfo_.clear();
1855 d->bibinfo_cache_valid_ = true;
1859 void Buffer::collectBibKeys() const
1861 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1862 it->collectBibKeys(it);
1866 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
1868 Buffer const * tmp = masterBuffer();
1869 BiblioInfo & masterbi = (tmp == this) ?
1870 d->bibinfo_ : tmp->d->bibinfo_;
1871 masterbi.mergeBiblioInfo(bi);
1875 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
1877 Buffer const * tmp = masterBuffer();
1878 BiblioInfo & masterbi = (tmp == this) ?
1879 d->bibinfo_ : tmp->d->bibinfo_;
1884 bool Buffer::isDepClean(string const & name) const
1886 DepClean::const_iterator const it = d->dep_clean.find(name);
1887 if (it == d->dep_clean.end())
1893 void Buffer::markDepClean(string const & name)
1895 d->dep_clean[name] = true;
1899 bool Buffer::isExportableFormat(string const & format) const
1901 typedef vector<Format const *> Formats;
1903 formats = exportableFormats(true);
1904 Formats::const_iterator fit = formats.begin();
1905 Formats::const_iterator end = formats.end();
1906 for (; fit != end ; ++fit) {
1907 if ((*fit)->name() == format)
1914 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1917 // FIXME? if there is an Buffer LFUN that can be dispatched even
1918 // if internal, put a switch '(cmd.action)' here.
1924 switch (cmd.action()) {
1926 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1927 flag.setOnOff(isReadonly());
1930 // FIXME: There is need for a command-line import.
1931 //case LFUN_BUFFER_IMPORT:
1933 case LFUN_BUFFER_AUTO_SAVE:
1936 case LFUN_BUFFER_EXPORT_CUSTOM:
1937 // FIXME: Nothing to check here?
1940 case LFUN_BUFFER_EXPORT: {
1941 docstring const arg = cmd.argument();
1942 enable = arg == "custom" || isExportable(to_utf8(arg));
1944 flag.message(bformat(
1945 _("Don't know how to export to format: %1$s"), arg));
1949 case LFUN_BUFFER_CHKTEX:
1950 enable = isLatex() && !lyxrc.chktex_command.empty();
1953 case LFUN_BUILD_PROGRAM:
1954 enable = isExportable("program");
1957 case LFUN_BRANCH_ACTIVATE:
1958 case LFUN_BRANCH_DEACTIVATE: {
1959 BranchList const & branchList = params().branchlist();
1960 docstring const branchName = cmd.argument();
1961 enable = !branchName.empty() && branchList.find(branchName);
1965 case LFUN_BRANCH_ADD:
1966 case LFUN_BRANCHES_RENAME:
1967 case LFUN_BUFFER_PRINT:
1968 // if no Buffer is present, then of course we won't be called!
1971 case LFUN_BUFFER_LANGUAGE:
1972 enable = !isReadonly();
1978 flag.setEnabled(enable);
1983 void Buffer::dispatch(string const & command, DispatchResult & result)
1985 return dispatch(lyxaction.lookupFunc(command), result);
1989 // NOTE We can end up here even if we have no GUI, because we are called
1990 // by LyX::exec to handled command-line requests. So we may need to check
1991 // whether we have a GUI or not. The boolean use_gui holds this information.
1992 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
1995 // FIXME? if there is an Buffer LFUN that can be dispatched even
1996 // if internal, put a switch '(cmd.action())' here.
1997 dr.dispatched(false);
2000 string const argument = to_utf8(func.argument());
2001 // We'll set this back to false if need be.
2002 bool dispatched = true;
2003 undo().beginUndoGroup();
2005 switch (func.action()) {
2006 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2007 if (lyxvc().inUse())
2008 lyxvc().toggleReadOnly();
2010 setReadonly(!isReadonly());
2013 case LFUN_BUFFER_EXPORT: {
2014 bool success = doExport(argument, false, false);
2015 dr.setError(!success);
2017 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2022 case LFUN_BUILD_PROGRAM:
2023 doExport("program", true, false);
2026 case LFUN_BUFFER_CHKTEX:
2030 case LFUN_BUFFER_EXPORT_CUSTOM: {
2032 string command = split(argument, format_name, ' ');
2033 Format const * format = formats.getFormat(format_name);
2035 lyxerr << "Format \"" << format_name
2036 << "\" not recognized!"
2041 // The name of the file created by the conversion process
2044 // Output to filename
2045 if (format->name() == "lyx") {
2046 string const latexname = latexName(false);
2047 filename = changeExtension(latexname,
2048 format->extension());
2049 filename = addName(temppath(), filename);
2051 if (!writeFile(FileName(filename)))
2055 doExport(format_name, true, false, filename);
2058 // Substitute $$FName for filename
2059 if (!contains(command, "$$FName"))
2060 command = "( " + command + " ) < $$FName";
2061 command = subst(command, "$$FName", filename);
2063 // Execute the command in the background
2065 call.startscript(Systemcall::DontWait, command);
2069 // FIXME: There is need for a command-line import.
2071 case LFUN_BUFFER_IMPORT:
2076 case LFUN_BUFFER_AUTO_SAVE:
2078 resetAutosaveTimers();
2081 case LFUN_BRANCH_ADD: {
2082 docstring branch_name = func.argument();
2083 if (branch_name.empty()) {
2087 BranchList & branch_list = params().branchlist();
2088 vector<docstring> const branches =
2089 getVectorFromString(branch_name, branch_list.separator());
2091 for (vector<docstring>::const_iterator it = branches.begin();
2092 it != branches.end(); ++it) {
2094 Branch * branch = branch_list.find(branch_name);
2096 LYXERR0("Branch " << branch_name << " already exists.");
2100 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2102 branch_list.add(branch_name);
2103 branch = branch_list.find(branch_name);
2104 string const x11hexname = X11hexname(branch->color());
2105 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2106 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2108 dr.screenUpdate(Update::Force);
2116 case LFUN_BRANCH_ACTIVATE:
2117 case LFUN_BRANCH_DEACTIVATE: {
2118 BranchList & branchList = params().branchlist();
2119 docstring const branchName = func.argument();
2120 // the case without a branch name is handled elsewhere
2121 if (branchName.empty()) {
2125 Branch * branch = branchList.find(branchName);
2127 LYXERR0("Branch " << branchName << " does not exist.");
2129 docstring const msg =
2130 bformat(_("Branch \"%1$s\" does not exist."), branchName);
2133 branch->setSelected(func.action() == LFUN_BRANCH_ACTIVATE);
2135 dr.screenUpdate(Update::Force);
2136 dr.forceBufferUpdate();
2141 case LFUN_BRANCHES_RENAME: {
2142 if (func.argument().empty())
2145 docstring const oldname = from_utf8(func.getArg(0));
2146 docstring const newname = from_utf8(func.getArg(1));
2147 InsetIterator it = inset_iterator_begin(inset());
2148 InsetIterator const end = inset_iterator_end(inset());
2149 bool success = false;
2150 for (; it != end; ++it) {
2151 if (it->lyxCode() == BRANCH_CODE) {
2152 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2153 if (ins.branch() == oldname) {
2154 undo().recordUndo(it);
2155 ins.rename(newname);
2160 if (it->lyxCode() == INCLUDE_CODE) {
2161 // get buffer of external file
2162 InsetInclude const & ins =
2163 static_cast<InsetInclude const &>(*it);
2164 Buffer * child = ins.getChildBuffer();
2167 child->dispatch(func, dr);
2172 dr.screenUpdate(Update::Force);
2173 dr.forceBufferUpdate();
2178 case LFUN_BUFFER_PRINT: {
2179 // we'll assume there's a problem until we succeed
2181 string target = func.getArg(0);
2182 string target_name = func.getArg(1);
2183 string command = func.getArg(2);
2186 || target_name.empty()
2187 || command.empty()) {
2188 LYXERR0("Unable to parse " << func.argument());
2189 docstring const msg =
2190 bformat(_("Unable to parse \"%1$s\""), func.argument());
2194 if (target != "printer" && target != "file") {
2195 LYXERR0("Unrecognized target \"" << target << '"');
2196 docstring const msg =
2197 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2202 bool const update_unincluded =
2203 params().maintain_unincluded_children
2204 && !params().getIncludedChildren().empty();
2205 if (!doExport("dvi", true, update_unincluded)) {
2206 showPrintError(absFileName());
2207 dr.setMessage(_("Error exporting to DVI."));
2211 // Push directory path.
2212 string const path = temppath();
2213 // Prevent the compiler from optimizing away p
2217 // there are three cases here:
2218 // 1. we print to a file
2219 // 2. we print directly to a printer
2220 // 3. we print using a spool command (print to file first)
2223 string const dviname = changeExtension(latexName(true), "dvi");
2225 if (target == "printer") {
2226 if (!lyxrc.print_spool_command.empty()) {
2227 // case 3: print using a spool
2228 string const psname = changeExtension(dviname,".ps");
2229 command += ' ' + lyxrc.print_to_file
2232 + quoteName(dviname);
2234 string command2 = lyxrc.print_spool_command + ' ';
2235 if (target_name != "default") {
2236 command2 += lyxrc.print_spool_printerprefix
2240 command2 += quoteName(psname);
2242 // If successful, then spool command
2243 res = one.startscript(Systemcall::Wait, command);
2246 // If there's no GUI, we have to wait on this command. Otherwise,
2247 // LyX deletes the temporary directory, and with it the spooled
2248 // file, before it can be printed!!
2249 Systemcall::Starttype stype = use_gui ?
2250 Systemcall::DontWait : Systemcall::Wait;
2251 res = one.startscript(stype, command2);
2254 // case 2: print directly to a printer
2255 if (target_name != "default")
2256 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2258 Systemcall::Starttype stype = use_gui ?
2259 Systemcall::DontWait : Systemcall::Wait;
2260 res = one.startscript(stype, command + quoteName(dviname));
2264 // case 1: print to a file
2265 FileName const filename(makeAbsPath(target_name, filePath()));
2266 FileName const dvifile(makeAbsPath(dviname, path));
2267 if (filename.exists()) {
2268 docstring text = bformat(
2269 _("The file %1$s already exists.\n\n"
2270 "Do you want to overwrite that file?"),
2271 makeDisplayPath(filename.absFileName()));
2272 if (Alert::prompt(_("Overwrite file?"),
2273 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2276 command += ' ' + lyxrc.print_to_file
2277 + quoteName(filename.toFilesystemEncoding())
2279 + quoteName(dvifile.toFilesystemEncoding());
2281 Systemcall::Starttype stype = use_gui ?
2282 Systemcall::DontWait : Systemcall::Wait;
2283 res = one.startscript(stype, command);
2289 dr.setMessage(_("Error running external commands."));
2290 showPrintError(absFileName());
2295 case LFUN_BUFFER_LANGUAGE: {
2296 Language const * oldL = params().language;
2297 Language const * newL = languages.getLanguage(argument);
2298 if (!newL || oldL == newL)
2300 if (oldL->rightToLeft() == newL->rightToLeft() && !isMultiLingual()) {
2301 changeLanguage(oldL, newL);
2302 dr.forceBufferUpdate();
2311 dr.dispatched(dispatched);
2312 undo().endUndoGroup();
2316 void Buffer::changeLanguage(Language const * from, Language const * to)
2318 LASSERT(from, /**/);
2321 for_each(par_iterator_begin(),
2323 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2327 bool Buffer::isMultiLingual() const
2329 ParConstIterator end = par_iterator_end();
2330 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2331 if (it->isMultiLingual(params()))
2338 std::set<Language const *> Buffer::getLanguages() const
2340 std::set<Language const *> languages;
2341 getLanguages(languages);
2346 void Buffer::getLanguages(std::set<Language const *> & languages) const
2348 ParConstIterator end = par_iterator_end();
2349 // add the buffer language, even if it's not actively used
2350 languages.insert(language());
2351 // iterate over the paragraphs
2352 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2353 it->getLanguages(languages);
2355 ListOfBuffers clist = getDescendents();
2356 ListOfBuffers::const_iterator cit = clist.begin();
2357 ListOfBuffers::const_iterator const cen = clist.end();
2358 for (; cit != cen; ++cit)
2359 (*cit)->getLanguages(languages);
2363 DocIterator Buffer::getParFromID(int const id) const
2365 Buffer * buf = const_cast<Buffer *>(this);
2367 // John says this is called with id == -1 from undo
2368 lyxerr << "getParFromID(), id: " << id << endl;
2369 return doc_iterator_end(buf);
2372 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2373 if (it.paragraph().id() == id)
2376 return doc_iterator_end(buf);
2380 bool Buffer::hasParWithID(int const id) const
2382 return !getParFromID(id).atEnd();
2386 ParIterator Buffer::par_iterator_begin()
2388 return ParIterator(doc_iterator_begin(this));
2392 ParIterator Buffer::par_iterator_end()
2394 return ParIterator(doc_iterator_end(this));
2398 ParConstIterator Buffer::par_iterator_begin() const
2400 return ParConstIterator(doc_iterator_begin(this));
2404 ParConstIterator Buffer::par_iterator_end() const
2406 return ParConstIterator(doc_iterator_end(this));
2410 Language const * Buffer::language() const
2412 return params().language;
2416 docstring const Buffer::B_(string const & l10n) const
2418 return params().B_(l10n);
2422 bool Buffer::isClean() const
2424 return d->lyx_clean;
2428 bool Buffer::isExternallyModified(CheckMethod method) const
2430 LASSERT(d->filename.exists(), /**/);
2431 // if method == timestamp, check timestamp before checksum
2432 return (method == checksum_method
2433 || d->timestamp_ != d->filename.lastModified())
2434 && d->checksum_ != d->filename.checksum();
2438 void Buffer::saveCheckSum() const
2440 FileName const & file = d->filename;
2441 if (file.exists()) {
2442 d->timestamp_ = file.lastModified();
2443 d->checksum_ = file.checksum();
2445 // in the case of save to a new file.
2452 void Buffer::markClean() const
2454 if (!d->lyx_clean) {
2455 d->lyx_clean = true;
2458 // if the .lyx file has been saved, we don't need an
2460 d->bak_clean = true;
2461 d->undo_.markDirty();
2465 void Buffer::setUnnamed(bool flag)
2471 bool Buffer::isUnnamed() const
2478 /// Don't check unnamed, here: isInternal() is used in
2479 /// newBuffer(), where the unnamed flag has not been set by anyone
2480 /// yet. Also, for an internal buffer, there should be no need for
2481 /// retrieving fileName() nor for checking if it is unnamed or not.
2482 bool Buffer::isInternal() const
2484 return fileName().extension() == "internal";
2488 void Buffer::markDirty()
2491 d->lyx_clean = false;
2494 d->bak_clean = false;
2496 DepClean::iterator it = d->dep_clean.begin();
2497 DepClean::const_iterator const end = d->dep_clean.end();
2499 for (; it != end; ++it)
2504 FileName Buffer::fileName() const
2510 string Buffer::absFileName() const
2512 return d->filename.absFileName();
2516 string Buffer::filePath() const
2518 return d->filename.onlyPath().absFileName() + "/";
2522 bool Buffer::isReadonly() const
2524 return d->read_only;
2528 void Buffer::setParent(Buffer const * buffer)
2530 // Avoids recursive include.
2531 d->setParent(buffer == this ? 0 : buffer);
2536 Buffer const * Buffer::parent() const
2542 ListOfBuffers Buffer::allRelatives() const
2544 ListOfBuffers lb = masterBuffer()->getDescendents();
2545 lb.push_front(const_cast<Buffer *>(this));
2550 Buffer const * Buffer::masterBuffer() const
2552 // FIXME Should be make sure we are not in some kind
2553 // of recursive include? A -> B -> A will crash this.
2554 Buffer const * const pbuf = d->parent();
2558 return pbuf->masterBuffer();
2562 bool Buffer::isChild(Buffer * child) const
2564 return d->children_positions.find(child) != d->children_positions.end();
2568 DocIterator Buffer::firstChildPosition(Buffer const * child)
2570 Impl::BufferPositionMap::iterator it;
2571 it = d->children_positions.find(child);
2572 if (it == d->children_positions.end())
2573 return DocIterator(this);
2578 bool Buffer::hasChildren() const
2580 return !d->children_positions.empty();
2584 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
2586 // loop over children
2587 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2588 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2589 for (; it != end; ++it) {
2590 Buffer * child = const_cast<Buffer *>(it->first);
2592 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
2593 if (bit != clist.end())
2595 clist.push_back(child);
2597 // there might be grandchildren
2598 child->collectChildren(clist, true);
2603 ListOfBuffers Buffer::getChildren() const
2606 collectChildren(v, false);
2611 ListOfBuffers Buffer::getDescendents() const
2614 collectChildren(v, true);
2619 template<typename M>
2620 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
2625 typename M::const_iterator it = m.lower_bound(x);
2626 if (it == m.begin())
2634 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
2635 DocIterator const & pos) const
2637 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2639 // if paragraphs have no macro context set, pos will be empty
2643 // we haven't found anything yet
2644 DocIterator bestPos = owner_->par_iterator_begin();
2645 MacroData const * bestData = 0;
2647 // find macro definitions for name
2648 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
2649 if (nameIt != macros.end()) {
2650 // find last definition in front of pos or at pos itself
2651 PositionScopeMacroMap::const_iterator it
2652 = greatest_below(nameIt->second, pos);
2653 if (it != nameIt->second.end()) {
2655 // scope ends behind pos?
2656 if (pos < it->second.first) {
2657 // Looks good, remember this. If there
2658 // is no external macro behind this,
2659 // we found the right one already.
2660 bestPos = it->first;
2661 bestData = &it->second.second;
2665 // try previous macro if there is one
2666 if (it == nameIt->second.begin())
2673 // find macros in included files
2674 PositionScopeBufferMap::const_iterator it
2675 = greatest_below(position_to_children, pos);
2676 if (it == position_to_children.end())
2677 // no children before
2681 // do we know something better (i.e. later) already?
2682 if (it->first < bestPos )
2685 // scope ends behind pos?
2686 if (pos < it->second.first
2687 && (cloned_buffer_ ||
2688 theBufferList().isLoaded(it->second.second))) {
2689 // look for macro in external file
2691 MacroData const * data
2692 = it->second.second->getMacro(name, false);
2695 bestPos = it->first;
2701 // try previous file if there is one
2702 if (it == position_to_children.begin())
2707 // return the best macro we have found
2712 MacroData const * Buffer::getMacro(docstring const & name,
2713 DocIterator const & pos, bool global) const
2718 // query buffer macros
2719 MacroData const * data = d->getBufferMacro(name, pos);
2723 // If there is a master buffer, query that
2724 Buffer const * const pbuf = d->parent();
2726 d->macro_lock = true;
2727 MacroData const * macro = pbuf->getMacro(
2728 name, *this, false);
2729 d->macro_lock = false;
2735 data = MacroTable::globalMacros().get(name);
2744 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2746 // set scope end behind the last paragraph
2747 DocIterator scope = par_iterator_begin();
2748 scope.pit() = scope.lastpit() + 1;
2750 return getMacro(name, scope, global);
2754 MacroData const * Buffer::getMacro(docstring const & name,
2755 Buffer const & child, bool global) const
2757 // look where the child buffer is included first
2758 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2759 if (it == d->children_positions.end())
2762 // check for macros at the inclusion position
2763 return getMacro(name, it->second, global);
2767 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
2769 pit_type const lastpit = it.lastpit();
2771 // look for macros in each paragraph
2772 while (it.pit() <= lastpit) {
2773 Paragraph & par = it.paragraph();
2775 // iterate over the insets of the current paragraph
2776 InsetList const & insets = par.insetList();
2777 InsetList::const_iterator iit = insets.begin();
2778 InsetList::const_iterator end = insets.end();
2779 for (; iit != end; ++iit) {
2780 it.pos() = iit->pos;
2782 // is it a nested text inset?
2783 if (iit->inset->asInsetText()) {
2784 // Inset needs its own scope?
2785 InsetText const * itext = iit->inset->asInsetText();
2786 bool newScope = itext->isMacroScope();
2788 // scope which ends just behind the inset
2789 DocIterator insetScope = it;
2792 // collect macros in inset
2793 it.push_back(CursorSlice(*iit->inset));
2794 updateMacros(it, newScope ? insetScope : scope);
2799 if (iit->inset->asInsetTabular()) {
2800 CursorSlice slice(*iit->inset);
2801 size_t const numcells = slice.nargs();
2802 for (; slice.idx() < numcells; slice.forwardIdx()) {
2803 it.push_back(slice);
2804 updateMacros(it, scope);
2810 // is it an external file?
2811 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2812 // get buffer of external file
2813 InsetInclude const & inset =
2814 static_cast<InsetInclude const &>(*iit->inset);
2816 Buffer * child = inset.getChildBuffer();
2821 // register its position, but only when it is
2822 // included first in the buffer
2823 if (children_positions.find(child) ==
2824 children_positions.end())
2825 children_positions[child] = it;
2827 // register child with its scope
2828 position_to_children[it] = Impl::ScopeBuffer(scope, child);
2832 InsetMath * im = iit->inset->asInsetMath();
2833 if (doing_export && im) {
2834 InsetMathHull * hull = im->asHullInset();
2836 hull->recordLocation(it);
2839 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2843 MathMacroTemplate & macroTemplate =
2844 *iit->inset->asInsetMath()->asMacroTemplate();
2845 MacroContext mc(owner_, it);
2846 macroTemplate.updateToContext(mc);
2849 bool valid = macroTemplate.validMacro();
2850 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2851 // then the BufferView's cursor will be invalid in
2852 // some cases which leads to crashes.
2857 // FIXME (Abdel), I don't understandt why we pass 'it' here
2858 // instead of 'macroTemplate' defined above... is this correct?
2859 macros[macroTemplate.name()][it] =
2860 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
2870 void Buffer::updateMacros() const
2875 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2877 // start with empty table
2879 d->children_positions.clear();
2880 d->position_to_children.clear();
2882 // Iterate over buffer, starting with first paragraph
2883 // The scope must be bigger than any lookup DocIterator
2884 // later. For the global lookup, lastpit+1 is used, hence
2885 // we use lastpit+2 here.
2886 DocIterator it = par_iterator_begin();
2887 DocIterator outerScope = it;
2888 outerScope.pit() = outerScope.lastpit() + 2;
2889 d->updateMacros(it, outerScope);
2893 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
2895 InsetIterator it = inset_iterator_begin(inset());
2896 InsetIterator const end = inset_iterator_end(inset());
2897 for (; it != end; ++it) {
2898 if (it->lyxCode() == BRANCH_CODE) {
2899 InsetBranch & br = static_cast<InsetBranch &>(*it);
2900 docstring const name = br.branch();
2901 if (!from_master && !params().branchlist().find(name))
2902 result.push_back(name);
2903 else if (from_master && !masterBuffer()->params().branchlist().find(name))
2904 result.push_back(name);
2907 if (it->lyxCode() == INCLUDE_CODE) {
2908 // get buffer of external file
2909 InsetInclude const & ins =
2910 static_cast<InsetInclude const &>(*it);
2911 Buffer * child = ins.getChildBuffer();
2914 child->getUsedBranches(result, true);
2917 // remove duplicates
2922 void Buffer::updateMacroInstances() const
2924 LYXERR(Debug::MACROS, "updateMacroInstances for "
2925 << d->filename.onlyFileName());
2926 DocIterator it = doc_iterator_begin(this);
2928 DocIterator const end = doc_iterator_end(this);
2929 for (; it != end; it.forwardInset()) {
2930 // look for MathData cells in InsetMathNest insets
2931 InsetMath * minset = it.nextInset()->asInsetMath();
2935 // update macro in all cells of the InsetMathNest
2936 DocIterator::idx_type n = minset->nargs();
2937 MacroContext mc = MacroContext(this, it);
2938 for (DocIterator::idx_type i = 0; i < n; ++i) {
2939 MathData & data = minset->cell(i);
2940 data.updateMacros(0, mc);
2946 void Buffer::listMacroNames(MacroNameSet & macros) const
2951 d->macro_lock = true;
2953 // loop over macro names
2954 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2955 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2956 for (; nameIt != nameEnd; ++nameIt)
2957 macros.insert(nameIt->first);
2959 // loop over children
2960 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2961 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2962 for (; it != end; ++it)
2963 it->first->listMacroNames(macros);
2966 Buffer const * const pbuf = d->parent();
2968 pbuf->listMacroNames(macros);
2970 d->macro_lock = false;
2974 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2976 Buffer const * const pbuf = d->parent();
2981 pbuf->listMacroNames(names);
2984 MacroNameSet::iterator it = names.begin();
2985 MacroNameSet::iterator end = names.end();
2986 for (; it != end; ++it) {
2988 MacroData const * data =
2989 pbuf->getMacro(*it, *this, false);
2991 macros.insert(data);
2993 // we cannot access the original MathMacroTemplate anymore
2994 // here to calls validate method. So we do its work here manually.
2995 // FIXME: somehow make the template accessible here.
2996 if (data->optionals() > 0)
2997 features.require("xargs");
3003 Buffer::References & Buffer::references(docstring const & label)
3006 return const_cast<Buffer *>(masterBuffer())->references(label);
3008 RefCache::iterator it = d->ref_cache_.find(label);
3009 if (it != d->ref_cache_.end())
3010 return it->second.second;
3012 static InsetLabel const * dummy_il = 0;
3013 static References const dummy_refs;
3014 it = d->ref_cache_.insert(
3015 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3016 return it->second.second;
3020 Buffer::References const & Buffer::references(docstring const & label) const
3022 return const_cast<Buffer *>(this)->references(label);
3026 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3028 masterBuffer()->d->ref_cache_[label].first = il;
3032 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3034 return masterBuffer()->d->ref_cache_[label].first;
3038 void Buffer::clearReferenceCache() const
3041 d->ref_cache_.clear();
3045 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
3048 //FIXME: This does not work for child documents yet.
3049 LASSERT(code == CITE_CODE, /**/);
3051 reloadBibInfoCache();
3053 // Check if the label 'from' appears more than once
3054 BiblioInfo const & keys = masterBibInfo();
3055 BiblioInfo::const_iterator bit = keys.begin();
3056 BiblioInfo::const_iterator bend = keys.end();
3057 vector<docstring> labels;
3059 for (; bit != bend; ++bit)
3061 labels.push_back(bit->first);
3063 if (count(labels.begin(), labels.end(), from) > 1)
3066 string const paramName = "key";
3067 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3068 if (it->lyxCode() == code) {
3069 InsetCommand * inset = it->asInsetCommand();
3072 docstring const oldValue = inset->getParam(paramName);
3073 if (oldValue == from)
3074 inset->setParam(paramName, to);
3080 void Buffer::getSourceCode(odocstream & os, string const format,
3081 pit_type par_begin, pit_type par_end,
3082 bool full_source) const
3084 OutputParams runparams(¶ms().encoding());
3085 runparams.nice = true;
3086 runparams.flavor = getOutputFlavor(format);
3087 runparams.linelen = lyxrc.plaintext_linelen;
3088 // No side effect of file copying and image conversion
3089 runparams.dryrun = true;
3092 os << "% " << _("Preview source code") << "\n\n";
3094 d->texrow.newline();
3095 d->texrow.newline();
3097 writeDocBookSource(os, absFileName(), runparams, false);
3098 else if (runparams.flavor == OutputParams::HTML)
3099 writeLyXHTMLSource(os, runparams, false);
3101 // latex or literate
3102 otexstream ots(os, d->texrow);
3103 writeLaTeXSource(ots, string(), runparams, true, true);
3106 runparams.par_begin = par_begin;
3107 runparams.par_end = par_end;
3108 if (par_begin + 1 == par_end) {
3110 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3114 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3115 convert<docstring>(par_begin),
3116 convert<docstring>(par_end - 1))
3123 // output paragraphs
3125 docbookParagraphs(text(), *this, os, runparams);
3126 else if (runparams.flavor == OutputParams::HTML) {
3128 xhtmlParagraphs(text(), *this, xs, runparams);
3130 // latex or literate
3131 otexstream ots(os, texrow);
3132 latexParagraphs(*this, text(), ots, runparams);
3138 ErrorList & Buffer::errorList(string const & type) const
3140 static ErrorList emptyErrorList;
3141 map<string, ErrorList>::iterator it = d->errorLists.find(type);
3142 if (it == d->errorLists.end())
3143 return emptyErrorList;
3149 void Buffer::updateTocItem(std::string const & type,
3150 DocIterator const & dit) const
3153 d->gui_->updateTocItem(type, dit);
3157 void Buffer::structureChanged() const
3160 d->gui_->structureChanged();
3164 void Buffer::errors(string const & err, bool from_master) const
3167 d->gui_->errors(err, from_master);
3171 void Buffer::message(docstring const & msg) const
3174 d->gui_->message(msg);
3178 void Buffer::setBusy(bool on) const
3181 d->gui_->setBusy(on);
3185 void Buffer::updateTitles() const
3188 d->wa_->updateTitles();
3192 void Buffer::resetAutosaveTimers() const
3195 d->gui_->resetAutosaveTimers();
3199 bool Buffer::hasGuiDelegate() const
3205 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3214 class AutoSaveBuffer : public ForkedProcess {
3217 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3218 : buffer_(buffer), fname_(fname) {}
3220 virtual shared_ptr<ForkedProcess> clone() const
3222 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3227 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3228 from_utf8(fname_.absFileName())));
3229 return run(DontWait);
3233 virtual int generateChild();
3235 Buffer const & buffer_;
3240 int AutoSaveBuffer::generateChild()
3242 #if defined(__APPLE__)
3243 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3244 * We should use something else like threads.
3246 * Since I do not know how to determine at run time what is the OS X
3247 * version, I just disable forking altogether for now (JMarc)
3249 pid_t const pid = -1;
3251 // tmp_ret will be located (usually) in /tmp
3252 // will that be a problem?
3253 // Note that this calls ForkedCalls::fork(), so it's
3254 // ok cross-platform.
3255 pid_t const pid = fork();
3256 // If you want to debug the autosave
3257 // you should set pid to -1, and comment out the fork.
3258 if (pid != 0 && pid != -1)
3262 // pid = -1 signifies that lyx was unable
3263 // to fork. But we will do the save
3265 bool failed = false;
3266 FileName const tmp_ret = FileName::tempName("lyxauto");
3267 if (!tmp_ret.empty()) {
3268 buffer_.writeFile(tmp_ret);
3269 // assume successful write of tmp_ret
3270 if (!tmp_ret.moveTo(fname_))
3276 // failed to write/rename tmp_ret so try writing direct
3277 if (!buffer_.writeFile(fname_)) {
3278 // It is dangerous to do this in the child,
3279 // but safe in the parent, so...
3280 if (pid == -1) // emit message signal.
3281 buffer_.message(_("Autosave failed!"));
3285 if (pid == 0) // we are the child so...
3294 FileName Buffer::getEmergencyFileName() const
3296 return FileName(d->filename.absFileName() + ".emergency");
3300 FileName Buffer::getAutosaveFileName() const
3302 // if the document is unnamed try to save in the backup dir, else
3303 // in the default document path, and as a last try in the filePath,
3304 // which will most often be the temporary directory
3307 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3308 : lyxrc.backupdir_path;
3309 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3312 string const fname = "#" + d->filename.onlyFileName() + "#";
3314 return makeAbsPath(fname, fpath);
3318 void Buffer::removeAutosaveFile() const
3320 FileName const f = getAutosaveFileName();
3326 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3328 FileName const newauto = getAutosaveFileName();
3330 if (newauto != oldauto && oldauto.exists())
3331 if (!oldauto.moveTo(newauto))
3332 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3336 bool Buffer::autoSave() const
3338 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
3339 if (buf->d->bak_clean || isReadonly())
3342 message(_("Autosaving current document..."));
3343 buf->d->bak_clean = true;
3345 FileName const fname = getAutosaveFileName();
3346 if (d->cloned_buffer_) {
3347 // If this buffer is cloned, we assume that
3348 // we are running in a separate thread already.
3349 FileName const tmp_ret = FileName::tempName("lyxauto");
3350 if (!tmp_ret.empty()) {
3352 // assume successful write of tmp_ret
3353 if (tmp_ret.moveTo(fname))
3356 // failed to write/rename tmp_ret so try writing direct
3357 return writeFile(fname);
3359 /// This function is deprecated as the frontend needs to take care
3360 /// of cloning the buffer and autosaving it in another thread. It
3361 /// is still here to allow (QT_VERSION < 0x040400).
3362 AutoSaveBuffer autosave(*this, fname);
3369 string Buffer::bufferFormat() const
3371 string format = params().documentClass().outputFormat();
3372 if (format == "latex") {
3373 if (params().useNonTeXFonts)
3375 if (params().encoding().package() == Encoding::japanese)
3382 string Buffer::getDefaultOutputFormat() const
3384 if (!params().default_output_format.empty()
3385 && params().default_output_format != "default")
3386 return params().default_output_format;
3388 || params().useNonTeXFonts
3389 || params().encoding().package() == Encoding::japanese) {
3390 vector<Format const *> const formats = exportableFormats(true);
3391 if (formats.empty())
3393 // return the first we find
3394 return formats.front()->name();
3396 return lyxrc.default_view_format;
3400 OutputParams::FLAVOR Buffer::getOutputFlavor(string const format) const
3402 string const dformat = (format.empty() || format == "default") ?
3403 getDefaultOutputFormat() : format;
3404 DefaultFlavorCache::const_iterator it =
3405 default_flavors_.find(dformat);
3407 if (it != default_flavors_.end())
3410 OutputParams::FLAVOR result = OutputParams::LATEX;
3412 if (dformat == "xhtml")
3413 result = OutputParams::HTML;
3415 // Try to determine flavor of default output format
3416 vector<string> backs = backends();
3417 if (find(backs.begin(), backs.end(), dformat) == backs.end()) {
3418 // Get shortest path to format
3419 Graph::EdgePath path;
3420 for (vector<string>::const_iterator it = backs.begin();
3421 it != backs.end(); ++it) {
3422 Graph::EdgePath p = theConverters().getPath(*it, dformat);
3423 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3428 result = theConverters().getFlavor(path);
3431 // cache this flavor
3432 default_flavors_[dformat] = result;
3438 // helper class, to guarantee this gets reset properly
3439 class MarkAsExporting {
3441 MarkAsExporting(Buffer const * buf) : buf_(buf)
3443 LASSERT(buf_, /* */);
3444 buf_->setExportStatus(true);
3448 buf_->setExportStatus(false);
3451 Buffer const * const buf_;
3456 void Buffer::setExportStatus(bool e) const
3458 d->doing_export = e;
3462 bool Buffer::isExporting() const
3464 return d->doing_export;
3468 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3469 bool includeall, string & result_file) const
3471 MarkAsExporting exporting(this);
3472 string backend_format;
3473 OutputParams runparams(¶ms().encoding());
3474 runparams.flavor = OutputParams::LATEX;
3475 runparams.linelen = lyxrc.plaintext_linelen;
3476 runparams.includeall = includeall;
3477 vector<string> backs = backends();
3478 Converters converters = theConverters();
3479 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3480 // Get shortest path to format
3481 converters.buildGraph();
3482 Graph::EdgePath path;
3483 for (vector<string>::const_iterator it = backs.begin();
3484 it != backs.end(); ++it) {
3485 Graph::EdgePath p = converters.getPath(*it, format);
3486 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3487 backend_format = *it;
3492 if (!put_in_tempdir) {
3493 // Only show this alert if this is an export to a non-temporary
3494 // file (not for previewing).
3495 Alert::error(_("Couldn't export file"), bformat(
3496 _("No information for exporting the format %1$s."),
3497 formats.prettyName(format)));
3501 runparams.flavor = converters.getFlavor(path);
3504 backend_format = format;
3505 // FIXME: Don't hardcode format names here, but use a flag
3506 if (backend_format == "pdflatex")
3507 runparams.flavor = OutputParams::PDFLATEX;
3508 else if (backend_format == "luatex")
3509 runparams.flavor = OutputParams::LUATEX;
3510 else if (backend_format == "xetex")
3511 runparams.flavor = OutputParams::XETEX;
3514 string filename = latexName(false);
3515 filename = addName(temppath(), filename);
3516 filename = changeExtension(filename,
3517 formats.extension(backend_format));
3520 updateMacroInstances();
3522 // Plain text backend
3523 if (backend_format == "text") {
3524 runparams.flavor = OutputParams::TEXT;
3525 writePlaintextFile(*this, FileName(filename), runparams);
3528 else if (backend_format == "xhtml") {
3529 runparams.flavor = OutputParams::HTML;
3530 switch (params().html_math_output) {
3531 case BufferParams::MathML:
3532 runparams.math_flavor = OutputParams::MathAsMathML;
3534 case BufferParams::HTML:
3535 runparams.math_flavor = OutputParams::MathAsHTML;
3537 case BufferParams::Images:
3538 runparams.math_flavor = OutputParams::MathAsImages;
3540 case BufferParams::LaTeX:
3541 runparams.math_flavor = OutputParams::MathAsLaTeX;
3544 makeLyXHTMLFile(FileName(filename), runparams);
3545 } else if (backend_format == "lyx")
3546 writeFile(FileName(filename));
3548 else if (isDocBook()) {
3549 runparams.nice = !put_in_tempdir;
3550 makeDocBookFile(FileName(filename), runparams);
3553 else if (backend_format == format) {
3554 runparams.nice = true;
3555 if (!makeLaTeXFile(FileName(filename), string(), runparams))
3557 } else if (!lyxrc.tex_allows_spaces
3558 && contains(filePath(), ' ')) {
3559 Alert::error(_("File name error"),
3560 _("The directory path to the document cannot contain spaces."));
3563 runparams.nice = false;
3564 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
3568 string const error_type = (format == "program")
3569 ? "Build" : bufferFormat();
3570 ErrorList & error_list = d->errorLists[error_type];
3571 string const ext = formats.extension(format);
3572 FileName const tmp_result_file(changeExtension(filename, ext));
3573 bool const success = converters.convert(this, FileName(filename),
3574 tmp_result_file, FileName(absFileName()), backend_format, format,
3577 // Emit the signal to show the error list or copy it back to the
3578 // cloned Buffer so that it can be emitted afterwards.
3579 if (format != backend_format) {
3580 if (d->cloned_buffer_) {
3581 d->cloned_buffer_->d->errorLists[error_type] =
3582 d->errorLists[error_type];
3585 // also to the children, in case of master-buffer-view
3586 ListOfBuffers clist = getDescendents();
3587 ListOfBuffers::const_iterator cit = clist.begin();
3588 ListOfBuffers::const_iterator const cen = clist.end();
3589 for (; cit != cen; ++cit) {
3590 if (d->cloned_buffer_) {
3591 // Enable reverse search by copying back the
3592 // texrow object to the cloned buffer.
3593 // FIXME: this is not thread safe.
3594 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
3595 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
3596 (*cit)->d->errorLists[error_type];
3598 (*cit)->errors(error_type, true);
3602 if (d->cloned_buffer_) {
3603 // Enable reverse dvi or pdf to work by copying back the texrow
3604 // object to the cloned buffer.
3605 // FIXME: There is a possibility of concurrent access to texrow
3606 // here from the main GUI thread that should be securized.
3607 d->cloned_buffer_->d->texrow = d->texrow;
3608 string const error_type = bufferFormat();
3609 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
3615 if (put_in_tempdir) {
3616 result_file = tmp_result_file.absFileName();
3620 result_file = changeExtension(d->exportFileName().absFileName(), ext);
3621 // We need to copy referenced files (e. g. included graphics
3622 // if format == "dvi") to the result dir.
3623 vector<ExportedFile> const files =
3624 runparams.exportdata->externalFiles(format);
3625 string const dest = onlyPath(result_file);
3626 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
3627 : force_overwrite == ALL_FILES;
3628 CopyStatus status = use_force ? FORCE : SUCCESS;
3630 vector<ExportedFile>::const_iterator it = files.begin();
3631 vector<ExportedFile>::const_iterator const en = files.end();
3632 for (; it != en && status != CANCEL; ++it) {
3633 string const fmt = formats.getFormatFromFile(it->sourceName);
3634 status = copyFile(fmt, it->sourceName,
3635 makeAbsPath(it->exportName, dest),
3636 it->exportName, status == FORCE);
3639 if (status == CANCEL) {
3640 message(_("Document export cancelled."));
3641 } else if (tmp_result_file.exists()) {
3642 // Finally copy the main file
3643 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
3644 : force_overwrite != NO_FILES;
3645 if (status == SUCCESS && use_force)
3647 status = copyFile(format, tmp_result_file,
3648 FileName(result_file), result_file,
3650 message(bformat(_("Document exported as %1$s "
3652 formats.prettyName(format),
3653 makeDisplayPath(result_file)));
3655 // This must be a dummy converter like fax (bug 1888)
3656 message(bformat(_("Document exported as %1$s"),
3657 formats.prettyName(format)));
3664 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3665 bool includeall) const
3668 // (1) export with all included children (omit \includeonly)
3669 if (includeall && !doExport(format, put_in_tempdir, true, result_file))
3671 // (2) export with included children only
3672 return doExport(format, put_in_tempdir, false, result_file);
3676 bool Buffer::preview(string const & format, bool includeall) const
3678 MarkAsExporting exporting(this);
3680 // (1) export with all included children (omit \includeonly)
3681 if (includeall && !doExport(format, true, true))
3683 // (2) export with included children only
3684 if (!doExport(format, true, false, result_file))
3686 return formats.view(*this, FileName(result_file), format);
3690 bool Buffer::isExportable(string const & format) const
3692 vector<string> backs = backends();
3693 for (vector<string>::const_iterator it = backs.begin();
3694 it != backs.end(); ++it)
3695 if (theConverters().isReachable(*it, format))
3701 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
3703 vector<string> const backs = backends();
3704 vector<Format const *> result =
3705 theConverters().getReachable(backs[0], only_viewable, true);
3706 for (vector<string>::const_iterator it = backs.begin() + 1;
3707 it != backs.end(); ++it) {
3708 vector<Format const *> r =
3709 theConverters().getReachable(*it, only_viewable, false);
3710 result.insert(result.end(), r.begin(), r.end());
3716 vector<string> Buffer::backends() const
3719 v.push_back(bufferFormat());
3720 // FIXME: Don't hardcode format names here, but use a flag
3721 if (v.back() == "latex") {
3722 v.push_back("pdflatex");
3723 v.push_back("luatex");
3724 v.push_back("xetex");
3725 } else if (v.back() == "xetex")
3726 v.push_back("luatex");
3727 v.push_back("xhtml");
3728 v.push_back("text");
3734 Buffer::ReadStatus Buffer::extractFromVC()
3736 bool const found = LyXVC::file_not_found_hook(d->filename);
3738 return ReadFileNotFound;
3739 if (!d->filename.isReadableFile())
3745 Buffer::ReadStatus Buffer::loadEmergency()
3747 FileName const emergencyFile = getEmergencyFileName();
3748 if (!emergencyFile.exists()
3749 || emergencyFile.lastModified() <= d->filename.lastModified())
3750 return ReadFileNotFound;
3752 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
3753 docstring const text = bformat(_("An emergency save of the document "
3754 "%1$s exists.\n\nRecover emergency save?"), file);
3756 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
3757 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
3763 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
3764 bool const success = (ret_llf == ReadSuccess);
3767 Alert::warning(_("File is read-only"),
3768 bformat(_("An emergency file is successfully loaded, "
3769 "but the original file %1$s is marked read-only. "
3770 "Please make sure to save the document as a different "
3771 "file."), from_utf8(d->filename.absFileName())));
3774 str = _("Document was successfully recovered.");
3776 str = _("Document was NOT successfully recovered.");
3777 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3778 makeDisplayPath(emergencyFile.absFileName()));
3780 int const del_emerg =
3781 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3782 _("&Remove"), _("&Keep"));
3783 if (del_emerg == 0) {
3784 emergencyFile.removeFile();
3786 Alert::warning(_("Emergency file deleted"),
3787 _("Do not forget to save your file now!"), true);
3789 return success ? ReadSuccess : ReadEmergencyFailure;
3792 int const del_emerg =
3793 Alert::prompt(_("Delete emergency file?"),
3794 _("Remove emergency file now?"), 1, 1,
3795 _("&Remove"), _("&Keep"));
3797 emergencyFile.removeFile();
3798 return ReadOriginal;
3808 Buffer::ReadStatus Buffer::loadAutosave()
3810 // Now check if autosave file is newer.
3811 FileName const autosaveFile = getAutosaveFileName();
3812 if (!autosaveFile.exists()
3813 || autosaveFile.lastModified() <= d->filename.lastModified())
3814 return ReadFileNotFound;
3816 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
3817 docstring const text = bformat(_("The backup of the document %1$s "
3818 "is newer.\n\nLoad the backup instead?"), file);
3819 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
3820 _("&Load backup"), _("Load &original"), _("&Cancel"));
3825 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
3826 // the file is not saved if we load the autosave file.
3827 if (ret_llf == ReadSuccess) {
3829 Alert::warning(_("File is read-only"),
3830 bformat(_("A backup file is successfully loaded, "
3831 "but the original file %1$s is marked read-only. "
3832 "Please make sure to save the document as a "
3834 from_utf8(d->filename.absFileName())));
3839 return ReadAutosaveFailure;
3842 // Here we delete the autosave
3843 autosaveFile.removeFile();
3844 return ReadOriginal;
3852 Buffer::ReadStatus Buffer::loadLyXFile()
3854 if (!d->filename.isReadableFile()) {
3855 ReadStatus const ret_rvc = extractFromVC();
3856 if (ret_rvc != ReadSuccess)
3860 ReadStatus const ret_re = loadEmergency();
3861 if (ret_re == ReadSuccess || ret_re == ReadCancel)
3864 ReadStatus const ret_ra = loadAutosave();
3865 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
3868 return loadThisLyXFile(d->filename);
3872 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
3874 return readFile(fn);
3878 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3880 TeXErrors::Errors::const_iterator cit = terr.begin();
3881 TeXErrors::Errors::const_iterator end = terr.end();
3883 for (; cit != end; ++cit) {
3886 int errorRow = cit->error_in_line;
3887 bool found = d->texrow.getIdFromRow(errorRow, id_start,
3893 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
3894 } while (found && id_start == id_end && pos_start == pos_end);
3896 errorList.push_back(ErrorItem(cit->error_desc,
3897 cit->error_text, id_start, pos_start, pos_end));
3902 void Buffer::setBuffersForInsets() const
3904 inset().setBuffer(const_cast<Buffer &>(*this));
3908 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
3910 // Use the master text class also for child documents
3911 Buffer const * const master = masterBuffer();
3912 DocumentClass const & textclass = master->params().documentClass();
3914 // do this only if we are the top-level Buffer
3916 reloadBibInfoCache();
3918 // keep the buffers to be children in this set. If the call from the
3919 // master comes back we can see which of them were actually seen (i.e.
3920 // via an InsetInclude). The remaining ones in the set need still be updated.
3921 static std::set<Buffer const *> bufToUpdate;
3922 if (scope == UpdateMaster) {
3923 // If this is a child document start with the master
3924 if (master != this) {
3925 bufToUpdate.insert(this);
3926 master->updateBuffer(UpdateMaster, utype);
3927 // Do this here in case the master has no gui associated with it. Then,
3928 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3929 if (!master->d->gui_)
3932 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3933 if (bufToUpdate.find(this) == bufToUpdate.end())
3937 // start over the counters in the master
3938 textclass.counters().reset();
3941 // update will be done below for this buffer
3942 bufToUpdate.erase(this);
3944 // update all caches
3945 clearReferenceCache();
3948 Buffer & cbuf = const_cast<Buffer &>(*this);
3950 LASSERT(!text().paragraphs().empty(), /**/);
3953 ParIterator parit = cbuf.par_iterator_begin();
3954 updateBuffer(parit, utype);
3957 // TocBackend update will be done later.
3960 d->bibinfo_cache_valid_ = true;
3961 cbuf.tocBackend().update();
3962 if (scope == UpdateMaster)
3963 cbuf.structureChanged();
3967 static depth_type getDepth(DocIterator const & it)
3969 depth_type depth = 0;
3970 for (size_t i = 0 ; i < it.depth() ; ++i)
3971 if (!it[i].inset().inMathed())
3972 depth += it[i].paragraph().getDepth() + 1;
3973 // remove 1 since the outer inset does not count
3977 static depth_type getItemDepth(ParIterator const & it)
3979 Paragraph const & par = *it;
3980 LabelType const labeltype = par.layout().labeltype;
3982 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3985 // this will hold the lowest depth encountered up to now.
3986 depth_type min_depth = getDepth(it);
3987 ParIterator prev_it = it;
3990 --prev_it.top().pit();
3992 // start of nested inset: go to outer par
3994 if (prev_it.empty()) {
3995 // start of document: nothing to do
4000 // We search for the first paragraph with same label
4001 // that is not more deeply nested.
4002 Paragraph & prev_par = *prev_it;
4003 depth_type const prev_depth = getDepth(prev_it);
4004 if (labeltype == prev_par.layout().labeltype) {
4005 if (prev_depth < min_depth)
4006 return prev_par.itemdepth + 1;
4007 if (prev_depth == min_depth)
4008 return prev_par.itemdepth;
4010 min_depth = min(min_depth, prev_depth);
4011 // small optimization: if we are at depth 0, we won't
4012 // find anything else
4013 if (prev_depth == 0)
4019 static bool needEnumCounterReset(ParIterator const & it)
4021 Paragraph const & par = *it;
4022 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
4023 depth_type const cur_depth = par.getDepth();
4024 ParIterator prev_it = it;
4025 while (prev_it.pit()) {
4026 --prev_it.top().pit();
4027 Paragraph const & prev_par = *prev_it;
4028 if (prev_par.getDepth() <= cur_depth)
4029 return prev_par.layout().labeltype != LABEL_ENUMERATE;
4031 // start of nested inset: reset
4036 // set the label of a paragraph. This includes the counters.
4037 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4039 BufferParams const & bp = owner_->masterBuffer()->params();
4040 DocumentClass const & textclass = bp.documentClass();
4041 Paragraph & par = it.paragraph();
4042 Layout const & layout = par.layout();
4043 Counters & counters = textclass.counters();
4045 if (par.params().startOfAppendix()) {
4046 // FIXME: only the counter corresponding to toplevel
4047 // sectioning should be reset
4049 counters.appendix(true);
4051 par.params().appendix(counters.appendix());
4053 // Compute the item depth of the paragraph
4054 par.itemdepth = getItemDepth(it);
4056 if (layout.margintype == MARGIN_MANUAL
4057 || layout.latextype == LATEX_BIB_ENVIRONMENT) {
4058 if (par.params().labelWidthString().empty())
4059 par.params().labelWidthString(par.expandLabel(layout, bp));
4061 par.params().labelWidthString(docstring());
4064 switch(layout.labeltype) {
4066 if (layout.toclevel <= bp.secnumdepth
4067 && (layout.latextype != LATEX_ENVIRONMENT
4068 || it.text()->isFirstInSequence(it.pit()))) {
4069 if (counters.hasCounter(layout.counter))
4070 counters.step(layout.counter, utype);
4071 par.params().labelString(par.expandLabel(layout, bp));
4073 par.params().labelString(docstring());
4076 case LABEL_ITEMIZE: {
4077 // At some point of time we should do something more
4078 // clever here, like:
4079 // par.params().labelString(
4080 // bp.user_defined_bullet(par.itemdepth).getText());
4081 // for now, use a simple hardcoded label
4082 docstring itemlabel;
4083 switch (par.itemdepth) {
4085 itemlabel = char_type(0x2022);
4088 itemlabel = char_type(0x2013);
4091 itemlabel = char_type(0x2217);
4094 itemlabel = char_type(0x2219); // or 0x00b7
4097 par.params().labelString(itemlabel);
4101 case LABEL_ENUMERATE: {
4102 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4104 switch (par.itemdepth) {
4113 enumcounter += "iv";
4116 // not a valid enumdepth...
4120 // Maybe we have to reset the enumeration counter.
4121 if (needEnumCounterReset(it))
4122 counters.reset(enumcounter);
4123 counters.step(enumcounter, utype);
4125 string const & lang = par.getParLanguage(bp)->code();
4126 par.params().labelString(counters.theCounter(enumcounter, lang));
4131 case LABEL_SENSITIVE: {
4132 string const & type = counters.current_float();
4133 docstring full_label;
4135 full_label = owner_->B_("Senseless!!! ");
4137 docstring name = owner_->B_(textclass.floats().getType(type).name());
4138 if (counters.hasCounter(from_utf8(type))) {
4139 string const & lang = par.getParLanguage(bp)->code();
4140 counters.step(from_utf8(type), utype);
4141 full_label = bformat(from_ascii("%1$s %2$s:"),
4143 counters.theCounter(from_utf8(type), lang));
4145 full_label = bformat(from_ascii("%1$s #:"), name);
4147 par.params().labelString(full_label);
4151 case LABEL_NO_LABEL:
4152 par.params().labelString(docstring());
4156 case LABEL_TOP_ENVIRONMENT:
4157 case LABEL_CENTERED_TOP_ENVIRONMENT:
4160 par.params().labelString(par.expandLabel(layout, bp));
4166 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4168 LASSERT(parit.pit() == 0, /**/);
4170 // Set the position of the text in the buffer to be able
4171 // to resolve macros in it.
4172 parit.text()->setMacrocontextPosition(parit);
4174 depth_type maxdepth = 0;
4175 pit_type const lastpit = parit.lastpit();
4176 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4177 // reduce depth if necessary
4178 parit->params().depth(min(parit->params().depth(), maxdepth));
4179 maxdepth = parit->getMaxDepthAfter();
4181 if (utype == OutputUpdate) {
4182 // track the active counters
4183 // we have to do this for the master buffer, since the local
4184 // buffer isn't tracking anything.
4185 masterBuffer()->params().documentClass().counters().
4186 setActiveLayout(parit->layout());
4189 // set the counter for this paragraph
4190 d->setLabel(parit, utype);
4193 InsetList::const_iterator iit = parit->insetList().begin();
4194 InsetList::const_iterator end = parit->insetList().end();
4195 for (; iit != end; ++iit) {
4196 parit.pos() = iit->pos;
4197 iit->inset->updateBuffer(parit, utype);
4203 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4204 WordLangTuple & word_lang, docstring_list & suggestions) const
4208 suggestions.clear();
4209 word_lang = WordLangTuple();
4210 // OK, we start from here.
4211 DocIterator const end = doc_iterator_end(this);
4212 for (; from != end; from.forwardPos()) {
4213 // We are only interested in text so remove the math CursorSlice.
4214 while (from.inMathed()) {
4218 // If from is at the end of the document (which is possible
4219 // when leaving the mathed) LyX will crash later.
4223 from.paragraph().spellCheck();
4224 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4225 if (SpellChecker::misspelled(res)) {
4230 // Do not increase progress when from == to, otherwise the word
4231 // count will be wrong.
4241 Buffer::ReadStatus Buffer::reload()
4244 // c.f. bug http://www.lyx.org/trac/ticket/6587
4245 removeAutosaveFile();
4246 // e.g., read-only status could have changed due to version control
4247 d->filename.refresh();
4248 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4250 ReadStatus const status = loadLyXFile();
4251 if (status == ReadSuccess) {
4256 message(bformat(_("Document %1$s reloaded."), disp_fn));
4259 message(bformat(_("Could not reload document %1$s."), disp_fn));
4269 bool Buffer::saveAs(FileName const & fn)
4271 FileName const old_name = fileName();
4272 FileName const old_auto = getAutosaveFileName();
4273 bool const old_unnamed = isUnnamed();
4280 // bring the autosave file with us, just in case.
4281 moveAutosaveFile(old_auto);
4282 // validate version control data and
4283 // correct buffer title
4284 lyxvc().file_found_hook(fileName());
4286 // the file has now been saved to the new location.
4287 // we need to check that the locations of child buffers
4289 checkChildBuffers();
4293 // reset the old filename and unnamed state
4294 setFileName(old_name);
4295 setUnnamed(old_unnamed);
4301 // FIXME We could do better here, but it is complicated. What would be
4302 // nice is to offer either (a) to save the child buffer to an appropriate
4303 // location, so that it would "move with the master", or else (b) to update
4304 // the InsetInclude so that it pointed to the same file. But (a) is a bit
4305 // complicated, because the code for this lives in GuiView.
4306 void Buffer::checkChildBuffers()
4308 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4309 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4310 for (; it != en; ++it) {
4311 DocIterator dit = it->second;
4312 Buffer * cbuf = const_cast<Buffer *>(it->first);
4313 if (!cbuf || !theBufferList().isLoaded(cbuf))
4315 Inset * inset = dit.nextInset();
4316 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4317 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4318 docstring const & incfile = inset_inc->getParam("filename");
4319 string oldloc = cbuf->absFileName();
4320 string newloc = makeAbsPath(to_utf8(incfile),
4321 onlyPath(absFileName())).absFileName();
4322 if (oldloc == newloc)
4324 // the location of the child file is incorrect.
4325 Alert::warning(_("Included File Invalid"),
4326 bformat(_("Saving this document to a new location has made the file:\n"
4328 "inaccessible. You will need to update the included filename."),
4329 from_utf8(oldloc)));
4331 inset_inc->setChildBuffer(0);
4333 // invalidate cache of children
4334 d->children_positions.clear();
4335 d->position_to_children.clear();