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/InsetBibitem.h"
70 #include "insets/InsetBibtex.h"
71 #include "insets/InsetBranch.h"
72 #include "insets/InsetInclude.h"
73 #include "insets/InsetTabular.h"
74 #include "insets/InsetText.h"
76 #include "mathed/InsetMathHull.h"
77 #include "mathed/MacroTable.h"
78 #include "mathed/MathMacroTemplate.h"
79 #include "mathed/MathSupport.h"
81 #include "frontends/alert.h"
82 #include "frontends/Delegates.h"
83 #include "frontends/WorkAreaManager.h"
85 #include "graphics/Previews.h"
87 #include "support/lassert.h"
88 #include "support/convert.h"
89 #include "support/debug.h"
90 #include "support/docstring_list.h"
91 #include "support/ExceptionMessage.h"
92 #include "support/FileName.h"
93 #include "support/FileNameList.h"
94 #include "support/filetools.h"
95 #include "support/ForkedCalls.h"
96 #include "support/gettext.h"
97 #include "support/gzstream.h"
98 #include "support/lstrings.h"
99 #include "support/lyxalgo.h"
100 #include "support/os.h"
101 #include "support/Package.h"
102 #include "support/Path.h"
103 #include "support/Systemcall.h"
104 #include "support/textutils.h"
105 #include "support/types.h"
107 #include "support/bind.h"
108 #include "support/shared_ptr.h"
120 using namespace lyx::support;
124 namespace Alert = frontend::Alert;
125 namespace os = support::os;
129 // Do not remove the comment below, so we get merge conflict in
130 // independent branches. Instead add your own.
131 int const LYX_FORMAT = 404; // rgh: refstyle
133 typedef map<string, bool> DepClean;
134 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
136 void showPrintError(string const & name)
138 docstring str = bformat(_("Could not print the document %1$s.\n"
139 "Check that your printer is set up correctly."),
140 makeDisplayPath(name, 50));
141 Alert::error(_("Print document failed"), str);
150 Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
161 /// search for macro in local (buffer) table or in children
162 MacroData const * getBufferMacro(docstring const & name,
163 DocIterator const & pos) const;
165 /// Update macro table starting with position of it \param it in some
167 void updateMacros(DocIterator & it, DocIterator & scope);
169 void setLabel(ParIterator & it, UpdateType utype) const;
171 /** If we have branches that use the file suffix
172 feature, return the file name with suffix appended.
174 support::FileName exportFileName() const;
181 mutable TexRow texrow;
183 /// need to regenerate .tex?
187 mutable bool lyx_clean;
189 /// is autosave needed?
190 mutable bool bak_clean;
192 /// is this a unnamed file (New...)?
198 /// name of the file the buffer is associated with.
201 /** Set to true only when the file is fully loaded.
202 * Used to prevent the premature generation of previews
203 * and by the citation inset.
205 bool file_fully_loaded;
208 mutable TocBackend toc_backend;
211 typedef pair<DocIterator, MacroData> ScopeMacro;
212 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
213 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
214 /// map from the macro name to the position map,
215 /// which maps the macro definition position to the scope and the MacroData.
216 NamePositionScopeMacroMap macros;
217 /// This seem to change the way Buffer::getMacro() works
218 mutable bool macro_lock;
220 /// positions of child buffers in the buffer
221 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
222 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
223 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
224 /// position of children buffers in this buffer
225 BufferPositionMap children_positions;
226 /// map from children inclusion positions to their scope and their buffer
227 PositionScopeBufferMap position_to_children;
229 /// Container for all sort of Buffer dependant errors.
230 map<string, ErrorList> errorLists;
232 /// timestamp and checksum used to test if the file has been externally
233 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
235 unsigned long checksum_;
238 frontend::WorkAreaManager * wa_;
240 frontend::GuiBufferDelegate * gui_;
245 /// A cache for the bibfiles (including bibfiles of loaded child
246 /// documents), needed for appropriate update of natbib labels.
247 mutable support::FileNameList bibfiles_cache_;
249 // FIXME The caching mechanism could be improved. At present, we have a
250 // cache for each Buffer, that caches all the bibliography info for that
251 // Buffer. A more efficient solution would be to have a global cache per
252 // file, and then to construct the Buffer's bibinfo from that.
253 /// A cache for bibliography info
254 mutable BiblioInfo bibinfo_;
255 /// whether the bibinfo cache is valid
256 mutable bool bibinfo_cache_valid_;
257 /// whether the bibfile cache is valid
258 mutable bool bibfile_cache_valid_;
259 /// Cache of timestamps of .bib files
260 map<FileName, time_t> bibfile_status_;
262 mutable RefCache ref_cache_;
264 /// our Text that should be wrapped in an InsetText
267 /// This is here to force the test to be done whenever parent_buffer
269 Buffer const * parent() const {
270 // if parent_buffer is not loaded, then it has been unloaded,
271 // which means that parent_buffer is an invalid pointer. So we
272 // set it to null in that case.
273 // however, the BufferList doesn't know about cloned buffers, so
274 // they will always be regarded as unloaded. in that case, we hope
276 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
278 return parent_buffer;
282 void setParent(Buffer const * pb) {
283 if (parent_buffer == pb)
286 if (!cloned_buffer_ && parent_buffer && pb)
287 LYXERR0("Warning: a buffer should not have two parents!");
289 if (!cloned_buffer_ && parent_buffer) {
290 parent_buffer->invalidateBibfileCache();
291 parent_buffer->invalidateBibinfoCache();
295 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
296 /// This one is useful for preview detached in a thread.
297 Buffer const * cloned_buffer_;
298 /// are we in the process of exporting this buffer?
299 mutable bool doing_export;
302 /// So we can force access via the accessors.
303 mutable Buffer const * parent_buffer;
308 /// Creates the per buffer temporary directory
309 static FileName createBufferTmpDir()
312 // We are in our own directory. Why bother to mangle name?
313 // In fact I wrote this code to circumvent a problematic behaviour
314 // (bug?) of EMX mkstemp().
315 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
316 convert<string>(count++));
318 if (!tmpfl.createDirectory(0777)) {
319 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
320 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
321 from_utf8(tmpfl.absFileName())));
327 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
328 Buffer const * cloned_buffer)
329 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
330 read_only(readonly_), filename(file), file_fully_loaded(false),
331 toc_backend(owner), macro_lock(false), timestamp_(0),
332 checksum_(0), wa_(0), gui_(0), undo_(*owner), bibinfo_cache_valid_(false),
333 bibfile_cache_valid_(false), cloned_buffer_(cloned_buffer),
334 doing_export(false), parent_buffer(0)
336 if (!cloned_buffer_) {
337 temppath = createBufferTmpDir();
338 lyxvc.setBuffer(owner_);
340 wa_ = new frontend::WorkAreaManager;
343 temppath = cloned_buffer_->d->temppath;
344 file_fully_loaded = true;
345 params = cloned_buffer_->d->params;
346 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
347 bibinfo_ = cloned_buffer_->d->bibinfo_;
348 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
349 bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
350 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
354 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
355 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
357 LYXERR(Debug::INFO, "Buffer::Buffer()");
359 d->inset = new InsetText(*cloned_buffer->d->inset);
360 d->inset->setBuffer(*this);
361 // FIXME: optimize this loop somewhat, maybe by creating a new
362 // general recursive Inset::setId().
363 DocIterator it = doc_iterator_begin(this);
364 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
365 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
366 it.paragraph().setId(cloned_it.paragraph().id());
368 d->inset = new InsetText(this);
369 d->inset->setAutoBreakRows(true);
370 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
376 LYXERR(Debug::INFO, "Buffer::~Buffer()");
377 // here the buffer should take care that it is
378 // saved properly, before it goes into the void.
380 // GuiView already destroyed
384 // No need to do additional cleanups for internal buffer.
389 // loop over children
390 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
391 Impl::BufferPositionMap::iterator end = d->children_positions.end();
392 for (; it != end; ++it) {
393 Buffer * child = const_cast<Buffer *>(it->first);
394 if (d->cloned_buffer_)
396 // The child buffer might have been closed already.
397 else if (theBufferList().isLoaded(child))
398 theBufferList().releaseChild(this, child);
402 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
403 msg += emergencyWrite();
404 Alert::warning(_("Attempting to close changed document!"), msg);
407 // clear references to children in macro tables
408 d->children_positions.clear();
409 d->position_to_children.clear();
411 if (!d->cloned_buffer_ && !d->temppath.destroyDirectory()) {
412 Alert::warning(_("Could not remove temporary directory"),
413 bformat(_("Could not remove the temporary directory %1$s"),
414 from_utf8(d->temppath.absFileName())));
417 // Remove any previewed LaTeX snippets associated with this buffer.
419 thePreviews().removeLoader(*this);
425 Buffer * Buffer::clone() const
427 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
428 buffer_clone->d->macro_lock = true;
429 buffer_clone->d->children_positions.clear();
430 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
431 // math macro caches need to be rethought and simplified.
432 // I am not sure wether we should handle Buffer cloning here or in BufferList.
433 // Right now BufferList knows nothing about buffer clones.
434 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
435 Impl::BufferPositionMap::iterator end = d->children_positions.end();
436 for (; it != end; ++it) {
437 DocIterator dit = it->second.clone(buffer_clone);
438 dit.setBuffer(buffer_clone);
439 Buffer * child = const_cast<Buffer *>(it->first);
440 Buffer * child_clone = child->clone();
441 Inset * inset = dit.nextInset();
442 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
443 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
444 inset_inc->setChildBuffer(child_clone);
445 child_clone->d->setParent(buffer_clone);
446 buffer_clone->setChild(dit, child_clone);
448 buffer_clone->d->macro_lock = false;
453 bool Buffer::isClone() const
455 return d->cloned_buffer_;
459 void Buffer::changed(bool update_metrics) const
462 d->wa_->redrawAll(update_metrics);
466 frontend::WorkAreaManager & Buffer::workAreaManager() const
468 LASSERT(d->wa_, /**/);
473 Text & Buffer::text() const
475 return d->inset->text();
479 Inset & Buffer::inset() const
485 BufferParams & Buffer::params()
491 BufferParams const & Buffer::params() const
497 ParagraphList & Buffer::paragraphs()
499 return text().paragraphs();
503 ParagraphList const & Buffer::paragraphs() const
505 return text().paragraphs();
509 LyXVC & Buffer::lyxvc()
515 LyXVC const & Buffer::lyxvc() const
521 string const Buffer::temppath() const
523 return d->temppath.absFileName();
527 TexRow & Buffer::texrow()
533 TexRow const & Buffer::texrow() const
539 TocBackend & Buffer::tocBackend() const
541 return d->toc_backend;
545 Undo & Buffer::undo()
551 void Buffer::setChild(DocIterator const & dit, Buffer * child)
553 d->children_positions[child] = dit;
557 string Buffer::latexName(bool const no_path) const
559 FileName latex_name =
560 makeLatexName(d->exportFileName());
561 return no_path ? latex_name.onlyFileName()
562 : latex_name.absFileName();
566 FileName Buffer::Impl::exportFileName() const
568 docstring const branch_suffix =
569 params.branchlist().getFileNameSuffix();
570 if (branch_suffix.empty())
573 string const name = filename.onlyFileNameWithoutExt()
574 + to_utf8(branch_suffix);
575 FileName res(filename.onlyPath().absFileName() + "/" + name);
576 res.changeExtension(filename.extension());
582 string Buffer::logName(LogType * type) const
584 string const filename = latexName(false);
586 if (filename.empty()) {
592 string const path = temppath();
594 FileName const fname(addName(temppath(),
595 onlyFileName(changeExtension(filename,
598 // FIXME: how do we know this is the name of the build log?
599 FileName const bname(
600 addName(path, onlyFileName(
601 changeExtension(filename,
602 formats.extension(bufferFormat()) + ".out"))));
604 // Also consider the master buffer log file
605 FileName masterfname = fname;
607 if (masterBuffer() != this) {
608 string const mlogfile = masterBuffer()->logName(&mtype);
609 masterfname = FileName(mlogfile);
612 // If no Latex log or Build log is newer, show Build log
613 if (bname.exists() &&
614 ((!fname.exists() && !masterfname.exists())
615 || (fname.lastModified() < bname.lastModified()
616 && masterfname.lastModified() < bname.lastModified()))) {
617 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
620 return bname.absFileName();
621 // If we have a newer master file log or only a master log, show this
622 } else if (fname != masterfname
623 && (!fname.exists() && (masterfname.exists()
624 || fname.lastModified() < masterfname.lastModified()))) {
625 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
628 return masterfname.absFileName();
630 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
633 return fname.absFileName();
637 void Buffer::setReadonly(bool const flag)
639 if (d->read_only != flag) {
646 void Buffer::setFileName(string const & newfile)
648 d->filename = makeAbsPath(newfile);
649 setReadonly(d->filename.isReadOnly());
654 int Buffer::readHeader(Lexer & lex)
656 int unknown_tokens = 0;
658 int begin_header_line = -1;
660 // Initialize parameters that may be/go lacking in header:
661 params().branchlist().clear();
662 params().preamble.erase();
663 params().options.erase();
664 params().master.erase();
665 params().float_placement.erase();
666 params().paperwidth.erase();
667 params().paperheight.erase();
668 params().leftmargin.erase();
669 params().rightmargin.erase();
670 params().topmargin.erase();
671 params().bottommargin.erase();
672 params().headheight.erase();
673 params().headsep.erase();
674 params().footskip.erase();
675 params().columnsep.erase();
676 params().fontsCJK.erase();
677 params().listings_params.clear();
678 params().clearLayoutModules();
679 params().clearRemovedModules();
680 params().clearIncludedChildren();
681 params().pdfoptions().clear();
682 params().indiceslist().clear();
683 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
684 params().isbackgroundcolor = false;
685 params().fontcolor = lyx::rgbFromHexName("#000000");
686 params().isfontcolor = false;
687 params().notefontcolor = lyx::rgbFromHexName("#cccccc");
688 params().boxbgcolor = lyx::rgbFromHexName("#ff0000");
689 params().html_latex_start.clear();
690 params().html_latex_end.clear();
691 params().html_math_img_scale = 1.0;
692 params().output_sync_macro.erase();
694 for (int i = 0; i < 4; ++i) {
695 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
696 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
699 ErrorList & errorList = d->errorLists["Parse"];
708 if (token == "\\end_header")
712 if (token == "\\begin_header") {
713 begin_header_line = line;
717 LYXERR(Debug::PARSER, "Handling document header token: `"
720 string unknown = params().readToken(lex, token, d->filename.onlyPath());
721 if (!unknown.empty()) {
722 if (unknown[0] != '\\' && token == "\\textclass") {
723 Alert::warning(_("Unknown document class"),
724 bformat(_("Using the default document class, because the "
725 "class %1$s is unknown."), from_utf8(unknown)));
728 docstring const s = bformat(_("Unknown token: "
732 errorList.push_back(ErrorItem(_("Document header error"),
737 if (begin_header_line) {
738 docstring const s = _("\\begin_header is missing");
739 errorList.push_back(ErrorItem(_("Document header error"),
743 params().makeDocumentClass();
745 return unknown_tokens;
750 // changed to be public and have one parameter
751 // Returns true if "\end_document" is not read (Asger)
752 bool Buffer::readDocument(Lexer & lex)
754 ErrorList & errorList = d->errorLists["Parse"];
757 // remove dummy empty par
758 paragraphs().clear();
760 if (!lex.checkFor("\\begin_document")) {
761 docstring const s = _("\\begin_document is missing");
762 errorList.push_back(ErrorItem(_("Document header error"),
768 if (params().outputChanges) {
769 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
770 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
771 LaTeXFeatures::isAvailable("xcolor");
773 if (!dvipost && !xcolorulem) {
774 Alert::warning(_("Changes not shown in LaTeX output"),
775 _("Changes will not be highlighted in LaTeX output, "
776 "because neither dvipost nor xcolor/ulem are installed.\n"
777 "Please install these packages or redefine "
778 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
779 } else if (!xcolorulem) {
780 Alert::warning(_("Changes not shown in LaTeX output"),
781 _("Changes will not be highlighted in LaTeX output "
782 "when using pdflatex, because xcolor and ulem are not installed.\n"
783 "Please install both packages or redefine "
784 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
788 if (!params().master.empty()) {
789 FileName const master_file = makeAbsPath(params().master,
790 onlyPath(absFileName()));
791 if (isLyXFileName(master_file.absFileName())) {
793 checkAndLoadLyXFile(master_file, true);
795 // necessary e.g. after a reload
796 // to re-register the child (bug 5873)
797 // FIXME: clean up updateMacros (here, only
798 // child registering is needed).
799 master->updateMacros();
800 // set master as master buffer, but only
801 // if we are a real child
802 if (master->isChild(this))
804 // if the master is not fully loaded
805 // it is probably just loading this
806 // child. No warning needed then.
807 else if (master->isFullyLoaded())
808 LYXERR0("The master '"
810 << "' assigned to this document ("
812 << ") does not include "
813 "this document. Ignoring the master assignment.");
818 // assure we have a default index
819 params().indiceslist().addDefault(B_("Index"));
822 bool const res = text().read(lex, errorList, d->inset);
826 updateMacroInstances();
831 bool Buffer::readString(string const & s)
833 params().compressed = false;
838 FileName const fn = FileName::tempName("Buffer_readString");
841 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
842 if (ret_plf != ReadSuccess)
845 if (file_format != LYX_FORMAT) {
846 // We need to call lyx2lyx, so write the input to a file
847 ofstream os(fn.toFilesystemEncoding().c_str());
851 return readFile(fn) == ReadSuccess;
854 if (readDocument(lex))
860 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
867 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
868 if (ret_plf != ReadSuccess)
871 if (file_format != LYX_FORMAT) {
873 ReadStatus const ret_clf = convertLyXFormat(fn, tmpFile, file_format);
874 if (ret_clf != ReadSuccess)
876 return readFile(tmpFile);
879 if (readDocument(lex)) {
880 Alert::error(_("Document format failure"),
881 bformat(_("%1$s ended unexpectedly, which means"
882 " that it is probably corrupted."),
883 from_utf8(fn.absFileName())));
884 return ReadDocumentFailure;
887 d->file_fully_loaded = true;
888 // InsetInfo needs to know if file is under VCS
889 lyxvc().file_found_hook(fn);
890 d->read_only = !fname.isWritable();
891 params().compressed = fname.isZippedFile();
897 bool Buffer::isFullyLoaded() const
899 return d->file_fully_loaded;
903 void Buffer::setFullyLoaded(bool value)
905 d->file_fully_loaded = value;
909 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
910 FileName const & fn, int & file_format) const
912 if(!lex.checkFor("\\lyxformat")) {
913 Alert::error(_("Document format failure"),
914 bformat(_("%1$s is not a readable LyX document."),
915 from_utf8(fn.absFileName())));
916 return ReadNoLyXFormat;
922 // LyX formats 217 and earlier were written as 2.17. This corresponds
923 // to files from LyX versions < 1.1.6.3. We just remove the dot in
924 // these cases. See also: www.lyx.org/trac/changeset/1313.
925 size_t dot = tmp_format.find_first_of(".,");
926 if (dot != string::npos)
927 tmp_format.erase(dot, 1);
929 file_format = convert<int>(tmp_format);
934 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
935 FileName & tmpfile, int from_format)
937 tmpfile = FileName::tempName("Buffer_convertLyXFormat");
938 if(tmpfile.empty()) {
939 Alert::error(_("Conversion failed"),
940 bformat(_("%1$s is from a different"
941 " version of LyX, but a temporary"
942 " file for converting it could"
944 from_utf8(fn.absFileName())));
945 return LyX2LyXNoTempFile;
948 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
949 if (lyx2lyx.empty()) {
950 Alert::error(_("Conversion script not found"),
951 bformat(_("%1$s is from a different"
952 " version of LyX, but the"
953 " conversion script lyx2lyx"
954 " could not be found."),
955 from_utf8(fn.absFileName())));
956 return LyX2LyXNotFound;
960 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
961 ostringstream command;
962 command << os::python()
963 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
964 << " -t " << convert<string>(LYX_FORMAT)
965 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
966 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
967 string const command_str = command.str();
969 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
971 cmd_ret const ret = runCommand(command_str);
972 if (ret.first != 0) {
973 if (from_format < LYX_FORMAT) {
974 Alert::error(_("Conversion script failed"),
975 bformat(_("%1$s is from an older version"
976 " of LyX, but the lyx2lyx script"
977 " failed to convert it."),
978 from_utf8(fn.absFileName())));
979 return LyX2LyXOlderFormat;
981 Alert::error(_("Conversion script failed"),
982 bformat(_("%1$s is from an newer version"
983 " of LyX, but the lyx2lyx script"
984 " failed to convert it."),
985 from_utf8(fn.absFileName())));
986 return LyX2LyXNewerFormat;
993 // Should probably be moved to somewhere else: BufferView? GuiView?
994 bool Buffer::save() const
996 // ask if the disk file has been externally modified (use checksum method)
997 if (fileName().exists() && isExternallyModified(checksum_method)) {
998 docstring const file = makeDisplayPath(absFileName(), 20);
999 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
1000 "you want to overwrite this file?"), file);
1001 int const ret = Alert::prompt(_("Overwrite modified file?"),
1002 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1007 // We don't need autosaves in the immediate future. (Asger)
1008 resetAutosaveTimers();
1010 FileName backupName;
1011 bool madeBackup = false;
1013 // make a backup if the file already exists
1014 if (lyxrc.make_backup && fileName().exists()) {
1015 backupName = FileName(absFileName() + '~');
1016 if (!lyxrc.backupdir_path.empty()) {
1017 string const mangledName =
1018 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1019 backupName = FileName(addName(lyxrc.backupdir_path,
1022 // do not copy because of #6587
1023 if (fileName().moveTo(backupName)) {
1026 Alert::error(_("Backup failure"),
1027 bformat(_("Cannot create backup file %1$s.\n"
1028 "Please check whether the directory exists and is writeable."),
1029 from_utf8(backupName.absFileName())));
1030 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1034 if (writeFile(d->filename)) {
1038 // Saving failed, so backup is not backup
1040 backupName.moveTo(d->filename);
1046 bool Buffer::writeFile(FileName const & fname) const
1048 if (d->read_only && fname == d->filename)
1051 bool retval = false;
1053 docstring const str = bformat(_("Saving document %1$s..."),
1054 makeDisplayPath(fname.absFileName()));
1057 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1059 if (params().compressed) {
1060 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1061 retval = ofs && write(ofs);
1063 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1064 retval = ofs && write(ofs);
1068 message(str + _(" could not write file!"));
1073 // removeAutosaveFile();
1076 message(str + _(" done."));
1082 docstring Buffer::emergencyWrite()
1084 // No need to save if the buffer has not changed.
1088 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1090 docstring user_message = bformat(
1091 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1093 // We try to save three places:
1094 // 1) Same place as document. Unless it is an unnamed doc.
1096 string s = absFileName();
1099 if (writeFile(FileName(s))) {
1101 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1102 return user_message;
1104 user_message += _(" Save failed! Trying again...\n");
1108 // 2) In HOME directory.
1109 string s = addName(package().home_dir().absFileName(), absFileName());
1111 lyxerr << ' ' << s << endl;
1112 if (writeFile(FileName(s))) {
1114 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1115 return user_message;
1118 user_message += _(" Save failed! Trying yet again...\n");
1120 // 3) In "/tmp" directory.
1121 // MakeAbsPath to prepend the current
1122 // drive letter on OS/2
1123 s = addName(package().temp_dir().absFileName(), absFileName());
1125 lyxerr << ' ' << s << endl;
1126 if (writeFile(FileName(s))) {
1128 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1129 return user_message;
1132 user_message += _(" Save failed! Bummer. Document is lost.");
1135 return user_message;
1139 bool Buffer::write(ostream & ofs) const
1142 // Use the standard "C" locale for file output.
1143 ofs.imbue(locale::classic());
1146 // The top of the file should not be written by params().
1148 // write out a comment in the top of the file
1149 ofs << "#LyX " << lyx_version
1150 << " created this file. For more info see http://www.lyx.org/\n"
1151 << "\\lyxformat " << LYX_FORMAT << "\n"
1152 << "\\begin_document\n";
1154 /// For each author, set 'used' to true if there is a change
1155 /// by this author in the document; otherwise set it to 'false'.
1156 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1157 AuthorList::Authors::const_iterator a_end = params().authors().end();
1158 for (; a_it != a_end; ++a_it)
1159 a_it->setUsed(false);
1161 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1162 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1163 for ( ; it != end; ++it)
1164 it->checkAuthors(params().authors());
1166 // now write out the buffer parameters.
1167 ofs << "\\begin_header\n";
1168 params().writeFile(ofs);
1169 ofs << "\\end_header\n";
1172 ofs << "\n\\begin_body\n";
1174 ofs << "\n\\end_body\n";
1176 // Write marker that shows file is complete
1177 ofs << "\\end_document" << endl;
1179 // Shouldn't really be needed....
1182 // how to check if close went ok?
1183 // Following is an attempt... (BE 20001011)
1185 // good() returns false if any error occured, including some
1186 // formatting error.
1187 // bad() returns true if something bad happened in the buffer,
1188 // which should include file system full errors.
1193 lyxerr << "File was not closed properly." << endl;
1200 bool Buffer::makeLaTeXFile(FileName const & fname,
1201 string const & original_path,
1202 OutputParams const & runparams_in,
1203 bool output_preamble, bool output_body) const
1205 OutputParams runparams = runparams_in;
1206 if (params().useXetex)
1207 runparams.flavor = OutputParams::XETEX;
1209 string const encoding = runparams.encoding->iconvName();
1210 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1213 try { ofs.reset(encoding); }
1214 catch (iconv_codecvt_facet_exception & e) {
1215 lyxerr << "Caught iconv exception: " << e.what() << endl;
1216 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1217 "verify that the support software for your encoding (%1$s) is "
1218 "properly installed"), from_ascii(encoding)));
1221 if (!openFileWrite(ofs, fname))
1224 //TexStream ts(ofs.rdbuf(), &texrow());
1225 ErrorList & errorList = d->errorLists["Export"];
1227 bool failed_export = false;
1230 writeLaTeXSource(ofs, original_path,
1231 runparams, output_preamble, output_body);
1233 catch (EncodingException & e) {
1234 odocstringstream ods;
1235 ods.put(e.failed_char);
1237 oss << "0x" << hex << e.failed_char << dec;
1238 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1239 " (code point %2$s)"),
1240 ods.str(), from_utf8(oss.str()));
1241 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1242 "representable in the chosen encoding.\n"
1243 "Changing the document encoding to utf8 could help."),
1244 e.par_id, e.pos, e.pos + 1));
1245 failed_export = true;
1247 catch (iconv_codecvt_facet_exception & e) {
1248 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1249 _(e.what()), -1, 0, 0));
1250 failed_export = true;
1252 catch (exception const & e) {
1253 errorList.push_back(ErrorItem(_("conversion failed"),
1254 _(e.what()), -1, 0, 0));
1255 failed_export = true;
1258 lyxerr << "Caught some really weird exception..." << endl;
1264 failed_export = true;
1265 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1269 return !failed_export;
1273 void Buffer::writeLaTeXSource(odocstream & os,
1274 string const & original_path,
1275 OutputParams const & runparams_in,
1276 bool const output_preamble, bool const output_body) const
1278 // The child documents, if any, shall be already loaded at this point.
1280 OutputParams runparams = runparams_in;
1282 // Classify the unicode characters appearing in math insets
1283 Encodings::initUnicodeMath(*this);
1285 // validate the buffer.
1286 LYXERR(Debug::LATEX, " Validating buffer...");
1287 LaTeXFeatures features(*this, params(), runparams);
1289 LYXERR(Debug::LATEX, " Buffer validation done.");
1291 // The starting paragraph of the coming rows is the
1292 // first paragraph of the document. (Asger)
1293 if (output_preamble && runparams.nice) {
1294 os << "%% LyX " << lyx_version << " created this file. "
1295 "For more info, see http://www.lyx.org/.\n"
1296 "%% Do not edit unless you really know what "
1298 d->texrow.newline();
1299 d->texrow.newline();
1301 LYXERR(Debug::INFO, "lyx document header finished");
1303 // Don't move this behind the parent_buffer=0 code below,
1304 // because then the macros will not get the right "redefinition"
1305 // flag as they don't see the parent macros which are output before.
1308 // fold macros if possible, still with parent buffer as the
1309 // macros will be put in the prefix anyway.
1310 updateMacroInstances();
1312 // There are a few differences between nice LaTeX and usual files:
1313 // usual is \batchmode and has a
1314 // special input@path to allow the including of figures
1315 // with either \input or \includegraphics (what figinsets do).
1316 // input@path is set when the actual parameter
1317 // original_path is set. This is done for usual tex-file, but not
1318 // for nice-latex-file. (Matthias 250696)
1319 // Note that input@path is only needed for something the user does
1320 // in the preamble, included .tex files or ERT, files included by
1321 // LyX work without it.
1322 if (output_preamble) {
1323 if (!runparams.nice) {
1324 // code for usual, NOT nice-latex-file
1325 os << "\\batchmode\n"; // changed
1326 // from \nonstopmode
1327 d->texrow.newline();
1329 if (!original_path.empty()) {
1331 // We don't know the encoding of inputpath
1332 docstring const inputpath = from_utf8(support::latex_path(original_path));
1333 docstring uncodable_glyphs;
1334 Encoding const * const enc = runparams.encoding;
1336 for (size_t n = 0; n < inputpath.size(); ++n) {
1337 docstring const glyph =
1338 docstring(1, inputpath[n]);
1339 if (enc->latexChar(inputpath[n], true) != glyph) {
1340 LYXERR0("Uncodable character '"
1342 << "' in input path!");
1343 uncodable_glyphs += glyph;
1348 // warn user if we found uncodable glyphs.
1349 if (!uncodable_glyphs.empty()) {
1350 frontend::Alert::warning(_("Uncodable character in file path"),
1351 support::bformat(_("The path of your document\n"
1353 "contains glyphs that are unknown in the\n"
1354 "current document encoding (namely %2$s).\n"
1355 "This will likely result in incomplete output.\n\n"
1356 "Choose an appropriate document encoding (such as utf8)\n"
1357 "or change the file path name."), inputpath, uncodable_glyphs));
1359 os << "\\makeatletter\n"
1360 << "\\def\\input@path{{"
1361 << inputpath << "/}}\n"
1362 << "\\makeatother\n";
1363 d->texrow.newline();
1364 d->texrow.newline();
1365 d->texrow.newline();
1369 // get parent macros (if this buffer has a parent) which will be
1370 // written at the document begin further down.
1371 MacroSet parentMacros;
1372 listParentMacros(parentMacros, features);
1374 // Write the preamble
1375 runparams.use_babel = params().writeLaTeX(os, features,
1377 d->filename.onlyPath());
1379 runparams.use_japanese = features.isRequired("japanese");
1385 os << "\\begin{document}\n";
1386 d->texrow.newline();
1388 // output the parent macros
1389 MacroSet::iterator it = parentMacros.begin();
1390 MacroSet::iterator end = parentMacros.end();
1391 for (; it != end; ++it) {
1392 int num_lines = (*it)->write(os, true);
1393 d->texrow.newlines(num_lines);
1396 } // output_preamble
1398 d->texrow.start(paragraphs().begin()->id(), 0);
1400 LYXERR(Debug::INFO, "preamble finished, now the body.");
1402 // if we are doing a real file with body, even if this is the
1403 // child of some other buffer, let's cut the link here.
1404 // This happens for example if only a child document is printed.
1405 Buffer const * save_parent = 0;
1406 if (output_preamble) {
1407 save_parent = d->parent();
1412 latexParagraphs(*this, text(), os, d->texrow, runparams);
1414 // Restore the parenthood if needed
1415 if (output_preamble)
1416 d->setParent(save_parent);
1418 // add this just in case after all the paragraphs
1420 d->texrow.newline();
1422 if (output_preamble) {
1423 os << "\\end{document}\n";
1424 d->texrow.newline();
1425 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1427 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1429 runparams_in.encoding = runparams.encoding;
1431 // Just to be sure. (Asger)
1432 d->texrow.newline();
1434 //for (int i = 0; i<d->texrow.rows(); i++) {
1436 // if (d->texrow.getIdFromRow(i+1,id,pos) && id>0)
1437 // lyxerr << i+1 << ":" << id << ":" << getParFromID(id).paragraph().asString()<<"\n";
1440 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1441 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1445 bool Buffer::isLatex() const
1447 return params().documentClass().outputType() == LATEX;
1451 bool Buffer::isLiterate() const
1453 return params().documentClass().outputType() == LITERATE;
1457 bool Buffer::isDocBook() const
1459 return params().documentClass().outputType() == DOCBOOK;
1463 void Buffer::makeDocBookFile(FileName const & fname,
1464 OutputParams const & runparams,
1465 bool const body_only) const
1467 LYXERR(Debug::LATEX, "makeDocBookFile...");
1470 if (!openFileWrite(ofs, fname))
1473 writeDocBookSource(ofs, fname.absFileName(), runparams, body_only);
1477 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1481 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1482 OutputParams const & runparams,
1483 bool const only_body) const
1485 LaTeXFeatures features(*this, params(), runparams);
1490 DocumentClass const & tclass = params().documentClass();
1491 string const top_element = tclass.latexname();
1494 if (runparams.flavor == OutputParams::XML)
1495 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1498 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1501 if (! tclass.class_header().empty())
1502 os << from_ascii(tclass.class_header());
1503 else if (runparams.flavor == OutputParams::XML)
1504 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1505 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1507 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1509 docstring preamble = from_utf8(params().preamble);
1510 if (runparams.flavor != OutputParams::XML ) {
1511 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1512 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1513 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1514 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1517 string const name = runparams.nice
1518 ? changeExtension(absFileName(), ".sgml") : fname;
1519 preamble += features.getIncludedFiles(name);
1520 preamble += features.getLyXSGMLEntities();
1522 if (!preamble.empty()) {
1523 os << "\n [ " << preamble << " ]";
1528 string top = top_element;
1530 if (runparams.flavor == OutputParams::XML)
1531 top += params().language->code();
1533 top += params().language->code().substr(0, 2);
1536 if (!params().options.empty()) {
1538 top += params().options;
1541 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1542 << " file was created by LyX " << lyx_version
1543 << "\n See http://www.lyx.org/ for more information -->\n";
1545 params().documentClass().counters().reset();
1549 sgml::openTag(os, top);
1551 docbookParagraphs(text(), *this, os, runparams);
1552 sgml::closeTag(os, top_element);
1556 void Buffer::makeLyXHTMLFile(FileName const & fname,
1557 OutputParams const & runparams,
1558 bool const body_only) const
1560 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1563 if (!openFileWrite(ofs, fname))
1566 writeLyXHTMLSource(ofs, runparams, body_only);
1570 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1574 void Buffer::writeLyXHTMLSource(odocstream & os,
1575 OutputParams const & runparams,
1576 bool const only_body) const
1578 LaTeXFeatures features(*this, params(), runparams);
1580 updateBuffer(UpdateMaster, OutputUpdate);
1581 d->bibinfo_.makeCitationLabels(*this);
1583 updateMacroInstances();
1586 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1587 << "<!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"
1588 // FIXME Language should be set properly.
1589 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
1591 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
1592 // FIXME Presumably need to set this right
1593 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1595 docstring const & doctitle = features.htmlTitle();
1597 << (doctitle.empty() ? from_ascii("LyX Document") : doctitle)
1600 os << "\n<!-- Text Class Preamble -->\n"
1601 << features.getTClassHTMLPreamble()
1602 << "\n<!-- Premable Snippets -->\n"
1603 << from_utf8(features.getPreambleSnippets());
1605 os << "\n<!-- Layout-provided Styles -->\n";
1606 docstring const styleinfo = features.getTClassHTMLStyles();
1607 if (!styleinfo.empty()) {
1608 os << "<style type='text/css'>\n"
1612 os << "</head>\n<body>\n";
1616 params().documentClass().counters().reset();
1617 xhtmlParagraphs(text(), *this, xs, runparams);
1619 os << "</body>\n</html>\n";
1623 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1624 // Other flags: -wall -v0 -x
1625 int Buffer::runChktex()
1629 // get LaTeX-Filename
1630 FileName const path(temppath());
1631 string const name = addName(path.absFileName(), latexName());
1632 string const org_path = filePath();
1634 PathChanger p(path); // path to LaTeX file
1635 message(_("Running chktex..."));
1637 // Generate the LaTeX file if neccessary
1638 OutputParams runparams(¶ms().encoding());
1639 runparams.flavor = OutputParams::LATEX;
1640 runparams.nice = false;
1641 runparams.linelen = lyxrc.plaintext_linelen;
1642 makeLaTeXFile(FileName(name), org_path, runparams);
1645 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
1646 int const res = chktex.run(terr); // run chktex
1649 Alert::error(_("chktex failure"),
1650 _("Could not run chktex successfully."));
1651 } else if (res > 0) {
1652 ErrorList & errlist = d->errorLists["ChkTeX"];
1654 bufferErrors(terr, errlist);
1665 void Buffer::validate(LaTeXFeatures & features) const
1667 params().validate(features);
1671 for_each(paragraphs().begin(), paragraphs().end(),
1672 bind(&Paragraph::validate, _1, ref(features)));
1674 if (lyxerr.debugging(Debug::LATEX)) {
1675 features.showStruct();
1680 void Buffer::getLabelList(vector<docstring> & list) const
1682 // If this is a child document, use the master's list instead.
1684 masterBuffer()->getLabelList(list);
1689 Toc & toc = d->toc_backend.toc("label");
1690 TocIterator toc_it = toc.begin();
1691 TocIterator end = toc.end();
1692 for (; toc_it != end; ++toc_it) {
1693 if (toc_it->depth() == 0)
1694 list.push_back(toc_it->str());
1699 void Buffer::updateBibfilesCache(UpdateScope scope) const
1701 // FIXME This is probably unnecssary, given where we call this.
1702 // If this is a child document, use the parent's cache instead.
1703 if (parent() && scope != UpdateChildOnly) {
1704 masterBuffer()->updateBibfilesCache();
1708 d->bibfiles_cache_.clear();
1709 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1710 if (it->lyxCode() == BIBTEX_CODE) {
1711 InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
1712 support::FileNameList const bibfiles = inset.getBibFiles();
1713 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1716 } else if (it->lyxCode() == INCLUDE_CODE) {
1717 InsetInclude & inset = static_cast<InsetInclude &>(*it);
1718 Buffer const * const incbuf = inset.getChildBuffer();
1721 support::FileNameList const & bibfiles =
1722 incbuf->getBibfilesCache(UpdateChildOnly);
1723 if (!bibfiles.empty()) {
1724 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1730 d->bibfile_cache_valid_ = true;
1731 d->bibinfo_cache_valid_ = false;
1735 void Buffer::invalidateBibinfoCache() const
1737 d->bibinfo_cache_valid_ = false;
1738 // also invalidate the cache for the parent buffer
1739 Buffer const * const pbuf = d->parent();
1741 pbuf->invalidateBibinfoCache();
1745 void Buffer::invalidateBibfileCache() const
1747 d->bibfile_cache_valid_ = false;
1748 d->bibinfo_cache_valid_ = false;
1749 // also invalidate the cache for the parent buffer
1750 Buffer const * const pbuf = d->parent();
1752 pbuf->invalidateBibfileCache();
1756 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1758 // FIXME This is probably unnecessary, given where we call this.
1759 // If this is a child document, use the master's cache instead.
1760 Buffer const * const pbuf = masterBuffer();
1761 if (pbuf != this && scope != UpdateChildOnly)
1762 return pbuf->getBibfilesCache();
1764 if (!d->bibfile_cache_valid_)
1765 this->updateBibfilesCache(scope);
1767 return d->bibfiles_cache_;
1771 BiblioInfo const & Buffer::masterBibInfo() const
1773 Buffer const * const tmp = masterBuffer();
1775 return tmp->masterBibInfo();
1780 void Buffer::checkBibInfoCache() const
1782 // use the master's cache
1783 Buffer const * const tmp = masterBuffer();
1785 tmp->checkBibInfoCache();
1789 // this will also reload the cache if it is invalid
1790 support::FileNameList const & bibfiles_cache = getBibfilesCache();
1792 // compare the cached timestamps with the actual ones.
1793 support::FileNameList::const_iterator ei = bibfiles_cache.begin();
1794 support::FileNameList::const_iterator en = bibfiles_cache.end();
1795 for (; ei != en; ++ ei) {
1796 time_t lastw = ei->lastModified();
1797 time_t prevw = d->bibfile_status_[*ei];
1798 if (lastw != prevw) {
1799 d->bibinfo_cache_valid_ = false;
1800 d->bibfile_status_[*ei] = lastw;
1804 // if not valid, then reload the info
1805 if (!d->bibinfo_cache_valid_) {
1806 d->bibinfo_.clear();
1807 fillWithBibKeys(d->bibinfo_);
1808 d->bibinfo_cache_valid_ = true;
1813 void Buffer::fillWithBibKeys(BiblioInfo & keys) const
1815 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1816 it->fillWithBibKeys(keys, it);
1820 bool Buffer::isDepClean(string const & name) const
1822 DepClean::const_iterator const it = d->dep_clean.find(name);
1823 if (it == d->dep_clean.end())
1829 void Buffer::markDepClean(string const & name)
1831 d->dep_clean[name] = true;
1835 bool Buffer::isExportableFormat(string const & format) const
1837 typedef vector<Format const *> Formats;
1839 formats = exportableFormats(true);
1840 Formats::const_iterator fit = formats.begin();
1841 Formats::const_iterator end = formats.end();
1842 for (; fit != end ; ++fit) {
1843 if ((*fit)->name() == format)
1850 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1853 // FIXME? if there is an Buffer LFUN that can be dispatched even
1854 // if internal, put a switch '(cmd.action)' here.
1860 switch (cmd.action()) {
1862 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1863 flag.setOnOff(isReadonly());
1866 // FIXME: There is need for a command-line import.
1867 //case LFUN_BUFFER_IMPORT:
1869 case LFUN_BUFFER_AUTO_SAVE:
1872 case LFUN_BUFFER_EXPORT_CUSTOM:
1873 // FIXME: Nothing to check here?
1876 case LFUN_BUFFER_EXPORT: {
1877 docstring const arg = cmd.argument();
1878 enable = arg == "custom" || isExportable(to_utf8(arg));
1880 flag.message(bformat(
1881 _("Don't know how to export to format: %1$s"), arg));
1885 case LFUN_BUFFER_CHKTEX:
1886 enable = isLatex() && !lyxrc.chktex_command.empty();
1889 case LFUN_BUILD_PROGRAM:
1890 enable = isExportable("program");
1893 case LFUN_BRANCH_ACTIVATE:
1894 case LFUN_BRANCH_DEACTIVATE: {
1895 BranchList const & branchList = params().branchlist();
1896 docstring const branchName = cmd.argument();
1897 enable = !branchName.empty() && branchList.find(branchName);
1901 case LFUN_BRANCH_ADD:
1902 case LFUN_BRANCHES_RENAME:
1903 case LFUN_BUFFER_PRINT:
1904 // if no Buffer is present, then of course we won't be called!
1907 case LFUN_BUFFER_LANGUAGE:
1908 enable = !isReadonly();
1914 flag.setEnabled(enable);
1919 void Buffer::dispatch(string const & command, DispatchResult & result)
1921 return dispatch(lyxaction.lookupFunc(command), result);
1925 // NOTE We can end up here even if we have no GUI, because we are called
1926 // by LyX::exec to handled command-line requests. So we may need to check
1927 // whether we have a GUI or not. The boolean use_gui holds this information.
1928 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
1931 // FIXME? if there is an Buffer LFUN that can be dispatched even
1932 // if internal, put a switch '(cmd.action())' here.
1933 dr.dispatched(false);
1936 string const argument = to_utf8(func.argument());
1937 // We'll set this back to false if need be.
1938 bool dispatched = true;
1939 undo().beginUndoGroup();
1941 switch (func.action()) {
1942 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1943 if (lyxvc().inUse())
1944 lyxvc().toggleReadOnly();
1946 setReadonly(!isReadonly());
1949 case LFUN_BUFFER_EXPORT: {
1950 bool success = doExport(argument, false, false);
1951 dr.setError(!success);
1953 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
1958 case LFUN_BUILD_PROGRAM:
1959 doExport("program", true, false);
1962 case LFUN_BUFFER_CHKTEX:
1966 case LFUN_BUFFER_EXPORT_CUSTOM: {
1968 string command = split(argument, format_name, ' ');
1969 Format const * format = formats.getFormat(format_name);
1971 lyxerr << "Format \"" << format_name
1972 << "\" not recognized!"
1977 // The name of the file created by the conversion process
1980 // Output to filename
1981 if (format->name() == "lyx") {
1982 string const latexname = latexName(false);
1983 filename = changeExtension(latexname,
1984 format->extension());
1985 filename = addName(temppath(), filename);
1987 if (!writeFile(FileName(filename)))
1991 doExport(format_name, true, false, filename);
1994 // Substitute $$FName for filename
1995 if (!contains(command, "$$FName"))
1996 command = "( " + command + " ) < $$FName";
1997 command = subst(command, "$$FName", filename);
1999 // Execute the command in the background
2001 call.startscript(Systemcall::DontWait, command);
2005 // FIXME: There is need for a command-line import.
2007 case LFUN_BUFFER_IMPORT:
2012 case LFUN_BUFFER_AUTO_SAVE:
2016 case LFUN_BRANCH_ADD: {
2017 docstring branch_name = func.argument();
2018 if (branch_name.empty()) {
2022 BranchList & branch_list = params().branchlist();
2023 vector<docstring> const branches =
2024 getVectorFromString(branch_name, branch_list.separator());
2026 for (vector<docstring>::const_iterator it = branches.begin();
2027 it != branches.end(); ++it) {
2029 Branch * branch = branch_list.find(branch_name);
2031 LYXERR0("Branch " << branch_name << " already exists.");
2035 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2037 branch_list.add(branch_name);
2038 branch = branch_list.find(branch_name);
2039 string const x11hexname = X11hexname(branch->color());
2040 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2041 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2043 dr.screenUpdate(Update::Force);
2051 case LFUN_BRANCH_ACTIVATE:
2052 case LFUN_BRANCH_DEACTIVATE: {
2053 BranchList & branchList = params().branchlist();
2054 docstring const branchName = func.argument();
2055 // the case without a branch name is handled elsewhere
2056 if (branchName.empty()) {
2060 Branch * branch = branchList.find(branchName);
2062 LYXERR0("Branch " << branchName << " does not exist.");
2064 docstring const msg =
2065 bformat(_("Branch \"%1$s\" does not exist."), branchName);
2068 branch->setSelected(func.action() == LFUN_BRANCH_ACTIVATE);
2070 dr.screenUpdate(Update::Force);
2071 dr.forceBufferUpdate();
2076 case LFUN_BRANCHES_RENAME: {
2077 if (func.argument().empty())
2080 docstring const oldname = from_utf8(func.getArg(0));
2081 docstring const newname = from_utf8(func.getArg(1));
2082 InsetIterator it = inset_iterator_begin(inset());
2083 InsetIterator const end = inset_iterator_end(inset());
2084 bool success = false;
2085 for (; it != end; ++it) {
2086 if (it->lyxCode() == BRANCH_CODE) {
2087 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2088 if (ins.branch() == oldname) {
2089 undo().recordUndo(it);
2090 ins.rename(newname);
2095 if (it->lyxCode() == INCLUDE_CODE) {
2096 // get buffer of external file
2097 InsetInclude const & ins =
2098 static_cast<InsetInclude const &>(*it);
2099 Buffer * child = ins.getChildBuffer();
2102 child->dispatch(func, dr);
2107 dr.screenUpdate(Update::Force);
2108 dr.forceBufferUpdate();
2113 case LFUN_BUFFER_PRINT: {
2114 // we'll assume there's a problem until we succeed
2116 string target = func.getArg(0);
2117 string target_name = func.getArg(1);
2118 string command = func.getArg(2);
2121 || target_name.empty()
2122 || command.empty()) {
2123 LYXERR0("Unable to parse " << func.argument());
2124 docstring const msg =
2125 bformat(_("Unable to parse \"%1$s\""), func.argument());
2129 if (target != "printer" && target != "file") {
2130 LYXERR0("Unrecognized target \"" << target << '"');
2131 docstring const msg =
2132 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2137 bool const update_unincluded =
2138 params().maintain_unincluded_children
2139 && !params().getIncludedChildren().empty();
2140 if (!doExport("dvi", true, update_unincluded)) {
2141 showPrintError(absFileName());
2142 dr.setMessage(_("Error exporting to DVI."));
2146 // Push directory path.
2147 string const path = temppath();
2148 // Prevent the compiler from optimizing away p
2152 // there are three cases here:
2153 // 1. we print to a file
2154 // 2. we print directly to a printer
2155 // 3. we print using a spool command (print to file first)
2158 string const dviname = changeExtension(latexName(true), "dvi");
2160 if (target == "printer") {
2161 if (!lyxrc.print_spool_command.empty()) {
2162 // case 3: print using a spool
2163 string const psname = changeExtension(dviname,".ps");
2164 command += ' ' + lyxrc.print_to_file
2167 + quoteName(dviname);
2169 string command2 = lyxrc.print_spool_command + ' ';
2170 if (target_name != "default") {
2171 command2 += lyxrc.print_spool_printerprefix
2175 command2 += quoteName(psname);
2177 // If successful, then spool command
2178 res = one.startscript(Systemcall::Wait, command);
2181 // If there's no GUI, we have to wait on this command. Otherwise,
2182 // LyX deletes the temporary directory, and with it the spooled
2183 // file, before it can be printed!!
2184 Systemcall::Starttype stype = use_gui ?
2185 Systemcall::DontWait : Systemcall::Wait;
2186 res = one.startscript(stype, command2);
2189 // case 2: print directly to a printer
2190 if (target_name != "default")
2191 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2193 Systemcall::Starttype stype = use_gui ?
2194 Systemcall::DontWait : Systemcall::Wait;
2195 res = one.startscript(stype, command + quoteName(dviname));
2199 // case 1: print to a file
2200 FileName const filename(makeAbsPath(target_name, filePath()));
2201 FileName const dvifile(makeAbsPath(dviname, path));
2202 if (filename.exists()) {
2203 docstring text = bformat(
2204 _("The file %1$s already exists.\n\n"
2205 "Do you want to overwrite that file?"),
2206 makeDisplayPath(filename.absFileName()));
2207 if (Alert::prompt(_("Overwrite file?"),
2208 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2211 command += ' ' + lyxrc.print_to_file
2212 + quoteName(filename.toFilesystemEncoding())
2214 + quoteName(dvifile.toFilesystemEncoding());
2216 Systemcall::Starttype stype = use_gui ?
2217 Systemcall::DontWait : Systemcall::Wait;
2218 res = one.startscript(stype, command);
2224 dr.setMessage(_("Error running external commands."));
2225 showPrintError(absFileName());
2230 case LFUN_BUFFER_LANGUAGE: {
2231 Language const * oldL = params().language;
2232 Language const * newL = languages.getLanguage(argument);
2233 if (!newL || oldL == newL)
2235 if (oldL->rightToLeft() == newL->rightToLeft() && !isMultiLingual()) {
2236 changeLanguage(oldL, newL);
2237 dr.forceBufferUpdate();
2246 dr.dispatched(dispatched);
2247 undo().endUndoGroup();
2251 void Buffer::changeLanguage(Language const * from, Language const * to)
2253 LASSERT(from, /**/);
2256 for_each(par_iterator_begin(),
2258 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2262 bool Buffer::isMultiLingual() const
2264 ParConstIterator end = par_iterator_end();
2265 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2266 if (it->isMultiLingual(params()))
2273 std::set<Language const *> Buffer::getLanguages() const
2275 std::set<Language const *> languages;
2276 getLanguages(languages);
2281 void Buffer::getLanguages(std::set<Language const *> & languages) const
2283 ParConstIterator end = par_iterator_end();
2284 // add the buffer language, even if it's not actively used
2285 languages.insert(language());
2286 // iterate over the paragraphs
2287 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2288 it->getLanguages(languages);
2290 ListOfBuffers clist = getDescendents();
2291 ListOfBuffers::const_iterator cit = clist.begin();
2292 ListOfBuffers::const_iterator const cen = clist.end();
2293 for (; cit != cen; ++cit)
2294 (*cit)->getLanguages(languages);
2298 DocIterator Buffer::getParFromID(int const id) const
2300 Buffer * buf = const_cast<Buffer *>(this);
2302 // John says this is called with id == -1 from undo
2303 lyxerr << "getParFromID(), id: " << id << endl;
2304 return doc_iterator_end(buf);
2307 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2308 if (it.paragraph().id() == id)
2311 return doc_iterator_end(buf);
2315 bool Buffer::hasParWithID(int const id) const
2317 return !getParFromID(id).atEnd();
2321 ParIterator Buffer::par_iterator_begin()
2323 return ParIterator(doc_iterator_begin(this));
2327 ParIterator Buffer::par_iterator_end()
2329 return ParIterator(doc_iterator_end(this));
2333 ParConstIterator Buffer::par_iterator_begin() const
2335 return ParConstIterator(doc_iterator_begin(this));
2339 ParConstIterator Buffer::par_iterator_end() const
2341 return ParConstIterator(doc_iterator_end(this));
2345 Language const * Buffer::language() const
2347 return params().language;
2351 docstring const Buffer::B_(string const & l10n) const
2353 return params().B_(l10n);
2357 bool Buffer::isClean() const
2359 return d->lyx_clean;
2363 bool Buffer::isExternallyModified(CheckMethod method) const
2365 LASSERT(d->filename.exists(), /**/);
2366 // if method == timestamp, check timestamp before checksum
2367 return (method == checksum_method
2368 || d->timestamp_ != d->filename.lastModified())
2369 && d->checksum_ != d->filename.checksum();
2373 void Buffer::saveCheckSum() const
2375 FileName const & file = d->filename;
2376 if (file.exists()) {
2377 d->timestamp_ = file.lastModified();
2378 d->checksum_ = file.checksum();
2380 // in the case of save to a new file.
2387 void Buffer::markClean() const
2389 if (!d->lyx_clean) {
2390 d->lyx_clean = true;
2393 // if the .lyx file has been saved, we don't need an
2395 d->bak_clean = true;
2396 d->undo_.markDirty();
2400 void Buffer::setUnnamed(bool flag)
2406 bool Buffer::isUnnamed() const
2413 /// Don't check unnamed, here: isInternal() is used in
2414 /// newBuffer(), where the unnamed flag has not been set by anyone
2415 /// yet. Also, for an internal buffer, there should be no need for
2416 /// retrieving fileName() nor for checking if it is unnamed or not.
2417 bool Buffer::isInternal() const
2419 return fileName().extension() == "internal";
2423 void Buffer::markDirty()
2426 d->lyx_clean = false;
2429 d->bak_clean = false;
2431 DepClean::iterator it = d->dep_clean.begin();
2432 DepClean::const_iterator const end = d->dep_clean.end();
2434 for (; it != end; ++it)
2439 FileName Buffer::fileName() const
2445 string Buffer::absFileName() const
2447 return d->filename.absFileName();
2451 string Buffer::filePath() const
2453 return d->filename.onlyPath().absFileName() + "/";
2457 bool Buffer::isReadonly() const
2459 return d->read_only;
2463 void Buffer::setParent(Buffer const * buffer)
2465 // Avoids recursive include.
2466 d->setParent(buffer == this ? 0 : buffer);
2471 Buffer const * Buffer::parent() const
2477 ListOfBuffers Buffer::allRelatives() const
2479 ListOfBuffers lb = masterBuffer()->getDescendents();
2480 lb.push_front(const_cast<Buffer *>(this));
2485 Buffer const * Buffer::masterBuffer() const
2487 // FIXME Should be make sure we are not in some kind
2488 // of recursive include? A -> B -> A will crash this.
2489 Buffer const * const pbuf = d->parent();
2493 return pbuf->masterBuffer();
2497 bool Buffer::isChild(Buffer * child) const
2499 return d->children_positions.find(child) != d->children_positions.end();
2503 DocIterator Buffer::firstChildPosition(Buffer const * child)
2505 Impl::BufferPositionMap::iterator it;
2506 it = d->children_positions.find(child);
2507 if (it == d->children_positions.end())
2508 return DocIterator(this);
2513 bool Buffer::hasChildren() const
2515 return !d->children_positions.empty();
2519 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
2521 // loop over children
2522 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2523 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2524 for (; it != end; ++it) {
2525 Buffer * child = const_cast<Buffer *>(it->first);
2527 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
2528 if (bit != clist.end())
2530 clist.push_back(child);
2532 // there might be grandchildren
2533 child->collectChildren(clist, true);
2538 ListOfBuffers Buffer::getChildren() const
2541 collectChildren(v, false);
2546 ListOfBuffers Buffer::getDescendents() const
2549 collectChildren(v, true);
2554 template<typename M>
2555 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
2560 typename M::const_iterator it = m.lower_bound(x);
2561 if (it == m.begin())
2569 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
2570 DocIterator const & pos) const
2572 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2574 // if paragraphs have no macro context set, pos will be empty
2578 // we haven't found anything yet
2579 DocIterator bestPos = owner_->par_iterator_begin();
2580 MacroData const * bestData = 0;
2582 // find macro definitions for name
2583 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
2584 if (nameIt != macros.end()) {
2585 // find last definition in front of pos or at pos itself
2586 PositionScopeMacroMap::const_iterator it
2587 = greatest_below(nameIt->second, pos);
2588 if (it != nameIt->second.end()) {
2590 // scope ends behind pos?
2591 if (pos < it->second.first) {
2592 // Looks good, remember this. If there
2593 // is no external macro behind this,
2594 // we found the right one already.
2595 bestPos = it->first;
2596 bestData = &it->second.second;
2600 // try previous macro if there is one
2601 if (it == nameIt->second.begin())
2608 // find macros in included files
2609 PositionScopeBufferMap::const_iterator it
2610 = greatest_below(position_to_children, pos);
2611 if (it == position_to_children.end())
2612 // no children before
2616 // do we know something better (i.e. later) already?
2617 if (it->first < bestPos )
2620 // scope ends behind pos?
2621 if (pos < it->second.first) {
2622 // look for macro in external file
2624 MacroData const * data
2625 = it->second.second->getMacro(name, false);
2628 bestPos = it->first;
2634 // try previous file if there is one
2635 if (it == position_to_children.begin())
2640 // return the best macro we have found
2645 MacroData const * Buffer::getMacro(docstring const & name,
2646 DocIterator const & pos, bool global) const
2651 // query buffer macros
2652 MacroData const * data = d->getBufferMacro(name, pos);
2656 // If there is a master buffer, query that
2657 Buffer const * const pbuf = d->parent();
2659 d->macro_lock = true;
2660 MacroData const * macro = pbuf->getMacro(
2661 name, *this, false);
2662 d->macro_lock = false;
2668 data = MacroTable::globalMacros().get(name);
2677 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2679 // set scope end behind the last paragraph
2680 DocIterator scope = par_iterator_begin();
2681 scope.pit() = scope.lastpit() + 1;
2683 return getMacro(name, scope, global);
2687 MacroData const * Buffer::getMacro(docstring const & name,
2688 Buffer const & child, bool global) const
2690 // look where the child buffer is included first
2691 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2692 if (it == d->children_positions.end())
2695 // check for macros at the inclusion position
2696 return getMacro(name, it->second, global);
2700 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
2702 pit_type const lastpit = it.lastpit();
2704 // look for macros in each paragraph
2705 while (it.pit() <= lastpit) {
2706 Paragraph & par = it.paragraph();
2708 // iterate over the insets of the current paragraph
2709 InsetList const & insets = par.insetList();
2710 InsetList::const_iterator iit = insets.begin();
2711 InsetList::const_iterator end = insets.end();
2712 for (; iit != end; ++iit) {
2713 it.pos() = iit->pos;
2715 // is it a nested text inset?
2716 if (iit->inset->asInsetText()) {
2717 // Inset needs its own scope?
2718 InsetText const * itext = iit->inset->asInsetText();
2719 bool newScope = itext->isMacroScope();
2721 // scope which ends just behind the inset
2722 DocIterator insetScope = it;
2725 // collect macros in inset
2726 it.push_back(CursorSlice(*iit->inset));
2727 updateMacros(it, newScope ? insetScope : scope);
2732 if (iit->inset->asInsetTabular()) {
2733 CursorSlice slice(*iit->inset);
2734 size_t const numcells = slice.nargs();
2735 for (; slice.idx() < numcells; slice.forwardIdx()) {
2736 it.push_back(slice);
2737 updateMacros(it, scope);
2743 // is it an external file?
2744 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2745 // get buffer of external file
2746 InsetInclude const & inset =
2747 static_cast<InsetInclude const &>(*iit->inset);
2749 Buffer * child = inset.getChildBuffer();
2754 // register its position, but only when it is
2755 // included first in the buffer
2756 if (children_positions.find(child) ==
2757 children_positions.end())
2758 children_positions[child] = it;
2760 // register child with its scope
2761 position_to_children[it] = Impl::ScopeBuffer(scope, child);
2765 InsetMath * im = iit->inset->asInsetMath();
2766 if (doing_export && im) {
2767 InsetMathHull * hull = im->asHullInset();
2769 hull->recordLocation(it);
2772 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2776 MathMacroTemplate & macroTemplate =
2777 *iit->inset->asInsetMath()->asMacroTemplate();
2778 MacroContext mc(owner_, it);
2779 macroTemplate.updateToContext(mc);
2782 bool valid = macroTemplate.validMacro();
2783 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2784 // then the BufferView's cursor will be invalid in
2785 // some cases which leads to crashes.
2790 // FIXME (Abdel), I don't understandt why we pass 'it' here
2791 // instead of 'macroTemplate' defined above... is this correct?
2792 macros[macroTemplate.name()][it] =
2793 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
2803 void Buffer::updateMacros() const
2808 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2810 // start with empty table
2812 d->children_positions.clear();
2813 d->position_to_children.clear();
2815 // Iterate over buffer, starting with first paragraph
2816 // The scope must be bigger than any lookup DocIterator
2817 // later. For the global lookup, lastpit+1 is used, hence
2818 // we use lastpit+2 here.
2819 DocIterator it = par_iterator_begin();
2820 DocIterator outerScope = it;
2821 outerScope.pit() = outerScope.lastpit() + 2;
2822 d->updateMacros(it, outerScope);
2826 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
2828 InsetIterator it = inset_iterator_begin(inset());
2829 InsetIterator const end = inset_iterator_end(inset());
2830 for (; it != end; ++it) {
2831 if (it->lyxCode() == BRANCH_CODE) {
2832 InsetBranch & br = static_cast<InsetBranch &>(*it);
2833 docstring const name = br.branch();
2834 if (!from_master && !params().branchlist().find(name))
2835 result.push_back(name);
2836 else if (from_master && !masterBuffer()->params().branchlist().find(name))
2837 result.push_back(name);
2840 if (it->lyxCode() == INCLUDE_CODE) {
2841 // get buffer of external file
2842 InsetInclude const & ins =
2843 static_cast<InsetInclude const &>(*it);
2844 Buffer * child = ins.getChildBuffer();
2847 child->getUsedBranches(result, true);
2850 // remove duplicates
2855 void Buffer::updateMacroInstances() const
2857 LYXERR(Debug::MACROS, "updateMacroInstances for "
2858 << d->filename.onlyFileName());
2859 DocIterator it = doc_iterator_begin(this);
2861 DocIterator const end = doc_iterator_end(this);
2862 for (; it != end; it.forwardInset()) {
2863 // look for MathData cells in InsetMathNest insets
2864 InsetMath * minset = it.nextInset()->asInsetMath();
2868 // update macro in all cells of the InsetMathNest
2869 DocIterator::idx_type n = minset->nargs();
2870 MacroContext mc = MacroContext(this, it);
2871 for (DocIterator::idx_type i = 0; i < n; ++i) {
2872 MathData & data = minset->cell(i);
2873 data.updateMacros(0, mc);
2879 void Buffer::listMacroNames(MacroNameSet & macros) const
2884 d->macro_lock = true;
2886 // loop over macro names
2887 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2888 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2889 for (; nameIt != nameEnd; ++nameIt)
2890 macros.insert(nameIt->first);
2892 // loop over children
2893 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2894 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2895 for (; it != end; ++it)
2896 it->first->listMacroNames(macros);
2899 Buffer const * const pbuf = d->parent();
2901 pbuf->listMacroNames(macros);
2903 d->macro_lock = false;
2907 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2909 Buffer const * const pbuf = d->parent();
2914 pbuf->listMacroNames(names);
2917 MacroNameSet::iterator it = names.begin();
2918 MacroNameSet::iterator end = names.end();
2919 for (; it != end; ++it) {
2921 MacroData const * data =
2922 pbuf->getMacro(*it, *this, false);
2924 macros.insert(data);
2926 // we cannot access the original MathMacroTemplate anymore
2927 // here to calls validate method. So we do its work here manually.
2928 // FIXME: somehow make the template accessible here.
2929 if (data->optionals() > 0)
2930 features.require("xargs");
2936 Buffer::References & Buffer::references(docstring const & label)
2939 return const_cast<Buffer *>(masterBuffer())->references(label);
2941 RefCache::iterator it = d->ref_cache_.find(label);
2942 if (it != d->ref_cache_.end())
2943 return it->second.second;
2945 static InsetLabel const * dummy_il = 0;
2946 static References const dummy_refs;
2947 it = d->ref_cache_.insert(
2948 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2949 return it->second.second;
2953 Buffer::References const & Buffer::references(docstring const & label) const
2955 return const_cast<Buffer *>(this)->references(label);
2959 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2961 masterBuffer()->d->ref_cache_[label].first = il;
2965 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2967 return masterBuffer()->d->ref_cache_[label].first;
2971 void Buffer::clearReferenceCache() const
2974 d->ref_cache_.clear();
2978 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2981 //FIXME: This does not work for child documents yet.
2982 LASSERT(code == CITE_CODE, /**/);
2983 // Check if the label 'from' appears more than once
2984 vector<docstring> labels;
2986 checkBibInfoCache();
2987 BiblioInfo const & keys = masterBibInfo();
2988 BiblioInfo::const_iterator bit = keys.begin();
2989 BiblioInfo::const_iterator bend = keys.end();
2991 for (; bit != bend; ++bit)
2993 labels.push_back(bit->first);
2996 if (count(labels.begin(), labels.end(), from) > 1)
2999 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3000 if (it->lyxCode() == code) {
3001 InsetCommand * inset = it->asInsetCommand();
3004 docstring const oldValue = inset->getParam(paramName);
3005 if (oldValue == from)
3006 inset->setParam(paramName, to);
3012 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
3013 pit_type par_end, bool full_source) const
3015 OutputParams runparams(¶ms().encoding());
3016 runparams.nice = true;
3017 runparams.flavor = params().useXetex ?
3018 OutputParams::XETEX : OutputParams::LATEX;
3019 runparams.linelen = lyxrc.plaintext_linelen;
3020 // No side effect of file copying and image conversion
3021 runparams.dryrun = true;
3024 os << "% " << _("Preview source code") << "\n\n";
3026 d->texrow.newline();
3027 d->texrow.newline();
3029 writeDocBookSource(os, absFileName(), runparams, false);
3031 // latex or literate
3032 writeLaTeXSource(os, string(), runparams, true, true);
3034 runparams.par_begin = par_begin;
3035 runparams.par_end = par_end;
3036 if (par_begin + 1 == par_end) {
3038 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3042 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3043 convert<docstring>(par_begin),
3044 convert<docstring>(par_end - 1))
3051 // output paragraphs
3053 docbookParagraphs(text(), *this, os, runparams);
3055 // latex or literate
3056 latexParagraphs(*this, text(), os, texrow, runparams);
3061 ErrorList & Buffer::errorList(string const & type) const
3063 static ErrorList emptyErrorList;
3064 map<string, ErrorList>::iterator it = d->errorLists.find(type);
3065 if (it == d->errorLists.end())
3066 return emptyErrorList;
3072 void Buffer::updateTocItem(std::string const & type,
3073 DocIterator const & dit) const
3076 d->gui_->updateTocItem(type, dit);
3080 void Buffer::structureChanged() const
3083 d->gui_->structureChanged();
3087 void Buffer::errors(string const & err, bool from_master) const
3090 d->gui_->errors(err, from_master);
3094 void Buffer::message(docstring const & msg) const
3097 d->gui_->message(msg);
3101 void Buffer::setBusy(bool on) const
3104 d->gui_->setBusy(on);
3108 void Buffer::updateTitles() const
3111 d->wa_->updateTitles();
3115 void Buffer::resetAutosaveTimers() const
3118 d->gui_->resetAutosaveTimers();
3122 bool Buffer::hasGuiDelegate() const
3128 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3137 class AutoSaveBuffer : public ForkedProcess {
3140 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3141 : buffer_(buffer), fname_(fname) {}
3143 virtual shared_ptr<ForkedProcess> clone() const
3145 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3150 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3151 from_utf8(fname_.absFileName())));
3152 return run(DontWait);
3156 virtual int generateChild();
3158 Buffer const & buffer_;
3163 int AutoSaveBuffer::generateChild()
3165 #if defined(__APPLE__)
3166 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3167 * We should use something else like threads.
3169 * Since I do not know how to determine at run time what is the OS X
3170 * version, I just disable forking altogether for now (JMarc)
3172 pid_t const pid = -1;
3174 // tmp_ret will be located (usually) in /tmp
3175 // will that be a problem?
3176 // Note that this calls ForkedCalls::fork(), so it's
3177 // ok cross-platform.
3178 pid_t const pid = fork();
3179 // If you want to debug the autosave
3180 // you should set pid to -1, and comment out the fork.
3181 if (pid != 0 && pid != -1)
3185 // pid = -1 signifies that lyx was unable
3186 // to fork. But we will do the save
3188 bool failed = false;
3189 FileName const tmp_ret = FileName::tempName("lyxauto");
3190 if (!tmp_ret.empty()) {
3191 buffer_.writeFile(tmp_ret);
3192 // assume successful write of tmp_ret
3193 if (!tmp_ret.moveTo(fname_))
3199 // failed to write/rename tmp_ret so try writing direct
3200 if (!buffer_.writeFile(fname_)) {
3201 // It is dangerous to do this in the child,
3202 // but safe in the parent, so...
3203 if (pid == -1) // emit message signal.
3204 buffer_.message(_("Autosave failed!"));
3208 if (pid == 0) // we are the child so...
3217 FileName Buffer::getEmergencyFileName() const
3219 return getEmergencyFileNameFor(d->filename);
3223 FileName Buffer::getEmergencyFileNameFor(FileName const & fn) const
3225 return FileName(fn.absFileName() + ".emergency");
3229 FileName Buffer::getAutosaveFileName() const
3231 // if the document is unnamed try to save in the backup dir, else
3232 // in the default document path, and as a last try in the filePath,
3233 // which will most often be the temporary directory
3236 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3237 : lyxrc.backupdir_path;
3238 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3241 string const fname = d->filename.onlyFileName();
3242 return getAutosaveFileNameFor(makeAbsPath(fname, fpath));
3246 FileName Buffer::getAutosaveFileNameFor(FileName const & fn) const
3248 string const fname = "#" + onlyFileName(fn.absFileName()) + "#";
3249 return FileName(onlyPath(fn.absFileName()) + fname);
3253 void Buffer::removeAutosaveFile() const
3255 FileName const f = getAutosaveFileName();
3261 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3263 FileName const newauto = getAutosaveFileName();
3265 if (newauto != oldauto && oldauto.exists())
3266 if (!oldauto.moveTo(newauto))
3267 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3271 // Perfect target for a thread...
3272 void Buffer::autoSave() const
3274 if (d->bak_clean || isReadonly()) {
3275 // We don't save now, but we'll try again later
3276 resetAutosaveTimers();
3280 // emit message signal.
3281 message(_("Autosaving current document..."));
3282 AutoSaveBuffer autosave(*this, getAutosaveFileName());
3285 d->bak_clean = true;
3287 resetAutosaveTimers();
3291 string Buffer::bufferFormat() const
3293 string format = params().documentClass().outputFormat();
3294 if (format == "latex") {
3295 if (params().useXetex)
3297 if (params().encoding().package() == Encoding::japanese)
3304 string Buffer::getDefaultOutputFormat() const
3306 if (!params().defaultOutputFormat.empty()
3307 && params().defaultOutputFormat != "default")
3308 return params().defaultOutputFormat;
3309 typedef vector<Format const *> Formats;
3310 Formats formats = exportableFormats(true);
3313 || params().useXetex
3314 || params().encoding().package() == Encoding::japanese) {
3315 if (formats.empty())
3317 // return the first we find
3318 return formats.front()->name();
3320 return lyxrc.default_view_format;
3325 // helper class, to guarantee this gets reset properly
3326 class MarkAsExporting {
3328 MarkAsExporting(Buffer const * buf) : buf_(buf)
3330 LASSERT(buf_, /* */);
3331 buf_->setExportStatus(true);
3335 buf_->setExportStatus(false);
3338 Buffer const * const buf_;
3343 void Buffer::setExportStatus(bool e) const
3345 d->doing_export = e;
3349 bool Buffer::isExporting() const
3351 return d->doing_export;
3355 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3356 bool includeall, string & result_file) const
3358 MarkAsExporting exporting(this);
3359 string backend_format;
3360 OutputParams runparams(¶ms().encoding());
3361 runparams.flavor = OutputParams::LATEX;
3362 runparams.linelen = lyxrc.plaintext_linelen;
3363 runparams.includeall = includeall;
3364 vector<string> backs = backends();
3365 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3366 // Get shortest path to format
3367 Graph::EdgePath path;
3368 for (vector<string>::const_iterator it = backs.begin();
3369 it != backs.end(); ++it) {
3370 Graph::EdgePath p = theConverters().getPath(*it, format);
3371 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3372 backend_format = *it;
3377 if (!put_in_tempdir) {
3378 // Only show this alert if this is an export to a non-temporary
3379 // file (not for previewing).
3380 Alert::error(_("Couldn't export file"), bformat(
3381 _("No information for exporting the format %1$s."),
3382 formats.prettyName(format)));
3386 runparams.flavor = theConverters().getFlavor(path);
3389 backend_format = format;
3390 // FIXME: Don't hardcode format names here, but use a flag
3391 if (backend_format == "pdflatex")
3392 runparams.flavor = OutputParams::PDFLATEX;
3395 string filename = latexName(false);
3396 filename = addName(temppath(), filename);
3397 filename = changeExtension(filename,
3398 formats.extension(backend_format));
3401 updateMacroInstances();
3403 // Plain text backend
3404 if (backend_format == "text") {
3405 runparams.flavor = OutputParams::TEXT;
3406 writePlaintextFile(*this, FileName(filename), runparams);
3409 else if (backend_format == "xhtml") {
3410 runparams.flavor = OutputParams::HTML;
3411 switch (params().html_math_output) {
3412 case BufferParams::MathML:
3413 runparams.math_flavor = OutputParams::MathAsMathML;
3415 case BufferParams::HTML:
3416 runparams.math_flavor = OutputParams::MathAsHTML;
3418 case BufferParams::Images:
3419 runparams.math_flavor = OutputParams::MathAsImages;
3421 case BufferParams::LaTeX:
3422 runparams.math_flavor = OutputParams::MathAsLaTeX;
3426 makeLyXHTMLFile(FileName(filename), runparams);
3427 } else if (backend_format == "lyx")
3428 writeFile(FileName(filename));
3430 else if (isDocBook()) {
3431 runparams.nice = !put_in_tempdir;
3432 makeDocBookFile(FileName(filename), runparams);
3435 else if (backend_format == format) {
3436 runparams.nice = true;
3437 if (!makeLaTeXFile(FileName(filename), string(), runparams))
3439 } else if (!lyxrc.tex_allows_spaces
3440 && contains(filePath(), ' ')) {
3441 Alert::error(_("File name error"),
3442 _("The directory path to the document cannot contain spaces."));
3445 runparams.nice = false;
3446 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
3450 string const error_type = (format == "program")
3451 ? "Build" : bufferFormat();
3452 ErrorList & error_list = d->errorLists[error_type];
3453 string const ext = formats.extension(format);
3454 FileName const tmp_result_file(changeExtension(filename, ext));
3455 bool const success = theConverters().convert(this, FileName(filename),
3456 tmp_result_file, FileName(absFileName()), backend_format, format,
3459 // Emit the signal to show the error list or copy it back to the
3460 // cloned Buffer so that it cab be emitted afterwards.
3461 if (format != backend_format) {
3462 if (d->cloned_buffer_) {
3463 d->cloned_buffer_->d->errorLists[error_type] =
3464 d->errorLists[error_type];
3467 // also to the children, in case of master-buffer-view
3468 ListOfBuffers clist = getDescendents();
3469 ListOfBuffers::const_iterator cit = clist.begin();
3470 ListOfBuffers::const_iterator const cen = clist.end();
3471 for (; cit != cen; ++cit) {
3472 if (d->cloned_buffer_) {
3473 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
3474 (*cit)->d->errorLists[error_type];
3476 (*cit)->errors(error_type, true);
3480 if (d->cloned_buffer_) {
3481 // Enable reverse dvi or pdf to work by copying back the texrow
3482 // object to the cloned buffer.
3483 // FIXME: There is a possibility of concurrent access to texrow
3484 // here from the main GUI thread that should be securized.
3485 d->cloned_buffer_->d->texrow = d->texrow;
3486 string const error_type = bufferFormat();
3487 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
3493 if (put_in_tempdir) {
3494 result_file = tmp_result_file.absFileName();
3498 result_file = changeExtension(d->exportFileName().absFileName(), ext);
3499 // We need to copy referenced files (e. g. included graphics
3500 // if format == "dvi") to the result dir.
3501 vector<ExportedFile> const files =
3502 runparams.exportdata->externalFiles(format);
3503 string const dest = onlyPath(result_file);
3504 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
3505 : force_overwrite == ALL_FILES;
3506 CopyStatus status = use_force ? FORCE : SUCCESS;
3508 vector<ExportedFile>::const_iterator it = files.begin();
3509 vector<ExportedFile>::const_iterator const en = files.end();
3510 for (; it != en && status != CANCEL; ++it) {
3511 string const fmt = formats.getFormatFromFile(it->sourceName);
3512 status = copyFile(fmt, it->sourceName,
3513 makeAbsPath(it->exportName, dest),
3514 it->exportName, status == FORCE);
3517 if (status == CANCEL) {
3518 message(_("Document export cancelled."));
3519 } else if (tmp_result_file.exists()) {
3520 // Finally copy the main file
3521 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
3522 : force_overwrite != NO_FILES;
3523 if (status == SUCCESS && use_force)
3525 status = copyFile(format, tmp_result_file,
3526 FileName(result_file), result_file,
3528 message(bformat(_("Document exported as %1$s "
3530 formats.prettyName(format),
3531 makeDisplayPath(result_file)));
3533 // This must be a dummy converter like fax (bug 1888)
3534 message(bformat(_("Document exported as %1$s"),
3535 formats.prettyName(format)));
3542 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3543 bool includeall) const
3546 // (1) export with all included children (omit \includeonly)
3547 if (includeall && !doExport(format, put_in_tempdir, true, result_file))
3549 // (2) export with included children only
3550 return doExport(format, put_in_tempdir, false, result_file);
3554 bool Buffer::preview(string const & format, bool includeall) const
3556 MarkAsExporting exporting(this);
3558 // (1) export with all included children (omit \includeonly)
3559 if (includeall && !doExport(format, true, true))
3561 // (2) export with included children only
3562 if (!doExport(format, true, false, result_file))
3564 return formats.view(*this, FileName(result_file), format);
3568 bool Buffer::isExportable(string const & format) const
3570 vector<string> backs = backends();
3571 for (vector<string>::const_iterator it = backs.begin();
3572 it != backs.end(); ++it)
3573 if (theConverters().isReachable(*it, format))
3579 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
3581 vector<string> const backs = backends();
3582 vector<Format const *> result =
3583 theConverters().getReachable(backs[0], only_viewable, true);
3584 for (vector<string>::const_iterator it = backs.begin() + 1;
3585 it != backs.end(); ++it) {
3586 vector<Format const *> r =
3587 theConverters().getReachable(*it, only_viewable, false);
3588 result.insert(result.end(), r.begin(), r.end());
3594 vector<string> Buffer::backends() const
3597 v.push_back(bufferFormat());
3598 // FIXME: Don't hardcode format names here, but use a flag
3599 if (v.back() == "latex")
3600 v.push_back("pdflatex");
3601 v.push_back("xhtml");
3602 v.push_back("text");
3608 Buffer::ReadStatus Buffer::extractFromVC(FileName const & fn)
3610 bool const found = LyXVC::file_not_found_hook(fn);
3612 return ReadFileNotFound;
3613 if (!fn.isReadableFile())
3619 Buffer::ReadStatus Buffer::loadEmergency(FileName const & fn)
3621 FileName const emergencyFile = getEmergencyFileNameFor(fn);
3622 if (!emergencyFile.exists()
3623 || emergencyFile.lastModified() <= fn.lastModified())
3624 return ReadFileNotFound;
3626 docstring const file = makeDisplayPath(fn.absFileName(), 20);
3627 docstring const text = bformat(_("An emergency save of the document "
3628 "%1$s exists.\n\nRecover emergency save?"), file);
3630 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
3631 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
3637 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
3638 bool const success = (ret_llf == ReadSuccess);
3641 str = _("Document was successfully recovered.");
3643 str = _("Document was NOT successfully recovered.");
3644 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3645 makeDisplayPath(emergencyFile.absFileName()));
3647 int const del_emerg =
3648 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3649 _("&Remove"), _("&Keep"));
3650 if (del_emerg == 0) {
3651 emergencyFile.removeFile();
3653 Alert::warning(_("Emergency file deleted"),
3654 _("Do not forget to save your file now!"), true);
3656 return success ? ReadSuccess : ReadEmergencyFailure;
3659 int const del_emerg =
3660 Alert::prompt(_("Delete emergency file?"),
3661 _("Remove emergency file now?"), 1, 1,
3662 _("&Remove"), _("&Keep"));
3664 emergencyFile.removeFile();
3665 return ReadOriginal;
3675 Buffer::ReadStatus Buffer::loadAutosave(FileName const & fn)
3677 // Now check if autosave file is newer.
3678 FileName const autosaveFile = getAutosaveFileNameFor(fn);
3679 if (!autosaveFile.exists()
3680 || autosaveFile.lastModified() <= fn.lastModified())
3681 return ReadFileNotFound;
3683 docstring const file = makeDisplayPath(fn.absFileName(), 20);
3684 docstring const text = bformat(_("The backup of the document %1$s "
3685 "is newer.\n\nLoad the backup instead?"), file);
3686 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
3687 _("&Load backup"), _("Load &original"), _("&Cancel"));
3692 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
3693 // the file is not saved if we load the autosave file.
3694 if (ret_llf == ReadSuccess) {
3698 return ReadAutosaveFailure;
3701 // Here we delete the autosave
3702 autosaveFile.removeFile();
3703 return ReadOriginal;
3711 Buffer::ReadStatus Buffer::loadLyXFile(FileName const & fn)
3713 if (!fn.isReadableFile()) {
3714 ReadStatus const ret_rvc = extractFromVC(fn);
3715 if (ret_rvc != ReadSuccess)
3719 ReadStatus const ret_re = loadEmergency(fn);
3720 if (ret_re == ReadSuccess || ret_re == ReadCancel)
3723 ReadStatus const ret_ra = loadAutosave(fn);
3724 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
3727 return loadThisLyXFile(fn);
3731 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
3733 return readFile(fn);
3737 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3739 TeXErrors::Errors::const_iterator cit = terr.begin();
3740 TeXErrors::Errors::const_iterator end = terr.end();
3742 for (; cit != end; ++cit) {
3745 int errorRow = cit->error_in_line;
3746 bool found = d->texrow.getIdFromRow(errorRow, id_start,
3752 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
3753 } while (found && id_start == id_end && pos_start == pos_end);
3755 errorList.push_back(ErrorItem(cit->error_desc,
3756 cit->error_text, id_start, pos_start, pos_end));
3761 void Buffer::setBuffersForInsets() const
3763 inset().setBuffer(const_cast<Buffer &>(*this));
3767 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
3769 // Use the master text class also for child documents
3770 Buffer const * const master = masterBuffer();
3771 DocumentClass const & textclass = master->params().documentClass();
3773 // do this only if we are the top-level Buffer
3775 checkBibInfoCache();
3777 // keep the buffers to be children in this set. If the call from the
3778 // master comes back we can see which of them were actually seen (i.e.
3779 // via an InsetInclude). The remaining ones in the set need still be updated.
3780 static std::set<Buffer const *> bufToUpdate;
3781 if (scope == UpdateMaster) {
3782 // If this is a child document start with the master
3783 if (master != this) {
3784 bufToUpdate.insert(this);
3785 master->updateBuffer(UpdateMaster, utype);
3786 // Do this here in case the master has no gui associated with it. Then,
3787 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3788 if (!master->d->gui_)
3791 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3792 if (bufToUpdate.find(this) == bufToUpdate.end())
3796 // start over the counters in the master
3797 textclass.counters().reset();
3800 // update will be done below for this buffer
3801 bufToUpdate.erase(this);
3803 // update all caches
3804 clearReferenceCache();
3807 Buffer & cbuf = const_cast<Buffer &>(*this);
3809 LASSERT(!text().paragraphs().empty(), /**/);
3812 ParIterator parit = cbuf.par_iterator_begin();
3813 updateBuffer(parit, utype);
3816 // TocBackend update will be done later.
3819 cbuf.tocBackend().update();
3820 if (scope == UpdateMaster)
3821 cbuf.structureChanged();
3825 static depth_type getDepth(DocIterator const & it)
3827 depth_type depth = 0;
3828 for (size_t i = 0 ; i < it.depth() ; ++i)
3829 if (!it[i].inset().inMathed())
3830 depth += it[i].paragraph().getDepth() + 1;
3831 // remove 1 since the outer inset does not count
3835 static depth_type getItemDepth(ParIterator const & it)
3837 Paragraph const & par = *it;
3838 LabelType const labeltype = par.layout().labeltype;
3840 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3843 // this will hold the lowest depth encountered up to now.
3844 depth_type min_depth = getDepth(it);
3845 ParIterator prev_it = it;
3848 --prev_it.top().pit();
3850 // start of nested inset: go to outer par
3852 if (prev_it.empty()) {
3853 // start of document: nothing to do
3858 // We search for the first paragraph with same label
3859 // that is not more deeply nested.
3860 Paragraph & prev_par = *prev_it;
3861 depth_type const prev_depth = getDepth(prev_it);
3862 if (labeltype == prev_par.layout().labeltype) {
3863 if (prev_depth < min_depth)
3864 return prev_par.itemdepth + 1;
3865 if (prev_depth == min_depth)
3866 return prev_par.itemdepth;
3868 min_depth = min(min_depth, prev_depth);
3869 // small optimization: if we are at depth 0, we won't
3870 // find anything else
3871 if (prev_depth == 0)
3877 static bool needEnumCounterReset(ParIterator const & it)
3879 Paragraph const & par = *it;
3880 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3881 depth_type const cur_depth = par.getDepth();
3882 ParIterator prev_it = it;
3883 while (prev_it.pit()) {
3884 --prev_it.top().pit();
3885 Paragraph const & prev_par = *prev_it;
3886 if (prev_par.getDepth() <= cur_depth)
3887 return prev_par.layout().labeltype != LABEL_ENUMERATE;
3889 // start of nested inset: reset
3894 // set the label of a paragraph. This includes the counters.
3895 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
3897 BufferParams const & bp = owner_->masterBuffer()->params();
3898 DocumentClass const & textclass = bp.documentClass();
3899 Paragraph & par = it.paragraph();
3900 Layout const & layout = par.layout();
3901 Counters & counters = textclass.counters();
3903 if (par.params().startOfAppendix()) {
3904 // FIXME: only the counter corresponding to toplevel
3905 // sectioning should be reset
3907 counters.appendix(true);
3909 par.params().appendix(counters.appendix());
3911 // Compute the item depth of the paragraph
3912 par.itemdepth = getItemDepth(it);
3914 if (layout.margintype == MARGIN_MANUAL
3915 || layout.latextype == LATEX_BIB_ENVIRONMENT) {
3916 if (par.params().labelWidthString().empty())
3917 par.params().labelWidthString(par.expandLabel(layout, bp));
3919 par.params().labelWidthString(docstring());
3922 switch(layout.labeltype) {
3924 if (layout.toclevel <= bp.secnumdepth
3925 && (layout.latextype != LATEX_ENVIRONMENT
3926 || it.text()->isFirstInSequence(it.pit()))) {
3927 counters.step(layout.counter, utype);
3928 par.params().labelString(
3929 par.expandLabel(layout, bp));
3931 par.params().labelString(docstring());
3934 case LABEL_ITEMIZE: {
3935 // At some point of time we should do something more
3936 // clever here, like:
3937 // par.params().labelString(
3938 // bp.user_defined_bullet(par.itemdepth).getText());
3939 // for now, use a simple hardcoded label
3940 docstring itemlabel;
3941 switch (par.itemdepth) {
3943 itemlabel = char_type(0x2022);
3946 itemlabel = char_type(0x2013);
3949 itemlabel = char_type(0x2217);
3952 itemlabel = char_type(0x2219); // or 0x00b7
3955 par.params().labelString(itemlabel);
3959 case LABEL_ENUMERATE: {
3960 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
3962 switch (par.itemdepth) {
3971 enumcounter += "iv";
3974 // not a valid enumdepth...
3978 // Maybe we have to reset the enumeration counter.
3979 if (needEnumCounterReset(it))
3980 counters.reset(enumcounter);
3981 counters.step(enumcounter, utype);
3983 string const & lang = par.getParLanguage(bp)->code();
3984 par.params().labelString(counters.theCounter(enumcounter, lang));
3989 case LABEL_SENSITIVE: {
3990 string const & type = counters.current_float();
3991 docstring full_label;
3993 full_label = owner_->B_("Senseless!!! ");
3995 docstring name = owner_->B_(textclass.floats().getType(type).name());
3996 if (counters.hasCounter(from_utf8(type))) {
3997 string const & lang = par.getParLanguage(bp)->code();
3998 counters.step(from_utf8(type), utype);
3999 full_label = bformat(from_ascii("%1$s %2$s:"),
4001 counters.theCounter(from_utf8(type), lang));
4003 full_label = bformat(from_ascii("%1$s #:"), name);
4005 par.params().labelString(full_label);
4009 case LABEL_NO_LABEL:
4010 par.params().labelString(docstring());
4014 case LABEL_TOP_ENVIRONMENT:
4015 case LABEL_CENTERED_TOP_ENVIRONMENT:
4018 par.params().labelString(par.expandLabel(layout, bp));
4024 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4026 LASSERT(parit.pit() == 0, /**/);
4028 // Set the position of the text in the buffer to be able
4029 // to resolve macros in it.
4030 parit.text()->setMacrocontextPosition(parit);
4032 depth_type maxdepth = 0;
4033 pit_type const lastpit = parit.lastpit();
4034 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4035 // reduce depth if necessary
4036 parit->params().depth(min(parit->params().depth(), maxdepth));
4037 maxdepth = parit->getMaxDepthAfter();
4039 if (utype == OutputUpdate) {
4040 // track the active counters
4041 // we have to do this for the master buffer, since the local
4042 // buffer isn't tracking anything.
4043 masterBuffer()->params().documentClass().counters().
4044 setActiveLayout(parit->layout());
4047 // set the counter for this paragraph
4048 d->setLabel(parit, utype);
4051 InsetList::const_iterator iit = parit->insetList().begin();
4052 InsetList::const_iterator end = parit->insetList().end();
4053 for (; iit != end; ++iit) {
4054 parit.pos() = iit->pos;
4055 iit->inset->updateBuffer(parit, utype);
4061 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4062 WordLangTuple & word_lang, docstring_list & suggestions) const
4066 suggestions.clear();
4067 word_lang = WordLangTuple();
4068 // OK, we start from here.
4069 DocIterator const end = doc_iterator_end(this);
4070 for (; from != end; from.forwardPos()) {
4071 // We are only interested in text so remove the math CursorSlice.
4072 while (from.inMathed()) {
4076 // If from is at the end of the document (which is possible
4077 // when leaving the mathed) LyX will crash later.
4081 from.paragraph().spellCheck();
4082 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4083 if (SpellChecker::misspelled(res)) {
4088 // Do not increase progress when from == to, otherwise the word
4089 // count will be wrong.
4099 bool Buffer::reload()
4103 removeAutosaveFile();
4104 // e.g., read-only status could have changed due to version control
4105 d->filename.refresh();
4106 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4108 bool const success = (loadLyXFile(d->filename) == ReadSuccess);
4115 message(bformat(_("Document %1$s reloaded."), disp_fn));
4117 message(bformat(_("Could not reload document %1$s."), disp_fn));
4120 thePreviews().removeLoader(*this);
4121 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
4122 thePreviews().generateBufferPreviews(*this);
4128 // FIXME We could do better here, but it is complicated. What would be
4129 // nice is to offer either (a) to save the child buffer to an appropriate
4130 // location, so that it would "move with the master", or else (b) to update
4131 // the InsetInclude so that it pointed to the same file. But (a) is a bit
4132 // complicated, because the code for this lives in GuiView.
4133 void Buffer::checkChildBuffers()
4135 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4136 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4137 for (; it != en; ++it) {
4138 DocIterator dit = it->second;
4139 Buffer * cbuf = const_cast<Buffer *>(it->first);
4140 if (!cbuf || !theBufferList().isLoaded(cbuf))
4142 Inset * inset = dit.nextInset();
4143 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4144 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4145 docstring const & incfile = inset_inc->getParam("filename");
4146 string oldloc = cbuf->absFileName();
4147 string newloc = makeAbsPath(to_utf8(incfile),
4148 onlyPath(absFileName())).absFileName();
4149 if (oldloc == newloc)
4151 // the location of the child file is incorrect.
4152 Alert::warning(_("Included File Invalid"),
4153 bformat(_("Saving this document to a new location has made the file:\n"
4155 "inaccessible. You will need to update the included filename."),
4156 from_utf8(oldloc)));
4158 inset_inc->setChildBuffer(0);
4160 // invalidate cache of children
4161 d->children_positions.clear();
4162 d->position_to_children.clear();