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 = 413; // rgh: html_css_as_file
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_;
260 /// Indicates whether the bibinfo has changed since the last time
261 /// we ran updateBuffer(), i.e., whether citation labels may need
263 mutable bool cite_labels_valid_;
265 mutable RefCache ref_cache_;
267 /// our Text that should be wrapped in an InsetText
270 /// This is here to force the test to be done whenever parent_buffer
272 Buffer const * parent() const {
273 // if parent_buffer is not loaded, then it has been unloaded,
274 // which means that parent_buffer is an invalid pointer. So we
275 // set it to null in that case.
276 // however, the BufferList doesn't know about cloned buffers, so
277 // they will always be regarded as unloaded. in that case, we hope
279 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
281 return parent_buffer;
285 void setParent(Buffer const * pb) {
286 if (parent_buffer == pb)
289 if (!cloned_buffer_ && parent_buffer && pb)
290 LYXERR0("Warning: a buffer should not have two parents!");
292 if (!cloned_buffer_ && parent_buffer) {
293 parent_buffer->invalidateBibfileCache();
294 parent_buffer->invalidateBibinfoCache();
298 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
299 /// This one is useful for preview detached in a thread.
300 Buffer const * cloned_buffer_;
301 /// are we in the process of exporting this buffer?
302 mutable bool doing_export;
305 /// So we can force access via the accessors.
306 mutable Buffer const * parent_buffer;
311 /// Creates the per buffer temporary directory
312 static FileName createBufferTmpDir()
315 // We are in our own directory. Why bother to mangle name?
316 // In fact I wrote this code to circumvent a problematic behaviour
317 // (bug?) of EMX mkstemp().
318 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
319 convert<string>(count++));
321 if (!tmpfl.createDirectory(0777)) {
322 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
323 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
324 from_utf8(tmpfl.absFileName())));
330 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
331 Buffer const * cloned_buffer)
332 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
333 read_only(readonly_), filename(file), file_fully_loaded(false),
334 toc_backend(owner), macro_lock(false), timestamp_(0),
335 checksum_(0), wa_(0), gui_(0), undo_(*owner), bibinfo_cache_valid_(false),
336 bibfile_cache_valid_(false), cite_labels_valid_(false),
337 cloned_buffer_(cloned_buffer), doing_export(false), parent_buffer(0)
339 if (!cloned_buffer_) {
340 temppath = createBufferTmpDir();
341 lyxvc.setBuffer(owner_);
343 wa_ = new frontend::WorkAreaManager;
346 temppath = cloned_buffer_->d->temppath;
347 file_fully_loaded = true;
348 params = cloned_buffer_->d->params;
349 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
350 bibinfo_ = cloned_buffer_->d->bibinfo_;
351 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
352 bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
353 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
354 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
358 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
359 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
361 LYXERR(Debug::INFO, "Buffer::Buffer()");
363 d->inset = new InsetText(*cloned_buffer->d->inset);
364 d->inset->setBuffer(*this);
365 // FIXME: optimize this loop somewhat, maybe by creating a new
366 // general recursive Inset::setId().
367 DocIterator it = doc_iterator_begin(this);
368 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
369 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
370 it.paragraph().setId(cloned_it.paragraph().id());
372 d->inset = new InsetText(this);
373 d->inset->setAutoBreakRows(true);
374 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
380 LYXERR(Debug::INFO, "Buffer::~Buffer()");
381 // here the buffer should take care that it is
382 // saved properly, before it goes into the void.
384 // GuiView already destroyed
388 // No need to do additional cleanups for internal buffer.
393 // loop over children
394 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
395 Impl::BufferPositionMap::iterator end = d->children_positions.end();
396 for (; it != end; ++it) {
397 Buffer * child = const_cast<Buffer *>(it->first);
398 if (d->cloned_buffer_)
400 // The child buffer might have been closed already.
401 else if (theBufferList().isLoaded(child))
402 theBufferList().releaseChild(this, child);
406 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
407 msg += emergencyWrite();
408 Alert::warning(_("Attempting to close changed document!"), msg);
411 // clear references to children in macro tables
412 d->children_positions.clear();
413 d->position_to_children.clear();
415 if (!d->cloned_buffer_ && !d->temppath.destroyDirectory()) {
416 Alert::warning(_("Could not remove temporary directory"),
417 bformat(_("Could not remove the temporary directory %1$s"),
418 from_utf8(d->temppath.absFileName())));
428 Buffer * Buffer::clone() const
431 masterBuffer()->clone(bufmap);
432 BufferMap::iterator it = bufmap.find(this);
433 LASSERT(it != bufmap.end(), return 0);
438 void Buffer::clone(BufferMap & bufmap) const
440 // have we already been cloned?
441 if (bufmap.find(this) != bufmap.end())
444 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
445 bufmap[this] = buffer_clone;
446 buffer_clone->d->macro_lock = true;
447 buffer_clone->d->children_positions.clear();
448 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
449 // math macro caches need to be rethought and simplified.
450 // I am not sure wether we should handle Buffer cloning here or in BufferList.
451 // Right now BufferList knows nothing about buffer clones.
452 Impl::PositionScopeBufferMap::iterator it = d->position_to_children.begin();
453 Impl::PositionScopeBufferMap::iterator end = d->position_to_children.end();
454 for (; it != end; ++it) {
455 DocIterator dit = it->first.clone(buffer_clone);
456 dit.setBuffer(buffer_clone);
457 Buffer * child = const_cast<Buffer *>(it->second.second);
459 child->clone(bufmap);
460 BufferMap::iterator const bit = bufmap.find(child);
461 LASSERT(bit != bufmap.end(), continue);
462 Buffer * child_clone = bit->second;
464 Inset * inset = dit.nextInset();
465 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
466 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
467 inset_inc->setChildBuffer(child_clone);
468 child_clone->d->setParent(buffer_clone);
469 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
470 buffer_clone->setChild(dit, child_clone);
472 buffer_clone->d->macro_lock = false;
477 bool Buffer::isClone() const
479 return d->cloned_buffer_;
483 void Buffer::changed(bool update_metrics) const
486 d->wa_->redrawAll(update_metrics);
490 frontend::WorkAreaManager & Buffer::workAreaManager() const
492 LASSERT(d->wa_, /**/);
497 Text & Buffer::text() const
499 return d->inset->text();
503 Inset & Buffer::inset() const
509 BufferParams & Buffer::params()
515 BufferParams const & Buffer::params() const
521 ParagraphList & Buffer::paragraphs()
523 return text().paragraphs();
527 ParagraphList const & Buffer::paragraphs() const
529 return text().paragraphs();
533 LyXVC & Buffer::lyxvc()
539 LyXVC const & Buffer::lyxvc() const
545 string const Buffer::temppath() const
547 return d->temppath.absFileName();
551 TexRow & Buffer::texrow()
557 TexRow const & Buffer::texrow() const
563 TocBackend & Buffer::tocBackend() const
565 return d->toc_backend;
569 Undo & Buffer::undo()
575 void Buffer::setChild(DocIterator const & dit, Buffer * child)
577 d->children_positions[child] = dit;
581 string Buffer::latexName(bool const no_path) const
583 FileName latex_name =
584 makeLatexName(d->exportFileName());
585 return no_path ? latex_name.onlyFileName()
586 : latex_name.absFileName();
590 FileName Buffer::Impl::exportFileName() const
592 docstring const branch_suffix =
593 params.branchlist().getFileNameSuffix();
594 if (branch_suffix.empty())
597 string const name = filename.onlyFileNameWithoutExt()
598 + to_utf8(branch_suffix);
599 FileName res(filename.onlyPath().absFileName() + "/" + name);
600 res.changeExtension(filename.extension());
606 string Buffer::logName(LogType * type) const
608 string const filename = latexName(false);
610 if (filename.empty()) {
616 string const path = temppath();
618 FileName const fname(addName(temppath(),
619 onlyFileName(changeExtension(filename,
622 // FIXME: how do we know this is the name of the build log?
623 FileName const bname(
624 addName(path, onlyFileName(
625 changeExtension(filename,
626 formats.extension(params().bufferFormat()) + ".out"))));
628 // Also consider the master buffer log file
629 FileName masterfname = fname;
631 if (masterBuffer() != this) {
632 string const mlogfile = masterBuffer()->logName(&mtype);
633 masterfname = FileName(mlogfile);
636 // If no Latex log or Build log is newer, show Build log
637 if (bname.exists() &&
638 ((!fname.exists() && !masterfname.exists())
639 || (fname.lastModified() < bname.lastModified()
640 && masterfname.lastModified() < bname.lastModified()))) {
641 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
644 return bname.absFileName();
645 // If we have a newer master file log or only a master log, show this
646 } else if (fname != masterfname
647 && (!fname.exists() && (masterfname.exists()
648 || fname.lastModified() < masterfname.lastModified()))) {
649 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
652 return masterfname.absFileName();
654 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
657 return fname.absFileName();
661 void Buffer::setReadonly(bool const flag)
663 if (d->read_only != flag) {
670 void Buffer::setFileName(FileName const & fname)
673 setReadonly(d->filename.isReadOnly());
679 int Buffer::readHeader(Lexer & lex)
681 int unknown_tokens = 0;
683 int begin_header_line = -1;
685 // Initialize parameters that may be/go lacking in header:
686 params().branchlist().clear();
687 params().preamble.erase();
688 params().options.erase();
689 params().master.erase();
690 params().float_placement.erase();
691 params().paperwidth.erase();
692 params().paperheight.erase();
693 params().leftmargin.erase();
694 params().rightmargin.erase();
695 params().topmargin.erase();
696 params().bottommargin.erase();
697 params().headheight.erase();
698 params().headsep.erase();
699 params().footskip.erase();
700 params().columnsep.erase();
701 params().fonts_cjk.erase();
702 params().listings_params.clear();
703 params().clearLayoutModules();
704 params().clearRemovedModules();
705 params().clearIncludedChildren();
706 params().pdfoptions().clear();
707 params().indiceslist().clear();
708 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
709 params().isbackgroundcolor = false;
710 params().fontcolor = lyx::rgbFromHexName("#000000");
711 params().isfontcolor = false;
712 params().notefontcolor = lyx::rgbFromHexName("#cccccc");
713 params().boxbgcolor = lyx::rgbFromHexName("#ff0000");
714 params().html_latex_start.clear();
715 params().html_latex_end.clear();
716 params().html_math_img_scale = 1.0;
717 params().output_sync_macro.erase();
719 for (int i = 0; i < 4; ++i) {
720 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
721 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
724 ErrorList & errorList = d->errorLists["Parse"];
733 if (token == "\\end_header")
737 if (token == "\\begin_header") {
738 begin_header_line = line;
742 LYXERR(Debug::PARSER, "Handling document header token: `"
745 string unknown = params().readToken(lex, token, d->filename.onlyPath());
746 if (!unknown.empty()) {
747 if (unknown[0] != '\\' && token == "\\textclass") {
748 Alert::warning(_("Unknown document class"),
749 bformat(_("Using the default document class, because the "
750 "class %1$s is unknown."), from_utf8(unknown)));
753 docstring const s = bformat(_("Unknown token: "
757 errorList.push_back(ErrorItem(_("Document header error"),
762 if (begin_header_line) {
763 docstring const s = _("\\begin_header is missing");
764 errorList.push_back(ErrorItem(_("Document header error"),
768 params().makeDocumentClass();
770 return unknown_tokens;
775 // changed to be public and have one parameter
776 // Returns true if "\end_document" is not read (Asger)
777 bool Buffer::readDocument(Lexer & lex)
779 ErrorList & errorList = d->errorLists["Parse"];
782 // remove dummy empty par
783 paragraphs().clear();
785 if (!lex.checkFor("\\begin_document")) {
786 docstring const s = _("\\begin_document is missing");
787 errorList.push_back(ErrorItem(_("Document header error"),
793 if (params().outputChanges) {
794 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
795 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
796 LaTeXFeatures::isAvailable("xcolor");
798 if (!dvipost && !xcolorulem) {
799 Alert::warning(_("Changes not shown in LaTeX output"),
800 _("Changes will not be highlighted in LaTeX output, "
801 "because neither dvipost nor xcolor/ulem are installed.\n"
802 "Please install these packages or redefine "
803 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
804 } else if (!xcolorulem) {
805 Alert::warning(_("Changes not shown in LaTeX output"),
806 _("Changes will not be highlighted in LaTeX output "
807 "when using pdflatex, because xcolor and ulem are not installed.\n"
808 "Please install both packages or redefine "
809 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
813 if (!params().master.empty()) {
814 FileName const master_file = makeAbsPath(params().master,
815 onlyPath(absFileName()));
816 if (isLyXFileName(master_file.absFileName())) {
818 checkAndLoadLyXFile(master_file, true);
820 // necessary e.g. after a reload
821 // to re-register the child (bug 5873)
822 // FIXME: clean up updateMacros (here, only
823 // child registering is needed).
824 master->updateMacros();
825 // set master as master buffer, but only
826 // if we are a real child
827 if (master->isChild(this))
829 // if the master is not fully loaded
830 // it is probably just loading this
831 // child. No warning needed then.
832 else if (master->isFullyLoaded())
833 LYXERR0("The master '"
835 << "' assigned to this document ("
837 << ") does not include "
838 "this document. Ignoring the master assignment.");
843 // assure we have a default index
844 params().indiceslist().addDefault(B_("Index"));
847 bool const res = text().read(lex, errorList, d->inset);
849 // inform parent buffer about local macros
851 Buffer const * pbuf = parent();
852 UserMacroSet::const_iterator cit = usermacros.begin();
853 UserMacroSet::const_iterator end = usermacros.end();
854 for (; cit != end; ++cit)
855 pbuf->usermacros.insert(*cit);
859 updateMacroInstances(InternalUpdate);
864 bool Buffer::readString(string const & s)
866 params().compressed = false;
871 FileName const fn = FileName::tempName("Buffer_readString");
874 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
875 if (ret_plf != ReadSuccess)
878 if (file_format != LYX_FORMAT) {
879 // We need to call lyx2lyx, so write the input to a file
880 ofstream os(fn.toFilesystemEncoding().c_str());
884 return readFile(fn) == ReadSuccess;
887 if (readDocument(lex))
893 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
897 if (!lex.setFile(fname)) {
898 Alert::error(_("File Not Found"),
899 bformat(_("Unable to open file `%1$s'."),
900 from_utf8(fn.absFileName())));
901 return ReadFileNotFound;
905 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
906 if (ret_plf != ReadSuccess)
909 if (file_format != LYX_FORMAT) {
911 ReadStatus const ret_clf = convertLyXFormat(fn, tmpFile, file_format);
912 if (ret_clf != ReadSuccess)
914 return readFile(tmpFile);
917 // FIXME: InsetInfo needs to know whether the file is under VCS
918 // during the parse process, so this has to be done before.
919 lyxvc().file_found_hook(d->filename);
921 if (readDocument(lex)) {
922 Alert::error(_("Document format failure"),
923 bformat(_("%1$s ended unexpectedly, which means"
924 " that it is probably corrupted."),
925 from_utf8(fn.absFileName())));
926 return ReadDocumentFailure;
929 d->file_fully_loaded = true;
930 d->read_only = !d->filename.isWritable();
931 params().compressed = d->filename.isZippedFile();
937 bool Buffer::isFullyLoaded() const
939 return d->file_fully_loaded;
943 void Buffer::setFullyLoaded(bool value)
945 d->file_fully_loaded = value;
949 void Buffer::updatePreviews() const
951 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
952 thePreviews().generateBufferPreviews(*this);
956 void Buffer::removePreviews() const
958 thePreviews().removeLoader(*this);
962 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
963 FileName const & fn, int & file_format) const
965 if(!lex.checkFor("\\lyxformat")) {
966 Alert::error(_("Document format failure"),
967 bformat(_("%1$s is not a readable LyX document."),
968 from_utf8(fn.absFileName())));
969 return ReadNoLyXFormat;
975 // LyX formats 217 and earlier were written as 2.17. This corresponds
976 // to files from LyX versions < 1.1.6.3. We just remove the dot in
977 // these cases. See also: www.lyx.org/trac/changeset/1313.
978 size_t dot = tmp_format.find_first_of(".,");
979 if (dot != string::npos)
980 tmp_format.erase(dot, 1);
982 file_format = convert<int>(tmp_format);
987 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
988 FileName & tmpfile, int from_format)
990 tmpfile = FileName::tempName("Buffer_convertLyXFormat");
991 if(tmpfile.empty()) {
992 Alert::error(_("Conversion failed"),
993 bformat(_("%1$s is from a different"
994 " version of LyX, but a temporary"
995 " file for converting it could"
997 from_utf8(fn.absFileName())));
998 return LyX2LyXNoTempFile;
1001 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1002 if (lyx2lyx.empty()) {
1003 Alert::error(_("Conversion script not found"),
1004 bformat(_("%1$s is from a different"
1005 " version of LyX, but the"
1006 " conversion script lyx2lyx"
1007 " could not be found."),
1008 from_utf8(fn.absFileName())));
1009 return LyX2LyXNotFound;
1013 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1014 ostringstream command;
1015 command << os::python()
1016 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1017 << " -t " << convert<string>(LYX_FORMAT)
1018 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
1019 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1020 string const command_str = command.str();
1022 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1024 cmd_ret const ret = runCommand(command_str);
1025 if (ret.first != 0) {
1026 if (from_format < LYX_FORMAT) {
1027 Alert::error(_("Conversion script failed"),
1028 bformat(_("%1$s is from an older version"
1029 " of LyX and the lyx2lyx script"
1030 " failed to convert it."),
1031 from_utf8(fn.absFileName())));
1032 return LyX2LyXOlderFormat;
1034 Alert::error(_("Conversion script failed"),
1035 bformat(_("%1$s is from a newer version"
1036 " of LyX and the lyx2lyx script"
1037 " failed to convert it."),
1038 from_utf8(fn.absFileName())));
1039 return LyX2LyXNewerFormat;
1046 // Should probably be moved to somewhere else: BufferView? GuiView?
1047 bool Buffer::save() const
1049 docstring const file = makeDisplayPath(absFileName(), 20);
1050 d->filename.refresh();
1052 // check the read-only status before moving the file as a backup
1053 if (d->filename.exists()) {
1054 bool const read_only = !d->filename.isWritable();
1056 Alert::warning(_("File is read-only"),
1057 bformat(_("The file %1$s cannot be written because it "
1058 "is marked as read-only."), file));
1063 // ask if the disk file has been externally modified (use checksum method)
1064 if (fileName().exists() && isExternallyModified(checksum_method)) {
1066 bformat(_("Document %1$s has been externally modified. "
1067 "Are you sure you want to overwrite this file?"), file);
1068 int const ret = Alert::prompt(_("Overwrite modified file?"),
1069 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1074 // We don't need autosaves in the immediate future. (Asger)
1075 resetAutosaveTimers();
1077 FileName backupName;
1078 bool madeBackup = false;
1080 // make a backup if the file already exists
1081 if (lyxrc.make_backup && fileName().exists()) {
1082 backupName = FileName(absFileName() + '~');
1083 if (!lyxrc.backupdir_path.empty()) {
1084 string const mangledName =
1085 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1086 backupName = FileName(addName(lyxrc.backupdir_path,
1090 // Except file is symlink do not copy because of #6587.
1091 // Hard links have bad luck.
1092 if (fileName().isSymLink())
1093 madeBackup = fileName().copyTo(backupName);
1095 madeBackup = fileName().moveTo(backupName);
1098 Alert::error(_("Backup failure"),
1099 bformat(_("Cannot create backup file %1$s.\n"
1100 "Please check whether the directory exists and is writable."),
1101 from_utf8(backupName.absFileName())));
1102 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1106 if (writeFile(d->filename)) {
1110 // Saving failed, so backup is not backup
1112 backupName.moveTo(d->filename);
1118 bool Buffer::writeFile(FileName const & fname) const
1120 // FIXME Do we need to do these here? I don't think writing
1121 // the LyX file depends upon it. (RGH)
1123 // updateMacroInstances();
1125 if (d->read_only && fname == d->filename)
1128 bool retval = false;
1130 docstring const str = bformat(_("Saving document %1$s..."),
1131 makeDisplayPath(fname.absFileName()));
1134 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1136 if (params().compressed) {
1137 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1138 retval = ofs && write(ofs);
1140 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1141 retval = ofs && write(ofs);
1145 message(str + _(" could not write file!"));
1150 // removeAutosaveFile();
1153 message(str + _(" done."));
1159 docstring Buffer::emergencyWrite()
1161 // No need to save if the buffer has not changed.
1165 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1167 docstring user_message = bformat(
1168 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1170 // We try to save three places:
1171 // 1) Same place as document. Unless it is an unnamed doc.
1173 string s = absFileName();
1176 if (writeFile(FileName(s))) {
1178 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1179 return user_message;
1181 user_message += " " + _("Save failed! Trying again...\n");
1185 // 2) In HOME directory.
1186 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1188 lyxerr << ' ' << s << endl;
1189 if (writeFile(FileName(s))) {
1191 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1192 return user_message;
1195 user_message += " " + _("Save failed! Trying yet again...\n");
1197 // 3) In "/tmp" directory.
1198 // MakeAbsPath to prepend the current
1199 // drive letter on OS/2
1200 s = addName(package().temp_dir().absFileName(), absFileName());
1202 lyxerr << ' ' << s << endl;
1203 if (writeFile(FileName(s))) {
1205 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1206 return user_message;
1209 user_message += " " + _("Save failed! Bummer. Document is lost.");
1212 return user_message;
1216 bool Buffer::write(ostream & ofs) const
1219 // Use the standard "C" locale for file output.
1220 ofs.imbue(locale::classic());
1223 // The top of the file should not be written by params().
1225 // write out a comment in the top of the file
1226 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1227 << " created this file. For more info see http://www.lyx.org/\n"
1228 << "\\lyxformat " << LYX_FORMAT << "\n"
1229 << "\\begin_document\n";
1231 /// For each author, set 'used' to true if there is a change
1232 /// by this author in the document; otherwise set it to 'false'.
1233 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1234 AuthorList::Authors::const_iterator a_end = params().authors().end();
1235 for (; a_it != a_end; ++a_it)
1236 a_it->setUsed(false);
1238 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1239 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1240 for ( ; it != end; ++it)
1241 it->checkAuthors(params().authors());
1243 // now write out the buffer parameters.
1244 ofs << "\\begin_header\n";
1245 params().writeFile(ofs);
1246 ofs << "\\end_header\n";
1249 ofs << "\n\\begin_body\n";
1251 ofs << "\n\\end_body\n";
1253 // Write marker that shows file is complete
1254 ofs << "\\end_document" << endl;
1256 // Shouldn't really be needed....
1259 // how to check if close went ok?
1260 // Following is an attempt... (BE 20001011)
1262 // good() returns false if any error occured, including some
1263 // formatting error.
1264 // bad() returns true if something bad happened in the buffer,
1265 // which should include file system full errors.
1270 lyxerr << "File was not closed properly." << endl;
1277 bool Buffer::makeLaTeXFile(FileName const & fname,
1278 string const & original_path,
1279 OutputParams const & runparams_in,
1280 bool output_preamble, bool output_body) const
1282 OutputParams runparams = runparams_in;
1284 // This is necessary for LuaTeX/XeTeX with tex fonts.
1285 // See FIXME in BufferParams::encoding()
1286 if (runparams.isFullUnicode())
1287 runparams.encoding = encodings.fromLyXName("utf8-plain");
1289 string const encoding = runparams.encoding->iconvName();
1290 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1293 try { ofs.reset(encoding); }
1294 catch (iconv_codecvt_facet_exception & e) {
1295 lyxerr << "Caught iconv exception: " << e.what() << endl;
1296 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1297 "verify that the support software for your encoding (%1$s) is "
1298 "properly installed"), from_ascii(encoding)));
1301 if (!openFileWrite(ofs, fname))
1304 //TexStream ts(ofs.rdbuf(), &texrow());
1305 ErrorList & errorList = d->errorLists["Export"];
1307 bool failed_export = false;
1308 otexstream os(ofs, d->texrow);
1310 // make sure we are ready to export
1311 // this needs to be done before we validate
1312 // FIXME Do we need to do this all the time? I.e., in children
1313 // of a master we are exporting?
1315 updateMacroInstances(OutputUpdate);
1318 os.texrow().reset();
1319 writeLaTeXSource(os, original_path,
1320 runparams, output_preamble, output_body);
1322 catch (EncodingException & e) {
1323 odocstringstream ods;
1324 ods.put(e.failed_char);
1326 oss << "0x" << hex << e.failed_char << dec;
1327 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1328 " (code point %2$s)"),
1329 ods.str(), from_utf8(oss.str()));
1330 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1331 "representable in the chosen encoding.\n"
1332 "Changing the document encoding to utf8 could help."),
1333 e.par_id, e.pos, e.pos + 1));
1334 failed_export = true;
1336 catch (iconv_codecvt_facet_exception & e) {
1337 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1338 _(e.what()), -1, 0, 0));
1339 failed_export = true;
1341 catch (exception const & e) {
1342 errorList.push_back(ErrorItem(_("conversion failed"),
1343 _(e.what()), -1, 0, 0));
1344 failed_export = true;
1347 lyxerr << "Caught some really weird exception..." << endl;
1353 failed_export = true;
1354 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1358 return !failed_export;
1362 void Buffer::writeLaTeXSource(otexstream & os,
1363 string const & original_path,
1364 OutputParams const & runparams_in,
1365 bool const output_preamble, bool const output_body) const
1367 // The child documents, if any, shall be already loaded at this point.
1369 OutputParams runparams = runparams_in;
1371 // Classify the unicode characters appearing in math insets
1372 Encodings::initUnicodeMath(*this);
1374 // validate the buffer.
1375 LYXERR(Debug::LATEX, " Validating buffer...");
1376 LaTeXFeatures features(*this, params(), runparams);
1378 LYXERR(Debug::LATEX, " Buffer validation done.");
1380 // The starting paragraph of the coming rows is the
1381 // first paragraph of the document. (Asger)
1382 if (output_preamble && runparams.nice) {
1383 os << "%% LyX " << lyx_version << " created this file. "
1384 "For more info, see http://www.lyx.org/.\n"
1385 "%% Do not edit unless you really know what "
1388 LYXERR(Debug::INFO, "lyx document header finished");
1390 // There are a few differences between nice LaTeX and usual files:
1391 // usual is \batchmode and has a
1392 // special input@path to allow the including of figures
1393 // with either \input or \includegraphics (what figinsets do).
1394 // input@path is set when the actual parameter
1395 // original_path is set. This is done for usual tex-file, but not
1396 // for nice-latex-file. (Matthias 250696)
1397 // Note that input@path is only needed for something the user does
1398 // in the preamble, included .tex files or ERT, files included by
1399 // LyX work without it.
1400 if (output_preamble) {
1401 if (!runparams.nice) {
1402 // code for usual, NOT nice-latex-file
1403 os << "\\batchmode\n"; // changed from \nonstopmode
1405 if (!original_path.empty()) {
1407 // We don't know the encoding of inputpath
1408 docstring const inputpath = from_utf8(support::latex_path(original_path));
1409 docstring uncodable_glyphs;
1410 Encoding const * const enc = runparams.encoding;
1412 for (size_t n = 0; n < inputpath.size(); ++n) {
1413 docstring const glyph =
1414 docstring(1, inputpath[n]);
1415 if (enc->latexChar(inputpath[n], true) != glyph) {
1416 LYXERR0("Uncodable character '"
1418 << "' in input path!");
1419 uncodable_glyphs += glyph;
1424 // warn user if we found uncodable glyphs.
1425 if (!uncodable_glyphs.empty()) {
1426 frontend::Alert::warning(_("Uncodable character in file path"),
1427 support::bformat(_("The path of your document\n"
1429 "contains glyphs that are unknown in the\n"
1430 "current document encoding (namely %2$s).\n"
1431 "This will likely result in incomplete output.\n\n"
1432 "Choose an appropriate document encoding (such as utf8)\n"
1433 "or change the file path name."), inputpath, uncodable_glyphs));
1435 os << "\\makeatletter\n"
1436 << "\\def\\input@path{{"
1437 << inputpath << "/}}\n"
1438 << "\\makeatother\n";
1442 // get parent macros (if this buffer has a parent) which will be
1443 // written at the document begin further down.
1444 MacroSet parentMacros;
1445 listParentMacros(parentMacros, features);
1447 runparams.use_polyglossia = features.usePolyglossia();
1448 // Write the preamble
1449 runparams.use_babel = params().writeLaTeX(os, features,
1450 d->filename.onlyPath());
1452 runparams.use_japanese = features.isRequired("japanese");
1458 os << "\\begin{document}\n";
1460 // output the parent macros
1461 MacroSet::iterator it = parentMacros.begin();
1462 MacroSet::iterator end = parentMacros.end();
1463 for (; it != end; ++it) {
1464 int num_lines = (*it)->write(os.os(), true);
1465 os.texrow().newlines(num_lines);
1468 } // output_preamble
1470 os.texrow().start(paragraphs().begin()->id(), 0);
1472 LYXERR(Debug::INFO, "preamble finished, now the body.");
1474 // if we are doing a real file with body, even if this is the
1475 // child of some other buffer, let's cut the link here.
1476 // This happens for example if only a child document is printed.
1477 Buffer const * save_parent = 0;
1478 if (output_preamble) {
1479 save_parent = d->parent();
1484 latexParagraphs(*this, text(), os, runparams);
1486 // Restore the parenthood if needed
1487 if (output_preamble)
1488 d->setParent(save_parent);
1490 // add this just in case after all the paragraphs
1493 if (output_preamble) {
1494 os << "\\end{document}\n";
1495 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1497 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1499 runparams_in.encoding = runparams.encoding;
1501 // Just to be sure. (Asger)
1502 os.texrow().newline();
1504 //for (int i = 0; i<d->texrow.rows(); i++) {
1506 // if (d->texrow.getIdFromRow(i+1,id,pos) && id>0)
1507 // lyxerr << i+1 << ":" << id << ":" << getParFromID(id).paragraph().asString()<<"\n";
1510 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1511 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
1515 void Buffer::makeDocBookFile(FileName const & fname,
1516 OutputParams const & runparams,
1517 bool const body_only) const
1519 LYXERR(Debug::LATEX, "makeDocBookFile...");
1522 if (!openFileWrite(ofs, fname))
1525 // make sure we are ready to export
1526 // this needs to be done before we validate
1528 updateMacroInstances(OutputUpdate);
1530 writeDocBookSource(ofs, fname.absFileName(), runparams, body_only);
1534 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1538 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1539 OutputParams const & runparams,
1540 bool const only_body) const
1542 LaTeXFeatures features(*this, params(), runparams);
1547 DocumentClass const & tclass = params().documentClass();
1548 string const top_element = tclass.latexname();
1551 if (runparams.flavor == OutputParams::XML)
1552 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1555 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1558 if (! tclass.class_header().empty())
1559 os << from_ascii(tclass.class_header());
1560 else if (runparams.flavor == OutputParams::XML)
1561 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1562 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1564 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1566 docstring preamble = from_utf8(params().preamble);
1567 if (runparams.flavor != OutputParams::XML ) {
1568 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1569 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1570 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1571 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1574 string const name = runparams.nice
1575 ? changeExtension(absFileName(), ".sgml") : fname;
1576 preamble += features.getIncludedFiles(name);
1577 preamble += features.getLyXSGMLEntities();
1579 if (!preamble.empty()) {
1580 os << "\n [ " << preamble << " ]";
1585 string top = top_element;
1587 if (runparams.flavor == OutputParams::XML)
1588 top += params().language->code();
1590 top += params().language->code().substr(0, 2);
1593 if (!params().options.empty()) {
1595 top += params().options;
1598 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1599 << " file was created by LyX " << lyx_version
1600 << "\n See http://www.lyx.org/ for more information -->\n";
1602 params().documentClass().counters().reset();
1604 sgml::openTag(os, top);
1606 docbookParagraphs(text(), *this, os, runparams);
1607 sgml::closeTag(os, top_element);
1611 void Buffer::makeLyXHTMLFile(FileName const & fname,
1612 OutputParams const & runparams,
1613 bool const body_only) const
1615 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1618 if (!openFileWrite(ofs, fname))
1621 // make sure we are ready to export
1622 // this has to be done before we validate
1623 updateBuffer(UpdateMaster, OutputUpdate);
1624 updateMacroInstances(OutputUpdate);
1626 writeLyXHTMLSource(ofs, runparams, body_only);
1630 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1634 void Buffer::writeLyXHTMLSource(odocstream & os,
1635 OutputParams const & runparams,
1636 bool const only_body) const
1638 LaTeXFeatures features(*this, params(), runparams);
1640 d->bibinfo_.makeCitationLabels(*this);
1643 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1644 << "<!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"
1645 // FIXME Language should be set properly.
1646 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
1648 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
1649 // FIXME Presumably need to set this right
1650 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1652 docstring const & doctitle = features.htmlTitle();
1654 << (doctitle.empty() ? from_ascii("LyX Document") : doctitle)
1657 os << "\n<!-- Text Class Preamble -->\n"
1658 << features.getTClassHTMLPreamble()
1659 << "\n<!-- Preamble Snippets -->\n"
1660 << from_utf8(features.getPreambleSnippets());
1662 os << "\n<!-- Layout-provided Styles -->\n";
1663 docstring const styleinfo = features.getTClassHTMLStyles();
1664 if (!styleinfo.empty()) {
1665 os << "<style type='text/css'>\n"
1669 os << "</head>\n<body>\n";
1673 params().documentClass().counters().reset();
1674 xhtmlParagraphs(text(), *this, xs, runparams);
1676 os << "</body>\n</html>\n";
1680 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1681 // Other flags: -wall -v0 -x
1682 int Buffer::runChktex()
1686 // get LaTeX-Filename
1687 FileName const path(temppath());
1688 string const name = addName(path.absFileName(), latexName());
1689 string const org_path = filePath();
1691 PathChanger p(path); // path to LaTeX file
1692 message(_("Running chktex..."));
1694 // Generate the LaTeX file if neccessary
1695 OutputParams runparams(¶ms().encoding());
1696 runparams.flavor = OutputParams::LATEX;
1697 runparams.nice = false;
1698 runparams.linelen = lyxrc.plaintext_linelen;
1699 makeLaTeXFile(FileName(name), org_path, runparams);
1702 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
1703 int const res = chktex.run(terr); // run chktex
1706 Alert::error(_("chktex failure"),
1707 _("Could not run chktex successfully."));
1708 } else if (res > 0) {
1709 ErrorList & errlist = d->errorLists["ChkTeX"];
1711 bufferErrors(terr, errlist);
1722 void Buffer::validate(LaTeXFeatures & features) const
1724 params().validate(features);
1726 for_each(paragraphs().begin(), paragraphs().end(),
1727 bind(&Paragraph::validate, _1, ref(features)));
1729 if (lyxerr.debugging(Debug::LATEX)) {
1730 features.showStruct();
1735 void Buffer::getLabelList(vector<docstring> & list) const
1737 // If this is a child document, use the master's list instead.
1739 masterBuffer()->getLabelList(list);
1744 Toc & toc = d->toc_backend.toc("label");
1745 TocIterator toc_it = toc.begin();
1746 TocIterator end = toc.end();
1747 for (; toc_it != end; ++toc_it) {
1748 if (toc_it->depth() == 0)
1749 list.push_back(toc_it->str());
1754 void Buffer::updateBibfilesCache(UpdateScope scope) const
1756 // FIXME This is probably unnecssary, given where we call this.
1757 // If this is a child document, use the parent's cache instead.
1758 if (parent() && scope != UpdateChildOnly) {
1759 masterBuffer()->updateBibfilesCache();
1763 d->bibfiles_cache_.clear();
1764 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1765 if (it->lyxCode() == BIBTEX_CODE) {
1766 InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
1767 support::FileNameList const bibfiles = inset.getBibFiles();
1768 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1771 } else if (it->lyxCode() == INCLUDE_CODE) {
1772 InsetInclude & inset = static_cast<InsetInclude &>(*it);
1773 Buffer const * const incbuf = inset.getChildBuffer();
1776 support::FileNameList const & bibfiles =
1777 incbuf->getBibfilesCache(UpdateChildOnly);
1778 if (!bibfiles.empty()) {
1779 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1785 d->bibfile_cache_valid_ = true;
1786 d->bibinfo_cache_valid_ = false;
1787 d->cite_labels_valid_ = false;
1791 void Buffer::invalidateBibinfoCache() const
1793 d->bibinfo_cache_valid_ = false;
1794 d->cite_labels_valid_ = false;
1795 // also invalidate the cache for the parent buffer
1796 Buffer const * const pbuf = d->parent();
1798 pbuf->invalidateBibinfoCache();
1802 void Buffer::invalidateBibfileCache() const
1804 d->bibfile_cache_valid_ = false;
1805 d->bibinfo_cache_valid_ = false;
1806 d->cite_labels_valid_ = false;
1807 // also invalidate the cache for the parent buffer
1808 Buffer const * const pbuf = d->parent();
1810 pbuf->invalidateBibfileCache();
1814 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1816 // FIXME This is probably unnecessary, given where we call this.
1817 // If this is a child document, use the master's cache instead.
1818 Buffer const * const pbuf = masterBuffer();
1819 if (pbuf != this && scope != UpdateChildOnly)
1820 return pbuf->getBibfilesCache();
1822 if (!d->bibfile_cache_valid_)
1823 this->updateBibfilesCache(scope);
1825 return d->bibfiles_cache_;
1829 BiblioInfo const & Buffer::masterBibInfo() const
1831 Buffer const * const tmp = masterBuffer();
1833 return tmp->masterBibInfo();
1838 void Buffer::checkIfBibInfoCacheIsValid() const
1840 // use the master's cache
1841 Buffer const * const tmp = masterBuffer();
1843 tmp->checkIfBibInfoCacheIsValid();
1847 // compare the cached timestamps with the actual ones.
1848 FileNameList const & bibfiles_cache = getBibfilesCache();
1849 FileNameList::const_iterator ei = bibfiles_cache.begin();
1850 FileNameList::const_iterator en = bibfiles_cache.end();
1851 for (; ei != en; ++ ei) {
1852 time_t lastw = ei->lastModified();
1853 time_t prevw = d->bibfile_status_[*ei];
1854 if (lastw != prevw) {
1855 d->bibinfo_cache_valid_ = false;
1856 d->cite_labels_valid_ = false;
1857 d->bibfile_status_[*ei] = lastw;
1863 void Buffer::reloadBibInfoCache() const
1865 // use the master's cache
1866 Buffer const * const tmp = masterBuffer();
1868 tmp->reloadBibInfoCache();
1872 checkIfBibInfoCacheIsValid();
1873 if (d->bibinfo_cache_valid_)
1876 d->bibinfo_.clear();
1878 d->bibinfo_cache_valid_ = true;
1882 void Buffer::collectBibKeys() const
1884 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1885 it->collectBibKeys(it);
1889 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
1891 Buffer const * tmp = masterBuffer();
1892 BiblioInfo & masterbi = (tmp == this) ?
1893 d->bibinfo_ : tmp->d->bibinfo_;
1894 masterbi.mergeBiblioInfo(bi);
1898 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
1900 Buffer const * tmp = masterBuffer();
1901 BiblioInfo & masterbi = (tmp == this) ?
1902 d->bibinfo_ : tmp->d->bibinfo_;
1907 bool Buffer::citeLabelsValid() const
1909 return masterBuffer()->d->cite_labels_valid_;
1913 bool Buffer::isDepClean(string const & name) const
1915 DepClean::const_iterator const it = d->dep_clean.find(name);
1916 if (it == d->dep_clean.end())
1922 void Buffer::markDepClean(string const & name)
1924 d->dep_clean[name] = true;
1928 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1931 // FIXME? if there is an Buffer LFUN that can be dispatched even
1932 // if internal, put a switch '(cmd.action)' here.
1938 switch (cmd.action()) {
1940 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1941 flag.setOnOff(isReadonly());
1944 // FIXME: There is need for a command-line import.
1945 //case LFUN_BUFFER_IMPORT:
1947 case LFUN_BUFFER_AUTO_SAVE:
1950 case LFUN_BUFFER_EXPORT_CUSTOM:
1951 // FIXME: Nothing to check here?
1954 case LFUN_BUFFER_EXPORT: {
1955 docstring const arg = cmd.argument();
1956 enable = arg == "custom" || params().isExportable(to_utf8(arg));
1958 flag.message(bformat(
1959 _("Don't know how to export to format: %1$s"), arg));
1963 case LFUN_BUFFER_CHKTEX:
1964 enable = params().isLatex() && !lyxrc.chktex_command.empty();
1967 case LFUN_BUILD_PROGRAM:
1968 enable = params().isExportable("program");
1971 case LFUN_BRANCH_ACTIVATE:
1972 case LFUN_BRANCH_DEACTIVATE: {
1973 BranchList const & branchList = params().branchlist();
1974 docstring const branchName = cmd.argument();
1975 enable = !branchName.empty() && branchList.find(branchName);
1979 case LFUN_BRANCH_ADD:
1980 case LFUN_BRANCHES_RENAME:
1981 case LFUN_BUFFER_PRINT:
1982 // if no Buffer is present, then of course we won't be called!
1985 case LFUN_BUFFER_LANGUAGE:
1986 enable = !isReadonly();
1992 flag.setEnabled(enable);
1997 void Buffer::dispatch(string const & command, DispatchResult & result)
1999 return dispatch(lyxaction.lookupFunc(command), result);
2003 // NOTE We can end up here even if we have no GUI, because we are called
2004 // by LyX::exec to handled command-line requests. So we may need to check
2005 // whether we have a GUI or not. The boolean use_gui holds this information.
2006 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2009 // FIXME? if there is an Buffer LFUN that can be dispatched even
2010 // if internal, put a switch '(cmd.action())' here.
2011 dr.dispatched(false);
2014 string const argument = to_utf8(func.argument());
2015 // We'll set this back to false if need be.
2016 bool dispatched = true;
2017 undo().beginUndoGroup();
2019 switch (func.action()) {
2020 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2021 if (lyxvc().inUse())
2022 lyxvc().toggleReadOnly();
2024 setReadonly(!isReadonly());
2027 case LFUN_BUFFER_EXPORT: {
2028 bool success = doExport(argument, false, false);
2029 dr.setError(!success);
2031 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2036 case LFUN_BUILD_PROGRAM:
2037 doExport("program", true, false);
2040 case LFUN_BUFFER_CHKTEX:
2044 case LFUN_BUFFER_EXPORT_CUSTOM: {
2046 string command = split(argument, format_name, ' ');
2047 Format const * format = formats.getFormat(format_name);
2049 lyxerr << "Format \"" << format_name
2050 << "\" not recognized!"
2055 // The name of the file created by the conversion process
2058 // Output to filename
2059 if (format->name() == "lyx") {
2060 string const latexname = latexName(false);
2061 filename = changeExtension(latexname,
2062 format->extension());
2063 filename = addName(temppath(), filename);
2065 if (!writeFile(FileName(filename)))
2069 doExport(format_name, true, false, filename);
2072 // Substitute $$FName for filename
2073 if (!contains(command, "$$FName"))
2074 command = "( " + command + " ) < $$FName";
2075 command = subst(command, "$$FName", filename);
2077 // Execute the command in the background
2079 call.startscript(Systemcall::DontWait, command, filePath());
2083 // FIXME: There is need for a command-line import.
2085 case LFUN_BUFFER_IMPORT:
2090 case LFUN_BUFFER_AUTO_SAVE:
2092 resetAutosaveTimers();
2095 case LFUN_BRANCH_ADD: {
2096 docstring branch_name = func.argument();
2097 if (branch_name.empty()) {
2101 BranchList & branch_list = params().branchlist();
2102 vector<docstring> const branches =
2103 getVectorFromString(branch_name, branch_list.separator());
2105 for (vector<docstring>::const_iterator it = branches.begin();
2106 it != branches.end(); ++it) {
2108 Branch * branch = branch_list.find(branch_name);
2110 LYXERR0("Branch " << branch_name << " already exists.");
2114 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2116 branch_list.add(branch_name);
2117 branch = branch_list.find(branch_name);
2118 string const x11hexname = X11hexname(branch->color());
2119 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2120 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2122 dr.screenUpdate(Update::Force);
2130 case LFUN_BRANCH_ACTIVATE:
2131 case LFUN_BRANCH_DEACTIVATE: {
2132 BranchList & branchList = params().branchlist();
2133 docstring const branchName = func.argument();
2134 // the case without a branch name is handled elsewhere
2135 if (branchName.empty()) {
2139 Branch * branch = branchList.find(branchName);
2141 LYXERR0("Branch " << branchName << " does not exist.");
2143 docstring const msg =
2144 bformat(_("Branch \"%1$s\" does not exist."), branchName);
2147 branch->setSelected(func.action() == LFUN_BRANCH_ACTIVATE);
2149 dr.screenUpdate(Update::Force);
2150 dr.forceBufferUpdate();
2155 case LFUN_BRANCHES_RENAME: {
2156 if (func.argument().empty())
2159 docstring const oldname = from_utf8(func.getArg(0));
2160 docstring const newname = from_utf8(func.getArg(1));
2161 InsetIterator it = inset_iterator_begin(inset());
2162 InsetIterator const end = inset_iterator_end(inset());
2163 bool success = false;
2164 for (; it != end; ++it) {
2165 if (it->lyxCode() == BRANCH_CODE) {
2166 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2167 if (ins.branch() == oldname) {
2168 undo().recordUndo(it);
2169 ins.rename(newname);
2174 if (it->lyxCode() == INCLUDE_CODE) {
2175 // get buffer of external file
2176 InsetInclude const & ins =
2177 static_cast<InsetInclude const &>(*it);
2178 Buffer * child = ins.getChildBuffer();
2181 child->dispatch(func, dr);
2186 dr.screenUpdate(Update::Force);
2187 dr.forceBufferUpdate();
2192 case LFUN_BUFFER_PRINT: {
2193 // we'll assume there's a problem until we succeed
2195 string target = func.getArg(0);
2196 string target_name = func.getArg(1);
2197 string command = func.getArg(2);
2200 || target_name.empty()
2201 || command.empty()) {
2202 LYXERR0("Unable to parse " << func.argument());
2203 docstring const msg =
2204 bformat(_("Unable to parse \"%1$s\""), func.argument());
2208 if (target != "printer" && target != "file") {
2209 LYXERR0("Unrecognized target \"" << target << '"');
2210 docstring const msg =
2211 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2216 bool const update_unincluded =
2217 params().maintain_unincluded_children
2218 && !params().getIncludedChildren().empty();
2219 if (!doExport("dvi", true, update_unincluded)) {
2220 showPrintError(absFileName());
2221 dr.setMessage(_("Error exporting to DVI."));
2225 // Push directory path.
2226 string const path = temppath();
2227 // Prevent the compiler from optimizing away p
2231 // there are three cases here:
2232 // 1. we print to a file
2233 // 2. we print directly to a printer
2234 // 3. we print using a spool command (print to file first)
2237 string const dviname = changeExtension(latexName(true), "dvi");
2239 if (target == "printer") {
2240 if (!lyxrc.print_spool_command.empty()) {
2241 // case 3: print using a spool
2242 string const psname = changeExtension(dviname,".ps");
2243 command += ' ' + lyxrc.print_to_file
2246 + quoteName(dviname);
2248 string command2 = lyxrc.print_spool_command + ' ';
2249 if (target_name != "default") {
2250 command2 += lyxrc.print_spool_printerprefix
2254 command2 += quoteName(psname);
2256 // If successful, then spool command
2257 res = one.startscript(Systemcall::Wait, command,
2261 // If there's no GUI, we have to wait on this command. Otherwise,
2262 // LyX deletes the temporary directory, and with it the spooled
2263 // file, before it can be printed!!
2264 Systemcall::Starttype stype = use_gui ?
2265 Systemcall::DontWait : Systemcall::Wait;
2266 res = one.startscript(stype, command2,
2270 // case 2: print directly to a printer
2271 if (target_name != "default")
2272 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2274 Systemcall::Starttype stype = use_gui ?
2275 Systemcall::DontWait : Systemcall::Wait;
2276 res = one.startscript(stype, command +
2277 quoteName(dviname), filePath());
2281 // case 1: print to a file
2282 FileName const filename(makeAbsPath(target_name, filePath()));
2283 FileName const dvifile(makeAbsPath(dviname, path));
2284 if (filename.exists()) {
2285 docstring text = bformat(
2286 _("The file %1$s already exists.\n\n"
2287 "Do you want to overwrite that file?"),
2288 makeDisplayPath(filename.absFileName()));
2289 if (Alert::prompt(_("Overwrite file?"),
2290 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2293 command += ' ' + lyxrc.print_to_file
2294 + quoteName(filename.toFilesystemEncoding())
2296 + quoteName(dvifile.toFilesystemEncoding());
2298 Systemcall::Starttype stype = use_gui ?
2299 Systemcall::DontWait : Systemcall::Wait;
2300 res = one.startscript(stype, command, filePath());
2306 dr.setMessage(_("Error running external commands."));
2307 showPrintError(absFileName());
2312 case LFUN_BUFFER_LANGUAGE: {
2313 Language const * oldL = params().language;
2314 Language const * newL = languages.getLanguage(argument);
2315 if (!newL || oldL == newL)
2317 if (oldL->rightToLeft() == newL->rightToLeft() && !isMultiLingual()) {
2318 changeLanguage(oldL, newL);
2319 dr.forceBufferUpdate();
2328 dr.dispatched(dispatched);
2329 undo().endUndoGroup();
2333 void Buffer::changeLanguage(Language const * from, Language const * to)
2335 LASSERT(from, /**/);
2338 for_each(par_iterator_begin(),
2340 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2344 bool Buffer::isMultiLingual() const
2346 ParConstIterator end = par_iterator_end();
2347 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2348 if (it->isMultiLingual(params()))
2355 std::set<Language const *> Buffer::getLanguages() const
2357 std::set<Language const *> languages;
2358 getLanguages(languages);
2363 void Buffer::getLanguages(std::set<Language const *> & languages) const
2365 ParConstIterator end = par_iterator_end();
2366 // add the buffer language, even if it's not actively used
2367 languages.insert(language());
2368 // iterate over the paragraphs
2369 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2370 it->getLanguages(languages);
2372 ListOfBuffers clist = getDescendents();
2373 ListOfBuffers::const_iterator cit = clist.begin();
2374 ListOfBuffers::const_iterator const cen = clist.end();
2375 for (; cit != cen; ++cit)
2376 (*cit)->getLanguages(languages);
2380 DocIterator Buffer::getParFromID(int const id) const
2382 Buffer * buf = const_cast<Buffer *>(this);
2384 // John says this is called with id == -1 from undo
2385 lyxerr << "getParFromID(), id: " << id << endl;
2386 return doc_iterator_end(buf);
2389 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2390 if (it.paragraph().id() == id)
2393 return doc_iterator_end(buf);
2397 bool Buffer::hasParWithID(int const id) const
2399 return !getParFromID(id).atEnd();
2403 ParIterator Buffer::par_iterator_begin()
2405 return ParIterator(doc_iterator_begin(this));
2409 ParIterator Buffer::par_iterator_end()
2411 return ParIterator(doc_iterator_end(this));
2415 ParConstIterator Buffer::par_iterator_begin() const
2417 return ParConstIterator(doc_iterator_begin(this));
2421 ParConstIterator Buffer::par_iterator_end() const
2423 return ParConstIterator(doc_iterator_end(this));
2427 Language const * Buffer::language() const
2429 return params().language;
2433 docstring const Buffer::B_(string const & l10n) const
2435 return params().B_(l10n);
2439 bool Buffer::isClean() const
2441 return d->lyx_clean;
2445 bool Buffer::isExternallyModified(CheckMethod method) const
2447 LASSERT(d->filename.exists(), /**/);
2448 // if method == timestamp, check timestamp before checksum
2449 return (method == checksum_method
2450 || d->timestamp_ != d->filename.lastModified())
2451 && d->checksum_ != d->filename.checksum();
2455 void Buffer::saveCheckSum() const
2457 FileName const & file = d->filename;
2460 if (file.exists()) {
2461 d->timestamp_ = file.lastModified();
2462 d->checksum_ = file.checksum();
2464 // in the case of save to a new file.
2471 void Buffer::markClean() const
2473 if (!d->lyx_clean) {
2474 d->lyx_clean = true;
2477 // if the .lyx file has been saved, we don't need an
2479 d->bak_clean = true;
2480 d->undo_.markDirty();
2484 void Buffer::setUnnamed(bool flag)
2490 bool Buffer::isUnnamed() const
2497 /// Don't check unnamed, here: isInternal() is used in
2498 /// newBuffer(), where the unnamed flag has not been set by anyone
2499 /// yet. Also, for an internal buffer, there should be no need for
2500 /// retrieving fileName() nor for checking if it is unnamed or not.
2501 bool Buffer::isInternal() const
2503 return fileName().extension() == "internal";
2507 void Buffer::markDirty()
2510 d->lyx_clean = false;
2513 d->bak_clean = false;
2515 DepClean::iterator it = d->dep_clean.begin();
2516 DepClean::const_iterator const end = d->dep_clean.end();
2518 for (; it != end; ++it)
2523 FileName Buffer::fileName() const
2529 string Buffer::absFileName() const
2531 return d->filename.absFileName();
2535 string Buffer::filePath() const
2537 return d->filename.onlyPath().absFileName() + "/";
2541 bool Buffer::isReadonly() const
2543 return d->read_only;
2547 void Buffer::setParent(Buffer const * buffer)
2549 // Avoids recursive include.
2550 d->setParent(buffer == this ? 0 : buffer);
2555 Buffer const * Buffer::parent() const
2561 ListOfBuffers Buffer::allRelatives() const
2563 ListOfBuffers lb = masterBuffer()->getDescendents();
2564 lb.push_front(const_cast<Buffer *>(masterBuffer()));
2569 Buffer const * Buffer::masterBuffer() const
2571 // FIXME Should be make sure we are not in some kind
2572 // of recursive include? A -> B -> A will crash this.
2573 Buffer const * const pbuf = d->parent();
2577 return pbuf->masterBuffer();
2581 bool Buffer::isChild(Buffer * child) const
2583 return d->children_positions.find(child) != d->children_positions.end();
2587 DocIterator Buffer::firstChildPosition(Buffer const * child)
2589 Impl::BufferPositionMap::iterator it;
2590 it = d->children_positions.find(child);
2591 if (it == d->children_positions.end())
2592 return DocIterator(this);
2597 bool Buffer::hasChildren() const
2599 return !d->children_positions.empty();
2603 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
2605 // loop over children
2606 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2607 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2608 for (; it != end; ++it) {
2609 Buffer * child = const_cast<Buffer *>(it->first);
2611 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
2612 if (bit != clist.end())
2614 clist.push_back(child);
2616 // there might be grandchildren
2617 child->collectChildren(clist, true);
2622 ListOfBuffers Buffer::getChildren() const
2625 collectChildren(v, false);
2630 ListOfBuffers Buffer::getDescendents() const
2633 collectChildren(v, true);
2638 template<typename M>
2639 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
2644 typename M::const_iterator it = m.lower_bound(x);
2645 if (it == m.begin())
2653 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
2654 DocIterator const & pos) const
2656 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2658 // if paragraphs have no macro context set, pos will be empty
2662 // we haven't found anything yet
2663 DocIterator bestPos = owner_->par_iterator_begin();
2664 MacroData const * bestData = 0;
2666 // find macro definitions for name
2667 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
2668 if (nameIt != macros.end()) {
2669 // find last definition in front of pos or at pos itself
2670 PositionScopeMacroMap::const_iterator it
2671 = greatest_below(nameIt->second, pos);
2672 if (it != nameIt->second.end()) {
2674 // scope ends behind pos?
2675 if (pos < it->second.first) {
2676 // Looks good, remember this. If there
2677 // is no external macro behind this,
2678 // we found the right one already.
2679 bestPos = it->first;
2680 bestData = &it->second.second;
2684 // try previous macro if there is one
2685 if (it == nameIt->second.begin())
2692 // find macros in included files
2693 PositionScopeBufferMap::const_iterator it
2694 = greatest_below(position_to_children, pos);
2695 if (it == position_to_children.end())
2696 // no children before
2700 // do we know something better (i.e. later) already?
2701 if (it->first < bestPos )
2704 // scope ends behind pos?
2705 if (pos < it->second.first
2706 && (cloned_buffer_ ||
2707 theBufferList().isLoaded(it->second.second))) {
2708 // look for macro in external file
2710 MacroData const * data
2711 = it->second.second->getMacro(name, false);
2714 bestPos = it->first;
2720 // try previous file if there is one
2721 if (it == position_to_children.begin())
2726 // return the best macro we have found
2731 MacroData const * Buffer::getMacro(docstring const & name,
2732 DocIterator const & pos, bool global) const
2737 // query buffer macros
2738 MacroData const * data = d->getBufferMacro(name, pos);
2742 // If there is a master buffer, query that
2743 Buffer const * const pbuf = d->parent();
2745 d->macro_lock = true;
2746 MacroData const * macro = pbuf->getMacro(
2747 name, *this, false);
2748 d->macro_lock = false;
2754 data = MacroTable::globalMacros().get(name);
2763 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2765 // set scope end behind the last paragraph
2766 DocIterator scope = par_iterator_begin();
2767 scope.pit() = scope.lastpit() + 1;
2769 return getMacro(name, scope, global);
2773 MacroData const * Buffer::getMacro(docstring const & name,
2774 Buffer const & child, bool global) const
2776 // look where the child buffer is included first
2777 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2778 if (it == d->children_positions.end())
2781 // check for macros at the inclusion position
2782 return getMacro(name, it->second, global);
2786 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
2788 pit_type const lastpit = it.lastpit();
2790 // look for macros in each paragraph
2791 while (it.pit() <= lastpit) {
2792 Paragraph & par = it.paragraph();
2794 // iterate over the insets of the current paragraph
2795 InsetList const & insets = par.insetList();
2796 InsetList::const_iterator iit = insets.begin();
2797 InsetList::const_iterator end = insets.end();
2798 for (; iit != end; ++iit) {
2799 it.pos() = iit->pos;
2801 // is it a nested text inset?
2802 if (iit->inset->asInsetText()) {
2803 // Inset needs its own scope?
2804 InsetText const * itext = iit->inset->asInsetText();
2805 bool newScope = itext->isMacroScope();
2807 // scope which ends just behind the inset
2808 DocIterator insetScope = it;
2811 // collect macros in inset
2812 it.push_back(CursorSlice(*iit->inset));
2813 updateMacros(it, newScope ? insetScope : scope);
2818 if (iit->inset->asInsetTabular()) {
2819 CursorSlice slice(*iit->inset);
2820 size_t const numcells = slice.nargs();
2821 for (; slice.idx() < numcells; slice.forwardIdx()) {
2822 it.push_back(slice);
2823 updateMacros(it, scope);
2829 // is it an external file?
2830 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2831 // get buffer of external file
2832 InsetInclude const & inset =
2833 static_cast<InsetInclude const &>(*iit->inset);
2835 Buffer * child = inset.getChildBuffer();
2840 // register its position, but only when it is
2841 // included first in the buffer
2842 if (children_positions.find(child) ==
2843 children_positions.end())
2844 children_positions[child] = it;
2846 // register child with its scope
2847 position_to_children[it] = Impl::ScopeBuffer(scope, child);
2851 InsetMath * im = iit->inset->asInsetMath();
2852 if (doing_export && im) {
2853 InsetMathHull * hull = im->asHullInset();
2855 hull->recordLocation(it);
2858 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2862 MathMacroTemplate & macroTemplate =
2863 *iit->inset->asInsetMath()->asMacroTemplate();
2864 MacroContext mc(owner_, it);
2865 macroTemplate.updateToContext(mc);
2868 bool valid = macroTemplate.validMacro();
2869 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2870 // then the BufferView's cursor will be invalid in
2871 // some cases which leads to crashes.
2876 // FIXME (Abdel), I don't understandt why we pass 'it' here
2877 // instead of 'macroTemplate' defined above... is this correct?
2878 macros[macroTemplate.name()][it] =
2879 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
2889 void Buffer::updateMacros() const
2894 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2896 // start with empty table
2898 d->children_positions.clear();
2899 d->position_to_children.clear();
2901 // Iterate over buffer, starting with first paragraph
2902 // The scope must be bigger than any lookup DocIterator
2903 // later. For the global lookup, lastpit+1 is used, hence
2904 // we use lastpit+2 here.
2905 DocIterator it = par_iterator_begin();
2906 DocIterator outerScope = it;
2907 outerScope.pit() = outerScope.lastpit() + 2;
2908 d->updateMacros(it, outerScope);
2912 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
2914 InsetIterator it = inset_iterator_begin(inset());
2915 InsetIterator const end = inset_iterator_end(inset());
2916 for (; it != end; ++it) {
2917 if (it->lyxCode() == BRANCH_CODE) {
2918 InsetBranch & br = static_cast<InsetBranch &>(*it);
2919 docstring const name = br.branch();
2920 if (!from_master && !params().branchlist().find(name))
2921 result.push_back(name);
2922 else if (from_master && !masterBuffer()->params().branchlist().find(name))
2923 result.push_back(name);
2926 if (it->lyxCode() == INCLUDE_CODE) {
2927 // get buffer of external file
2928 InsetInclude const & ins =
2929 static_cast<InsetInclude const &>(*it);
2930 Buffer * child = ins.getChildBuffer();
2933 child->getUsedBranches(result, true);
2936 // remove duplicates
2941 void Buffer::updateMacroInstances(UpdateType utype) const
2943 LYXERR(Debug::MACROS, "updateMacroInstances for "
2944 << d->filename.onlyFileName());
2945 DocIterator it = doc_iterator_begin(this);
2947 DocIterator const end = doc_iterator_end(this);
2948 for (; it != end; it.forwardInset()) {
2949 // look for MathData cells in InsetMathNest insets
2950 InsetMath * minset = it.nextInset()->asInsetMath();
2954 // update macro in all cells of the InsetMathNest
2955 DocIterator::idx_type n = minset->nargs();
2956 MacroContext mc = MacroContext(this, it);
2957 for (DocIterator::idx_type i = 0; i < n; ++i) {
2958 MathData & data = minset->cell(i);
2959 data.updateMacros(0, mc, utype);
2965 void Buffer::listMacroNames(MacroNameSet & macros) const
2970 d->macro_lock = true;
2972 // loop over macro names
2973 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2974 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2975 for (; nameIt != nameEnd; ++nameIt)
2976 macros.insert(nameIt->first);
2978 // loop over children
2979 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2980 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2981 for (; it != end; ++it)
2982 it->first->listMacroNames(macros);
2985 Buffer const * const pbuf = d->parent();
2987 pbuf->listMacroNames(macros);
2989 d->macro_lock = false;
2993 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2995 Buffer const * const pbuf = d->parent();
3000 pbuf->listMacroNames(names);
3003 MacroNameSet::iterator it = names.begin();
3004 MacroNameSet::iterator end = names.end();
3005 for (; it != end; ++it) {
3007 MacroData const * data =
3008 pbuf->getMacro(*it, *this, false);
3010 macros.insert(data);
3012 // we cannot access the original MathMacroTemplate anymore
3013 // here to calls validate method. So we do its work here manually.
3014 // FIXME: somehow make the template accessible here.
3015 if (data->optionals() > 0)
3016 features.require("xargs");
3022 Buffer::References & Buffer::references(docstring const & label)
3025 return const_cast<Buffer *>(masterBuffer())->references(label);
3027 RefCache::iterator it = d->ref_cache_.find(label);
3028 if (it != d->ref_cache_.end())
3029 return it->second.second;
3031 static InsetLabel const * dummy_il = 0;
3032 static References const dummy_refs;
3033 it = d->ref_cache_.insert(
3034 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3035 return it->second.second;
3039 Buffer::References const & Buffer::references(docstring const & label) const
3041 return const_cast<Buffer *>(this)->references(label);
3045 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3047 masterBuffer()->d->ref_cache_[label].first = il;
3051 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3053 return masterBuffer()->d->ref_cache_[label].first;
3057 void Buffer::clearReferenceCache() const
3060 d->ref_cache_.clear();
3064 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
3067 //FIXME: This does not work for child documents yet.
3068 LASSERT(code == CITE_CODE, /**/);
3070 reloadBibInfoCache();
3072 // Check if the label 'from' appears more than once
3073 BiblioInfo const & keys = masterBibInfo();
3074 BiblioInfo::const_iterator bit = keys.begin();
3075 BiblioInfo::const_iterator bend = keys.end();
3076 vector<docstring> labels;
3078 for (; bit != bend; ++bit)
3080 labels.push_back(bit->first);
3082 if (count(labels.begin(), labels.end(), from) > 1)
3085 string const paramName = "key";
3086 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3087 if (it->lyxCode() == code) {
3088 InsetCommand * inset = it->asInsetCommand();
3091 docstring const oldValue = inset->getParam(paramName);
3092 if (oldValue == from)
3093 inset->setParam(paramName, to);
3099 void Buffer::getSourceCode(odocstream & os, string const format,
3100 pit_type par_begin, pit_type par_end,
3101 bool full_source) const
3103 OutputParams runparams(¶ms().encoding());
3104 runparams.nice = true;
3105 runparams.flavor = params().getOutputFlavor(format);
3106 runparams.linelen = lyxrc.plaintext_linelen;
3107 // No side effect of file copying and image conversion
3108 runparams.dryrun = true;
3111 os << "% " << _("Preview source code") << "\n\n";
3113 d->texrow.newline();
3114 d->texrow.newline();
3115 if (params().isDocBook())
3116 writeDocBookSource(os, absFileName(), runparams, false);
3117 else if (runparams.flavor == OutputParams::HTML)
3118 writeLyXHTMLSource(os, runparams, false);
3120 // latex or literate
3121 otexstream ots(os, d->texrow);
3122 writeLaTeXSource(ots, string(), runparams, true, true);
3125 runparams.par_begin = par_begin;
3126 runparams.par_end = par_end;
3127 if (par_begin + 1 == par_end) {
3129 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3133 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3134 convert<docstring>(par_begin),
3135 convert<docstring>(par_end - 1))
3142 // output paragraphs
3143 if (params().isDocBook())
3144 docbookParagraphs(text(), *this, os, runparams);
3145 else if (runparams.flavor == OutputParams::HTML) {
3147 xhtmlParagraphs(text(), *this, xs, runparams);
3149 // latex or literate
3150 otexstream ots(os, texrow);
3151 latexParagraphs(*this, text(), ots, runparams);
3157 ErrorList & Buffer::errorList(string const & type) const
3159 return d->errorLists[type];
3163 void Buffer::updateTocItem(std::string const & type,
3164 DocIterator const & dit) const
3167 d->gui_->updateTocItem(type, dit);
3171 void Buffer::structureChanged() const
3174 d->gui_->structureChanged();
3178 void Buffer::errors(string const & err, bool from_master) const
3181 d->gui_->errors(err, from_master);
3185 void Buffer::message(docstring const & msg) const
3188 d->gui_->message(msg);
3192 void Buffer::setBusy(bool on) const
3195 d->gui_->setBusy(on);
3199 void Buffer::updateTitles() const
3202 d->wa_->updateTitles();
3206 void Buffer::resetAutosaveTimers() const
3209 d->gui_->resetAutosaveTimers();
3213 bool Buffer::hasGuiDelegate() const
3219 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3228 class AutoSaveBuffer : public ForkedProcess {
3231 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3232 : buffer_(buffer), fname_(fname) {}
3234 virtual shared_ptr<ForkedProcess> clone() const
3236 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3241 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3242 from_utf8(fname_.absFileName())));
3243 return run(DontWait);
3247 virtual int generateChild();
3249 Buffer const & buffer_;
3254 int AutoSaveBuffer::generateChild()
3256 #if defined(__APPLE__)
3257 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3258 * We should use something else like threads.
3260 * Since I do not know how to determine at run time what is the OS X
3261 * version, I just disable forking altogether for now (JMarc)
3263 pid_t const pid = -1;
3265 // tmp_ret will be located (usually) in /tmp
3266 // will that be a problem?
3267 // Note that this calls ForkedCalls::fork(), so it's
3268 // ok cross-platform.
3269 pid_t const pid = fork();
3270 // If you want to debug the autosave
3271 // you should set pid to -1, and comment out the fork.
3272 if (pid != 0 && pid != -1)
3276 // pid = -1 signifies that lyx was unable
3277 // to fork. But we will do the save
3279 bool failed = false;
3280 FileName const tmp_ret = FileName::tempName("lyxauto");
3281 if (!tmp_ret.empty()) {
3282 buffer_.writeFile(tmp_ret);
3283 // assume successful write of tmp_ret
3284 if (!tmp_ret.moveTo(fname_))
3290 // failed to write/rename tmp_ret so try writing direct
3291 if (!buffer_.writeFile(fname_)) {
3292 // It is dangerous to do this in the child,
3293 // but safe in the parent, so...
3294 if (pid == -1) // emit message signal.
3295 buffer_.message(_("Autosave failed!"));
3299 if (pid == 0) // we are the child so...
3308 FileName Buffer::getEmergencyFileName() const
3310 return FileName(d->filename.absFileName() + ".emergency");
3314 FileName Buffer::getAutosaveFileName() const
3316 // if the document is unnamed try to save in the backup dir, else
3317 // in the default document path, and as a last try in the filePath,
3318 // which will most often be the temporary directory
3321 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3322 : lyxrc.backupdir_path;
3323 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3326 string const fname = "#" + d->filename.onlyFileName() + "#";
3328 return makeAbsPath(fname, fpath);
3332 void Buffer::removeAutosaveFile() const
3334 FileName const f = getAutosaveFileName();
3340 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3342 FileName const newauto = getAutosaveFileName();
3344 if (newauto != oldauto && oldauto.exists())
3345 if (!oldauto.moveTo(newauto))
3346 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3350 bool Buffer::autoSave() const
3352 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
3353 if (buf->d->bak_clean || isReadonly())
3356 message(_("Autosaving current document..."));
3357 buf->d->bak_clean = true;
3359 FileName const fname = getAutosaveFileName();
3360 if (d->cloned_buffer_) {
3361 // If this buffer is cloned, we assume that
3362 // we are running in a separate thread already.
3363 FileName const tmp_ret = FileName::tempName("lyxauto");
3364 if (!tmp_ret.empty()) {
3366 // assume successful write of tmp_ret
3367 if (tmp_ret.moveTo(fname))
3370 // failed to write/rename tmp_ret so try writing direct
3371 return writeFile(fname);
3373 /// This function is deprecated as the frontend needs to take care
3374 /// of cloning the buffer and autosaving it in another thread. It
3375 /// is still here to allow (QT_VERSION < 0x040400).
3376 AutoSaveBuffer autosave(*this, fname);
3384 // helper class, to guarantee this gets reset properly
3385 class MarkAsExporting {
3387 MarkAsExporting(Buffer const * buf) : buf_(buf)
3389 LASSERT(buf_, /* */);
3390 buf_->setExportStatus(true);
3394 buf_->setExportStatus(false);
3397 Buffer const * const buf_;
3402 void Buffer::setExportStatus(bool e) const
3404 d->doing_export = e;
3405 ListOfBuffers clist = getDescendents();
3406 ListOfBuffers::const_iterator cit = clist.begin();
3407 ListOfBuffers::const_iterator const cen = clist.end();
3408 for (; cit != cen; ++cit)
3409 (*cit)->d->doing_export = e;
3413 bool Buffer::isExporting() const
3415 return d->doing_export;
3419 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3420 bool includeall, string & result_file) const
3422 MarkAsExporting exporting(this);
3423 string backend_format;
3424 OutputParams runparams(¶ms().encoding());
3425 runparams.flavor = OutputParams::LATEX;
3426 runparams.linelen = lyxrc.plaintext_linelen;
3427 runparams.includeall = includeall;
3428 vector<string> backs = params().backends();
3429 Converters converters = theConverters();
3430 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3431 // Get shortest path to format
3432 converters.buildGraph();
3433 Graph::EdgePath path;
3434 for (vector<string>::const_iterator it = backs.begin();
3435 it != backs.end(); ++it) {
3436 Graph::EdgePath p = converters.getPath(*it, format);
3437 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3438 backend_format = *it;
3443 if (!put_in_tempdir) {
3444 // Only show this alert if this is an export to a non-temporary
3445 // file (not for previewing).
3446 Alert::error(_("Couldn't export file"), bformat(
3447 _("No information for exporting the format %1$s."),
3448 formats.prettyName(format)));
3452 runparams.flavor = converters.getFlavor(path);
3455 backend_format = format;
3456 // FIXME: Don't hardcode format names here, but use a flag
3457 if (backend_format == "pdflatex")
3458 runparams.flavor = OutputParams::PDFLATEX;
3459 else if (backend_format == "luatex")
3460 runparams.flavor = OutputParams::LUATEX;
3461 else if (backend_format == "xetex")
3462 runparams.flavor = OutputParams::XETEX;
3465 string filename = latexName(false);
3466 filename = addName(temppath(), filename);
3467 filename = changeExtension(filename,
3468 formats.extension(backend_format));
3470 // Plain text backend
3471 if (backend_format == "text") {
3472 runparams.flavor = OutputParams::TEXT;
3473 writePlaintextFile(*this, FileName(filename), runparams);
3476 else if (backend_format == "xhtml") {
3477 runparams.flavor = OutputParams::HTML;
3478 switch (params().html_math_output) {
3479 case BufferParams::MathML:
3480 runparams.math_flavor = OutputParams::MathAsMathML;
3482 case BufferParams::HTML:
3483 runparams.math_flavor = OutputParams::MathAsHTML;
3485 case BufferParams::Images:
3486 runparams.math_flavor = OutputParams::MathAsImages;
3488 case BufferParams::LaTeX:
3489 runparams.math_flavor = OutputParams::MathAsLaTeX;
3492 makeLyXHTMLFile(FileName(filename), runparams);
3493 } else if (backend_format == "lyx")
3494 writeFile(FileName(filename));
3496 else if (params().isDocBook()) {
3497 runparams.nice = !put_in_tempdir;
3498 makeDocBookFile(FileName(filename), runparams);
3501 else if (backend_format == format) {
3502 runparams.nice = true;
3503 if (!makeLaTeXFile(FileName(filename), string(), runparams)) {
3504 if (d->cloned_buffer_) {
3505 d->cloned_buffer_->d->errorLists["Export"] =
3506 d->errorLists["Export"];
3510 } else if (!lyxrc.tex_allows_spaces
3511 && contains(filePath(), ' ')) {
3512 Alert::error(_("File name error"),
3513 _("The directory path to the document cannot contain spaces."));
3516 runparams.nice = false;
3517 if (!makeLaTeXFile(FileName(filename), filePath(), runparams)) {
3518 if (d->cloned_buffer_) {
3519 d->cloned_buffer_->d->errorLists["Export"] =
3520 d->errorLists["Export"];
3526 string const error_type = (format == "program")
3527 ? "Build" : params().bufferFormat();
3528 ErrorList & error_list = d->errorLists[error_type];
3529 string const ext = formats.extension(format);
3530 FileName const tmp_result_file(changeExtension(filename, ext));
3531 bool const success = converters.convert(this, FileName(filename),
3532 tmp_result_file, FileName(absFileName()), backend_format, format,
3535 // Emit the signal to show the error list or copy it back to the
3536 // cloned Buffer so that it can be emitted afterwards.
3537 if (format != backend_format) {
3538 if (d->cloned_buffer_) {
3539 d->cloned_buffer_->d->errorLists[error_type] =
3540 d->errorLists[error_type];
3543 // also to the children, in case of master-buffer-view
3544 ListOfBuffers clist = getDescendents();
3545 ListOfBuffers::const_iterator cit = clist.begin();
3546 ListOfBuffers::const_iterator const cen = clist.end();
3547 for (; cit != cen; ++cit) {
3548 if (d->cloned_buffer_) {
3549 // Enable reverse search by copying back the
3550 // texrow object to the cloned buffer.
3551 // FIXME: this is not thread safe.
3552 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
3553 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
3554 (*cit)->d->errorLists[error_type];
3556 (*cit)->errors(error_type, true);
3560 if (d->cloned_buffer_) {
3561 // Enable reverse dvi or pdf to work by copying back the texrow
3562 // object to the cloned buffer.
3563 // FIXME: There is a possibility of concurrent access to texrow
3564 // here from the main GUI thread that should be securized.
3565 d->cloned_buffer_->d->texrow = d->texrow;
3566 string const error_type = params().bufferFormat();
3567 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
3573 if (put_in_tempdir) {
3574 result_file = tmp_result_file.absFileName();
3578 result_file = changeExtension(d->exportFileName().absFileName(), ext);
3579 // We need to copy referenced files (e. g. included graphics
3580 // if format == "dvi") to the result dir.
3581 vector<ExportedFile> const files =
3582 runparams.exportdata->externalFiles(format);
3583 string const dest = onlyPath(result_file);
3584 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
3585 : force_overwrite == ALL_FILES;
3586 CopyStatus status = use_force ? FORCE : SUCCESS;
3588 vector<ExportedFile>::const_iterator it = files.begin();
3589 vector<ExportedFile>::const_iterator const en = files.end();
3590 for (; it != en && status != CANCEL; ++it) {
3591 string const fmt = formats.getFormatFromFile(it->sourceName);
3592 status = copyFile(fmt, it->sourceName,
3593 makeAbsPath(it->exportName, dest),
3594 it->exportName, status == FORCE);
3597 if (status == CANCEL) {
3598 message(_("Document export cancelled."));
3599 } else if (tmp_result_file.exists()) {
3600 // Finally copy the main file
3601 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
3602 : force_overwrite != NO_FILES;
3603 if (status == SUCCESS && use_force)
3605 status = copyFile(format, tmp_result_file,
3606 FileName(result_file), result_file,
3608 message(bformat(_("Document exported as %1$s "
3610 formats.prettyName(format),
3611 makeDisplayPath(result_file)));
3613 // This must be a dummy converter like fax (bug 1888)
3614 message(bformat(_("Document exported as %1$s"),
3615 formats.prettyName(format)));
3622 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3623 bool includeall) const
3626 // (1) export with all included children (omit \includeonly)
3627 if (includeall && !doExport(format, put_in_tempdir, true, result_file))
3629 // (2) export with included children only
3630 return doExport(format, put_in_tempdir, false, result_file);
3634 bool Buffer::preview(string const & format, bool includeall) const
3636 MarkAsExporting exporting(this);
3638 // (1) export with all included children (omit \includeonly)
3639 if (includeall && !doExport(format, true, true))
3641 // (2) export with included children only
3642 if (!doExport(format, true, false, result_file))
3644 return formats.view(*this, FileName(result_file), format);
3648 Buffer::ReadStatus Buffer::extractFromVC()
3650 bool const found = LyXVC::file_not_found_hook(d->filename);
3652 return ReadFileNotFound;
3653 if (!d->filename.isReadableFile())
3659 Buffer::ReadStatus Buffer::loadEmergency()
3661 FileName const emergencyFile = getEmergencyFileName();
3662 if (!emergencyFile.exists()
3663 || emergencyFile.lastModified() <= d->filename.lastModified())
3664 return ReadFileNotFound;
3666 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
3667 docstring const text = bformat(_("An emergency save of the document "
3668 "%1$s exists.\n\nRecover emergency save?"), file);
3670 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
3671 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
3677 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
3678 bool const success = (ret_llf == ReadSuccess);
3681 Alert::warning(_("File is read-only"),
3682 bformat(_("An emergency file is successfully loaded, "
3683 "but the original file %1$s is marked read-only. "
3684 "Please make sure to save the document as a different "
3685 "file."), from_utf8(d->filename.absFileName())));
3688 str = _("Document was successfully recovered.");
3690 str = _("Document was NOT successfully recovered.");
3691 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3692 makeDisplayPath(emergencyFile.absFileName()));
3694 int const del_emerg =
3695 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3696 _("&Remove"), _("&Keep"));
3697 if (del_emerg == 0) {
3698 emergencyFile.removeFile();
3700 Alert::warning(_("Emergency file deleted"),
3701 _("Do not forget to save your file now!"), true);
3703 return success ? ReadSuccess : ReadEmergencyFailure;
3706 int const del_emerg =
3707 Alert::prompt(_("Delete emergency file?"),
3708 _("Remove emergency file now?"), 1, 1,
3709 _("&Remove"), _("&Keep"));
3711 emergencyFile.removeFile();
3712 return ReadOriginal;
3722 Buffer::ReadStatus Buffer::loadAutosave()
3724 // Now check if autosave file is newer.
3725 FileName const autosaveFile = getAutosaveFileName();
3726 if (!autosaveFile.exists()
3727 || autosaveFile.lastModified() <= d->filename.lastModified())
3728 return ReadFileNotFound;
3730 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
3731 docstring const text = bformat(_("The backup of the document %1$s "
3732 "is newer.\n\nLoad the backup instead?"), file);
3733 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
3734 _("&Load backup"), _("Load &original"), _("&Cancel"));
3739 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
3740 // the file is not saved if we load the autosave file.
3741 if (ret_llf == ReadSuccess) {
3743 Alert::warning(_("File is read-only"),
3744 bformat(_("A backup file is successfully loaded, "
3745 "but the original file %1$s is marked read-only. "
3746 "Please make sure to save the document as a "
3748 from_utf8(d->filename.absFileName())));
3753 return ReadAutosaveFailure;
3756 // Here we delete the autosave
3757 autosaveFile.removeFile();
3758 return ReadOriginal;
3766 Buffer::ReadStatus Buffer::loadLyXFile()
3768 if (!d->filename.isReadableFile()) {
3769 ReadStatus const ret_rvc = extractFromVC();
3770 if (ret_rvc != ReadSuccess)
3774 ReadStatus const ret_re = loadEmergency();
3775 if (ret_re == ReadSuccess || ret_re == ReadCancel)
3778 ReadStatus const ret_ra = loadAutosave();
3779 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
3782 return loadThisLyXFile(d->filename);
3786 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
3788 return readFile(fn);
3792 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3794 TeXErrors::Errors::const_iterator it = terr.begin();
3795 TeXErrors::Errors::const_iterator end = terr.end();
3796 ListOfBuffers clist = getDescendents();
3797 ListOfBuffers::const_iterator cen = clist.end();
3799 for (; it != end; ++it) {
3802 int errorRow = it->error_in_line;
3803 Buffer const * buf = 0;
3805 if (it->child_name.empty())
3806 p->texrow.getIdFromRow(errorRow, id_start, pos_start);
3808 // The error occurred in a child
3809 ListOfBuffers::const_iterator cit = clist.begin();
3810 for (; cit != cen; ++cit) {
3811 string const child_name =
3812 DocFileName(changeExtension(
3813 (*cit)->absFileName(), "tex")).
3815 if (it->child_name != child_name)
3817 (*cit)->d->texrow.getIdFromRow(errorRow,
3818 id_start, pos_start);
3819 if (id_start != -1) {
3820 buf = d->cloned_buffer_
3821 ? (*cit)->d->cloned_buffer_->d->owner_
3822 : (*cit)->d->owner_;
3833 found = p->texrow.getIdFromRow(errorRow, id_end, pos_end);
3834 } while (found && id_start == id_end && pos_start == pos_end);
3836 if (id_start != id_end) {
3837 // Next registered position is outside the inset where
3838 // the error occurred, so signal end-of-paragraph
3842 errorList.push_back(ErrorItem(it->error_desc,
3843 it->error_text, id_start, pos_start, pos_end, buf));
3848 void Buffer::setBuffersForInsets() const
3850 inset().setBuffer(const_cast<Buffer &>(*this));
3854 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
3856 // Use the master text class also for child documents
3857 Buffer const * const master = masterBuffer();
3858 DocumentClass const & textclass = master->params().documentClass();
3860 // do this only if we are the top-level Buffer
3862 reloadBibInfoCache();
3864 // keep the buffers to be children in this set. If the call from the
3865 // master comes back we can see which of them were actually seen (i.e.
3866 // via an InsetInclude). The remaining ones in the set need still be updated.
3867 static std::set<Buffer const *> bufToUpdate;
3868 if (scope == UpdateMaster) {
3869 // If this is a child document start with the master
3870 if (master != this) {
3871 bufToUpdate.insert(this);
3872 master->updateBuffer(UpdateMaster, utype);
3873 // Do this here in case the master has no gui associated with it. Then,
3874 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3875 if (!master->d->gui_)
3878 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3879 if (bufToUpdate.find(this) == bufToUpdate.end())
3883 // start over the counters in the master
3884 textclass.counters().reset();
3887 // update will be done below for this buffer
3888 bufToUpdate.erase(this);
3890 // update all caches
3891 clearReferenceCache();
3894 Buffer & cbuf = const_cast<Buffer &>(*this);
3896 LASSERT(!text().paragraphs().empty(), /**/);
3899 ParIterator parit = cbuf.par_iterator_begin();
3900 updateBuffer(parit, utype);
3903 // TocBackend update will be done later.
3906 d->bibinfo_cache_valid_ = true;
3907 d->cite_labels_valid_ = true;
3908 cbuf.tocBackend().update();
3909 if (scope == UpdateMaster)
3910 cbuf.structureChanged();
3914 static depth_type getDepth(DocIterator const & it)
3916 depth_type depth = 0;
3917 for (size_t i = 0 ; i < it.depth() ; ++i)
3918 if (!it[i].inset().inMathed())
3919 depth += it[i].paragraph().getDepth() + 1;
3920 // remove 1 since the outer inset does not count
3924 static depth_type getItemDepth(ParIterator const & it)
3926 Paragraph const & par = *it;
3927 LabelType const labeltype = par.layout().labeltype;
3929 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3932 // this will hold the lowest depth encountered up to now.
3933 depth_type min_depth = getDepth(it);
3934 ParIterator prev_it = it;
3937 --prev_it.top().pit();
3939 // start of nested inset: go to outer par
3941 if (prev_it.empty()) {
3942 // start of document: nothing to do
3947 // We search for the first paragraph with same label
3948 // that is not more deeply nested.
3949 Paragraph & prev_par = *prev_it;
3950 depth_type const prev_depth = getDepth(prev_it);
3951 if (labeltype == prev_par.layout().labeltype) {
3952 if (prev_depth < min_depth)
3953 return prev_par.itemdepth + 1;
3954 if (prev_depth == min_depth)
3955 return prev_par.itemdepth;
3957 min_depth = min(min_depth, prev_depth);
3958 // small optimization: if we are at depth 0, we won't
3959 // find anything else
3960 if (prev_depth == 0)
3966 static bool needEnumCounterReset(ParIterator const & it)
3968 Paragraph const & par = *it;
3969 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3970 depth_type const cur_depth = par.getDepth();
3971 ParIterator prev_it = it;
3972 while (prev_it.pit()) {
3973 --prev_it.top().pit();
3974 Paragraph const & prev_par = *prev_it;
3975 if (prev_par.getDepth() <= cur_depth)
3976 return prev_par.layout().labeltype != LABEL_ENUMERATE;
3978 // start of nested inset: reset
3983 // set the label of a paragraph. This includes the counters.
3984 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
3986 BufferParams const & bp = owner_->masterBuffer()->params();
3987 DocumentClass const & textclass = bp.documentClass();
3988 Paragraph & par = it.paragraph();
3989 Layout const & layout = par.layout();
3990 Counters & counters = textclass.counters();
3992 if (par.params().startOfAppendix()) {
3993 // FIXME: only the counter corresponding to toplevel
3994 // sectioning should be reset
3996 counters.appendix(true);
3998 par.params().appendix(counters.appendix());
4000 // Compute the item depth of the paragraph
4001 par.itemdepth = getItemDepth(it);
4003 if (layout.margintype == MARGIN_MANUAL
4004 || layout.latextype == LATEX_BIB_ENVIRONMENT) {
4005 if (par.params().labelWidthString().empty())
4006 par.params().labelWidthString(par.expandLabel(layout, bp));
4008 par.params().labelWidthString(docstring());
4011 switch(layout.labeltype) {
4013 if (layout.toclevel <= bp.secnumdepth
4014 && (layout.latextype != LATEX_ENVIRONMENT
4015 || it.text()->isFirstInSequence(it.pit()))) {
4016 if (counters.hasCounter(layout.counter))
4017 counters.step(layout.counter, utype);
4018 par.params().labelString(par.expandLabel(layout, bp));
4020 par.params().labelString(docstring());
4023 case LABEL_ITEMIZE: {
4024 // At some point of time we should do something more
4025 // clever here, like:
4026 // par.params().labelString(
4027 // bp.user_defined_bullet(par.itemdepth).getText());
4028 // for now, use a simple hardcoded label
4029 docstring itemlabel;
4030 switch (par.itemdepth) {
4032 itemlabel = char_type(0x2022);
4035 itemlabel = char_type(0x2013);
4038 itemlabel = char_type(0x2217);
4041 itemlabel = char_type(0x2219); // or 0x00b7
4044 par.params().labelString(itemlabel);
4048 case LABEL_ENUMERATE: {
4049 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4051 switch (par.itemdepth) {
4060 enumcounter += "iv";
4063 // not a valid enumdepth...
4067 // Maybe we have to reset the enumeration counter.
4068 if (needEnumCounterReset(it))
4069 counters.reset(enumcounter);
4070 counters.step(enumcounter, utype);
4072 string const & lang = par.getParLanguage(bp)->code();
4073 par.params().labelString(counters.theCounter(enumcounter, lang));
4078 case LABEL_SENSITIVE: {
4079 string const & type = counters.current_float();
4080 docstring full_label;
4082 full_label = owner_->B_("Senseless!!! ");
4084 docstring name = owner_->B_(textclass.floats().getType(type).name());
4085 if (counters.hasCounter(from_utf8(type))) {
4086 string const & lang = par.getParLanguage(bp)->code();
4087 counters.step(from_utf8(type), utype);
4088 full_label = bformat(from_ascii("%1$s %2$s:"),
4090 counters.theCounter(from_utf8(type), lang));
4092 full_label = bformat(from_ascii("%1$s #:"), name);
4094 par.params().labelString(full_label);
4098 case LABEL_NO_LABEL:
4099 par.params().labelString(docstring());
4103 case LABEL_TOP_ENVIRONMENT:
4104 case LABEL_CENTERED_TOP_ENVIRONMENT:
4107 par.params().labelString(par.expandLabel(layout, bp));
4113 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4115 LASSERT(parit.pit() == 0, /**/);
4117 // Set the position of the text in the buffer to be able
4118 // to resolve macros in it.
4119 parit.text()->setMacrocontextPosition(parit);
4121 depth_type maxdepth = 0;
4122 pit_type const lastpit = parit.lastpit();
4123 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4124 // reduce depth if necessary
4125 parit->params().depth(min(parit->params().depth(), maxdepth));
4126 maxdepth = parit->getMaxDepthAfter();
4128 if (utype == OutputUpdate) {
4129 // track the active counters
4130 // we have to do this for the master buffer, since the local
4131 // buffer isn't tracking anything.
4132 masterBuffer()->params().documentClass().counters().
4133 setActiveLayout(parit->layout());
4136 // set the counter for this paragraph
4137 d->setLabel(parit, utype);
4140 InsetList::const_iterator iit = parit->insetList().begin();
4141 InsetList::const_iterator end = parit->insetList().end();
4142 for (; iit != end; ++iit) {
4143 parit.pos() = iit->pos;
4144 iit->inset->updateBuffer(parit, utype);
4150 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4151 WordLangTuple & word_lang, docstring_list & suggestions) const
4155 suggestions.clear();
4156 word_lang = WordLangTuple();
4157 // OK, we start from here.
4158 DocIterator const end = doc_iterator_end(this);
4159 for (; from != end; from.forwardPos()) {
4160 // We are only interested in text so remove the math CursorSlice.
4161 while (from.inMathed()) {
4165 // If from is at the end of the document (which is possible
4166 // when leaving the mathed) LyX will crash later.
4170 from.paragraph().spellCheck();
4171 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4172 if (SpellChecker::misspelled(res)) {
4177 // Do not increase progress when from == to, otherwise the word
4178 // count will be wrong.
4188 Buffer::ReadStatus Buffer::reload()
4191 // c.f. bug http://www.lyx.org/trac/ticket/6587
4192 removeAutosaveFile();
4193 // e.g., read-only status could have changed due to version control
4194 d->filename.refresh();
4195 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4197 ReadStatus const status = loadLyXFile();
4198 if (status == ReadSuccess) {
4203 message(bformat(_("Document %1$s reloaded."), disp_fn));
4206 message(bformat(_("Could not reload document %1$s."), disp_fn));
4216 bool Buffer::saveAs(FileName const & fn)
4218 FileName const old_name = fileName();
4219 FileName const old_auto = getAutosaveFileName();
4220 bool const old_unnamed = isUnnamed();
4227 // bring the autosave file with us, just in case.
4228 moveAutosaveFile(old_auto);
4229 // validate version control data and
4230 // correct buffer title
4231 lyxvc().file_found_hook(fileName());
4233 // the file has now been saved to the new location.
4234 // we need to check that the locations of child buffers
4236 checkChildBuffers();
4240 // reset the old filename and unnamed state
4241 setFileName(old_name);
4242 setUnnamed(old_unnamed);
4248 // FIXME We could do better here, but it is complicated. What would be
4249 // nice is to offer either (a) to save the child buffer to an appropriate
4250 // location, so that it would "move with the master", or else (b) to update
4251 // the InsetInclude so that it pointed to the same file. But (a) is a bit
4252 // complicated, because the code for this lives in GuiView.
4253 void Buffer::checkChildBuffers()
4255 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4256 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4257 for (; it != en; ++it) {
4258 DocIterator dit = it->second;
4259 Buffer * cbuf = const_cast<Buffer *>(it->first);
4260 if (!cbuf || !theBufferList().isLoaded(cbuf))
4262 Inset * inset = dit.nextInset();
4263 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4264 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4265 docstring const & incfile = inset_inc->getParam("filename");
4266 string oldloc = cbuf->absFileName();
4267 string newloc = makeAbsPath(to_utf8(incfile),
4268 onlyPath(absFileName())).absFileName();
4269 if (oldloc == newloc)
4271 // the location of the child file is incorrect.
4272 Alert::warning(_("Included File Invalid"),
4273 bformat(_("Saving this document to a new location has made the file:\n"
4275 "inaccessible. You will need to update the included filename."),
4276 from_utf8(oldloc)));
4278 inset_inc->setChildBuffer(0);
4280 // invalidate cache of children
4281 d->children_positions.clear();
4282 d->position_to_children.clear();