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/InsetText.h"
75 #include "mathed/InsetMathHull.h"
76 #include "mathed/MacroTable.h"
77 #include "mathed/MathMacroTemplate.h"
78 #include "mathed/MathSupport.h"
80 #include "frontends/alert.h"
81 #include "frontends/Delegates.h"
82 #include "frontends/WorkAreaManager.h"
84 #include "graphics/Previews.h"
86 #include "support/lassert.h"
87 #include "support/convert.h"
88 #include "support/debug.h"
89 #include "support/docstring_list.h"
90 #include "support/ExceptionMessage.h"
91 #include "support/FileName.h"
92 #include "support/FileNameList.h"
93 #include "support/filetools.h"
94 #include "support/ForkedCalls.h"
95 #include "support/gettext.h"
96 #include "support/gzstream.h"
97 #include "support/lstrings.h"
98 #include "support/lyxalgo.h"
99 #include "support/os.h"
100 #include "support/Package.h"
101 #include "support/Path.h"
102 #include "support/Systemcall.h"
103 #include "support/textutils.h"
104 #include "support/types.h"
106 #include "support/bind.h"
107 #include "support/shared_ptr.h"
119 using namespace lyx::support;
123 namespace Alert = frontend::Alert;
124 namespace os = support::os;
128 // Do not remove the comment below, so we get merge conflict in
129 // independent branches. Instead add your own.
130 int const LYX_FORMAT = 398; // uwestoehr: support for \mathscr
132 typedef map<string, bool> DepClean;
133 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
135 void showPrintError(string const & name)
137 docstring str = bformat(_("Could not print the document %1$s.\n"
138 "Check that your printer is set up correctly."),
139 makeDisplayPath(name, 50));
140 Alert::error(_("Print document failed"), str);
145 class BufferSet : public std::set<Buffer const *> {};
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 void collectRelatives(BufferSet & bufs) const;
173 /** If we have branches that use the file suffix
174 feature, return the file name with suffix appended.
176 support::FileName exportFileName() const;
183 mutable TexRow texrow;
185 /// need to regenerate .tex?
189 mutable bool lyx_clean;
191 /// is autosave needed?
192 mutable bool bak_clean;
194 /// is this a unnamed file (New...)?
200 /// name of the file the buffer is associated with.
203 /** Set to true only when the file is fully loaded.
204 * Used to prevent the premature generation of previews
205 * and by the citation inset.
207 bool file_fully_loaded;
210 mutable TocBackend toc_backend;
213 typedef pair<DocIterator, MacroData> ScopeMacro;
214 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
215 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
216 /// map from the macro name to the position map,
217 /// which maps the macro definition position to the scope and the MacroData.
218 NamePositionScopeMacroMap macros;
219 /// This seem to change the way Buffer::getMacro() works
220 mutable bool macro_lock;
222 /// positions of child buffers in the buffer
223 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
224 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
225 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
226 /// position of children buffers in this buffer
227 BufferPositionMap children_positions;
228 /// map from children inclusion positions to their scope and their buffer
229 PositionScopeBufferMap position_to_children;
231 /// Container for all sort of Buffer dependant errors.
232 map<string, ErrorList> errorLists;
234 /// timestamp and checksum used to test if the file has been externally
235 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
237 unsigned long checksum_;
240 frontend::WorkAreaManager * wa_;
242 frontend::GuiBufferDelegate * gui_;
247 /// A cache for the bibfiles (including bibfiles of loaded child
248 /// documents), needed for appropriate update of natbib labels.
249 mutable support::FileNameList bibfiles_cache_;
251 // FIXME The caching mechanism could be improved. At present, we have a
252 // cache for each Buffer, that caches all the bibliography info for that
253 // Buffer. A more efficient solution would be to have a global cache per
254 // file, and then to construct the Buffer's bibinfo from that.
255 /// A cache for bibliography info
256 mutable BiblioInfo bibinfo_;
257 /// whether the bibinfo cache is valid
258 bool bibinfo_cache_valid_;
259 /// whether the bibfile cache is valid
260 bool bibfile_cache_valid_;
261 /// Cache of timestamps of .bib files
262 map<FileName, time_t> bibfile_status_;
264 mutable RefCache ref_cache_;
266 /// our Text that should be wrapped in an InsetText
269 /// This is here to force the test to be done whenever parent_buffer
271 Buffer const * parent() const {
272 // if parent_buffer is not loaded, then it has been unloaded,
273 // which means that parent_buffer is an invalid pointer. So we
274 // set it to null in that case.
275 // however, the BufferList doesn't know about cloned buffers, so
276 // they will always be regarded as unloaded. in that case, we hope
278 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
280 return parent_buffer;
283 void setParent(Buffer const * pb) {
285 && parent_buffer && pb && parent_buffer != pb)
286 LYXERR0("Warning: a buffer should not have two parents!");
290 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
291 /// This one is useful for preview detached in a thread.
292 Buffer const * cloned_buffer_;
293 /// are we in the process of exporting this buffer?
294 mutable bool doing_export;
297 /// So we can force access via the accessors.
298 mutable Buffer const * parent_buffer;
303 /// Creates the per buffer temporary directory
304 static FileName createBufferTmpDir()
307 // We are in our own directory. Why bother to mangle name?
308 // In fact I wrote this code to circumvent a problematic behaviour
309 // (bug?) of EMX mkstemp().
310 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
311 convert<string>(count++));
313 if (!tmpfl.createDirectory(0777)) {
314 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
315 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
316 from_utf8(tmpfl.absFileName())));
322 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
323 Buffer const * cloned_buffer)
324 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
325 read_only(readonly_), filename(file), file_fully_loaded(false),
326 toc_backend(owner), macro_lock(false), timestamp_(0),
327 checksum_(0), wa_(0), gui_(0), undo_(*owner), bibinfo_cache_valid_(false),
328 bibfile_cache_valid_(false), cloned_buffer_(cloned_buffer),
329 doing_export(false), parent_buffer(0)
331 if (!cloned_buffer_) {
332 temppath = createBufferTmpDir();
333 lyxvc.setBuffer(owner_);
335 wa_ = new frontend::WorkAreaManager;
338 temppath = cloned_buffer_->d->temppath;
339 file_fully_loaded = true;
340 params = cloned_buffer_->d->params;
341 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
342 bibinfo_ = cloned_buffer_->d->bibinfo_;
343 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
344 bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
345 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
349 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
350 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
352 LYXERR(Debug::INFO, "Buffer::Buffer()");
354 d->inset = new InsetText(*cloned_buffer->d->inset);
355 d->inset->setBuffer(*this);
356 // FIXME: optimize this loop somewhat, maybe by creating a new
357 // general recursive Inset::setId().
358 DocIterator it = doc_iterator_begin(this);
359 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
360 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
361 it.paragraph().setId(cloned_it.paragraph().id());
363 d->inset = new InsetText(this);
364 d->inset->setAutoBreakRows(true);
365 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
371 LYXERR(Debug::INFO, "Buffer::~Buffer()");
372 // here the buffer should take care that it is
373 // saved properly, before it goes into the void.
375 // GuiView already destroyed
379 // No need to do additional cleanups for internal buffer.
384 // loop over children
385 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
386 Impl::BufferPositionMap::iterator end = d->children_positions.end();
387 for (; it != end; ++it) {
388 Buffer * child = const_cast<Buffer *>(it->first);
389 if (d->cloned_buffer_)
391 // The child buffer might have been closed already.
392 else if (theBufferList().isLoaded(child))
393 theBufferList().releaseChild(this, child);
397 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
398 msg += emergencyWrite();
399 Alert::warning(_("Attempting to close changed document!"), msg);
402 // clear references to children in macro tables
403 d->children_positions.clear();
404 d->position_to_children.clear();
406 if (!d->cloned_buffer_ && !d->temppath.destroyDirectory()) {
407 Alert::warning(_("Could not remove temporary directory"),
408 bformat(_("Could not remove the temporary directory %1$s"),
409 from_utf8(d->temppath.absFileName())));
412 // Remove any previewed LaTeX snippets associated with this buffer.
414 thePreviews().removeLoader(*this);
420 Buffer * Buffer::clone() const
422 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
423 buffer_clone->d->macro_lock = true;
424 buffer_clone->d->children_positions.clear();
425 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
426 // math macro caches need to be rethought and simplified.
427 // I am not sure wether we should handle Buffer cloning here or in BufferList.
428 // Right now BufferList knows nothing about buffer clones.
429 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
430 Impl::BufferPositionMap::iterator end = d->children_positions.end();
431 for (; it != end; ++it) {
432 DocIterator dit = it->second.clone(buffer_clone);
433 dit.setBuffer(buffer_clone);
434 Buffer * child = const_cast<Buffer *>(it->first);
435 Buffer * child_clone = child->clone();
436 Inset * inset = dit.nextInset();
437 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
438 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
439 inset_inc->setChildBuffer(child_clone);
440 child_clone->d->setParent(buffer_clone);
441 buffer_clone->setChild(dit, child_clone);
443 buffer_clone->d->macro_lock = false;
448 bool Buffer::isClone() const
450 return d->cloned_buffer_;
454 void Buffer::changed(bool update_metrics) const
457 d->wa_->redrawAll(update_metrics);
461 frontend::WorkAreaManager & Buffer::workAreaManager() const
463 LASSERT(d->wa_, /**/);
468 Text & Buffer::text() const
470 return d->inset->text();
474 Inset & Buffer::inset() const
480 BufferParams & Buffer::params()
486 BufferParams const & Buffer::params() const
492 ParagraphList & Buffer::paragraphs()
494 return text().paragraphs();
498 ParagraphList const & Buffer::paragraphs() const
500 return text().paragraphs();
504 LyXVC & Buffer::lyxvc()
510 LyXVC const & Buffer::lyxvc() const
516 string const Buffer::temppath() const
518 return d->temppath.absFileName();
522 TexRow & Buffer::texrow()
528 TexRow const & Buffer::texrow() const
534 TocBackend & Buffer::tocBackend() const
536 return d->toc_backend;
540 Undo & Buffer::undo()
546 void Buffer::setChild(DocIterator const & dit, Buffer * child)
548 d->children_positions[child] = dit;
552 string Buffer::latexName(bool const no_path) const
554 FileName latex_name =
555 makeLatexName(d->exportFileName());
556 return no_path ? latex_name.onlyFileName()
557 : latex_name.absFileName();
561 FileName Buffer::Impl::exportFileName() const
563 docstring const branch_suffix =
564 params.branchlist().getFileNameSuffix();
565 if (branch_suffix.empty())
568 string const name = filename.onlyFileNameWithoutExt()
569 + to_utf8(branch_suffix);
570 FileName res(filename.onlyPath().absFileName() + "/" + name);
571 res.changeExtension(filename.extension());
577 string Buffer::logName(LogType * type) const
579 string const filename = latexName(false);
581 if (filename.empty()) {
587 string const path = temppath();
589 FileName const fname(addName(temppath(),
590 onlyFileName(changeExtension(filename,
593 // FIXME: how do we know this is the name of the build log?
594 FileName const bname(
595 addName(path, onlyFileName(
596 changeExtension(filename,
597 formats.extension(bufferFormat()) + ".out"))));
599 // Also consider the master buffer log file
600 FileName masterfname = fname;
602 if (masterBuffer() != this) {
603 string const mlogfile = masterBuffer()->logName(&mtype);
604 masterfname = FileName(mlogfile);
607 // If no Latex log or Build log is newer, show Build log
608 if (bname.exists() &&
609 ((!fname.exists() && !masterfname.exists())
610 || (fname.lastModified() < bname.lastModified()
611 && masterfname.lastModified() < bname.lastModified()))) {
612 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
615 return bname.absFileName();
616 // If we have a newer master file log or only a master log, show this
617 } else if (fname != masterfname
618 && (!fname.exists() && (masterfname.exists()
619 || fname.lastModified() < masterfname.lastModified()))) {
620 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
623 return masterfname.absFileName();
625 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
628 return fname.absFileName();
632 void Buffer::setReadonly(bool const flag)
634 if (d->read_only != flag) {
641 void Buffer::setFileName(string const & newfile)
643 d->filename = makeAbsPath(newfile);
644 setReadonly(d->filename.isReadOnly());
649 int Buffer::readHeader(Lexer & lex)
651 int unknown_tokens = 0;
653 int begin_header_line = -1;
655 // Initialize parameters that may be/go lacking in header:
656 params().branchlist().clear();
657 params().preamble.erase();
658 params().options.erase();
659 params().master.erase();
660 params().float_placement.erase();
661 params().paperwidth.erase();
662 params().paperheight.erase();
663 params().leftmargin.erase();
664 params().rightmargin.erase();
665 params().topmargin.erase();
666 params().bottommargin.erase();
667 params().headheight.erase();
668 params().headsep.erase();
669 params().footskip.erase();
670 params().columnsep.erase();
671 params().fontsCJK.erase();
672 params().listings_params.clear();
673 params().clearLayoutModules();
674 params().clearRemovedModules();
675 params().clearIncludedChildren();
676 params().pdfoptions().clear();
677 params().indiceslist().clear();
678 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
679 params().isbackgroundcolor = false;
680 params().fontcolor = lyx::rgbFromHexName("#000000");
681 params().isfontcolor = false;
682 params().notefontcolor = lyx::rgbFromHexName("#cccccc");
683 params().boxbgcolor = lyx::rgbFromHexName("#ff0000");
684 params().html_latex_start.clear();
685 params().html_latex_end.clear();
686 params().html_math_img_scale = 1.0;
687 params().output_sync_macro.erase();
689 for (int i = 0; i < 4; ++i) {
690 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
691 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
694 ErrorList & errorList = d->errorLists["Parse"];
703 if (token == "\\end_header")
707 if (token == "\\begin_header") {
708 begin_header_line = line;
712 LYXERR(Debug::PARSER, "Handling document header token: `"
715 string unknown = params().readToken(lex, token, d->filename.onlyPath());
716 if (!unknown.empty()) {
717 if (unknown[0] != '\\' && token == "\\textclass") {
718 Alert::warning(_("Unknown document class"),
719 bformat(_("Using the default document class, because the "
720 "class %1$s is unknown."), from_utf8(unknown)));
723 docstring const s = bformat(_("Unknown token: "
727 errorList.push_back(ErrorItem(_("Document header error"),
732 if (begin_header_line) {
733 docstring const s = _("\\begin_header is missing");
734 errorList.push_back(ErrorItem(_("Document header error"),
738 params().makeDocumentClass();
740 return unknown_tokens;
745 // changed to be public and have one parameter
746 // Returns true if "\end_document" is not read (Asger)
747 bool Buffer::readDocument(Lexer & lex)
749 ErrorList & errorList = d->errorLists["Parse"];
752 if (!lex.checkFor("\\begin_document")) {
753 docstring const s = _("\\begin_document is missing");
754 errorList.push_back(ErrorItem(_("Document header error"),
758 // we are reading in a brand new document
759 LASSERT(paragraphs().empty(), /**/);
763 if (params().outputChanges) {
764 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
765 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
766 LaTeXFeatures::isAvailable("xcolor");
768 if (!dvipost && !xcolorulem) {
769 Alert::warning(_("Changes not shown in LaTeX output"),
770 _("Changes will not be highlighted in LaTeX output, "
771 "because neither dvipost nor xcolor/ulem are installed.\n"
772 "Please install these packages or redefine "
773 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
774 } else if (!xcolorulem) {
775 Alert::warning(_("Changes not shown in LaTeX output"),
776 _("Changes will not be highlighted in LaTeX output "
777 "when using pdflatex, because xcolor and ulem are not installed.\n"
778 "Please install both packages or redefine "
779 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
783 if (!params().master.empty()) {
784 FileName const master_file = makeAbsPath(params().master,
785 onlyPath(absFileName()));
786 if (isLyXFileName(master_file.absFileName())) {
788 checkAndLoadLyXFile(master_file, true);
790 // necessary e.g. after a reload
791 // to re-register the child (bug 5873)
792 // FIXME: clean up updateMacros (here, only
793 // child registering is needed).
794 master->updateMacros();
795 // set master as master buffer, but only
796 // if we are a real child
797 if (master->isChild(this))
799 // if the master is not fully loaded
800 // it is probably just loading this
801 // child. No warning needed then.
802 else if (master->isFullyLoaded())
803 LYXERR0("The master '"
805 << "' assigned to this document ("
807 << ") does not include "
808 "this document. Ignoring the master assignment.");
813 // assure we have a default index
814 params().indiceslist().addDefault(B_("Index"));
817 bool const res = text().read(lex, errorList, d->inset);
821 updateMacroInstances();
826 bool Buffer::readString(string const & s)
828 params().compressed = false;
830 // remove dummy empty par
831 paragraphs().clear();
835 FileName const name = FileName::tempName("Buffer_readString");
836 switch (readFile(lex, name, true)) {
840 // We need to call lyx2lyx, so write the input to a file
841 ofstream os(name.toFilesystemEncoding().c_str());
844 return readFile(name);
854 bool Buffer::readFile(FileName const & filename)
856 FileName fname(filename);
858 params().compressed = fname.isZippedFile();
860 // remove dummy empty par
861 paragraphs().clear();
864 if (readFile(lex, fname) != success)
871 bool Buffer::isFullyLoaded() const
873 return d->file_fully_loaded;
877 void Buffer::setFullyLoaded(bool value)
879 d->file_fully_loaded = value;
883 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
886 LASSERT(!filename.empty(), /**/);
888 // the first (non-comment) token _must_ be...
889 if (!lex.checkFor("\\lyxformat")) {
890 Alert::error(_("Document format failure"),
891 bformat(_("%1$s is not a readable LyX document."),
892 from_utf8(filename.absFileName())));
898 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
899 // if present remove ".," from string.
900 size_t dot = tmp_format.find_first_of(".,");
901 //lyxerr << " dot found at " << dot << endl;
902 if (dot != string::npos)
903 tmp_format.erase(dot, 1);
904 int const file_format = convert<int>(tmp_format);
905 //lyxerr << "format: " << file_format << endl;
907 // save timestamp and checksum of the original disk file, making sure
908 // to not overwrite them with those of the file created in the tempdir
909 // when it has to be converted to the current format.
911 // Save the timestamp and checksum of disk file. If filename is an
912 // emergency file, save the timestamp and checksum of the original lyx file
913 // because isExternallyModified will check for this file. (BUG4193)
914 string diskfile = filename.absFileName();
915 if (suffixIs(diskfile, ".emergency"))
916 diskfile = diskfile.substr(0, diskfile.size() - 10);
917 saveCheckSum(FileName(diskfile));
920 if (file_format != LYX_FORMAT) {
923 // lyx2lyx would fail
926 FileName const tmpfile = FileName::tempName("Buffer_readFile");
927 if (tmpfile.empty()) {
928 Alert::error(_("Conversion failed"),
929 bformat(_("%1$s is from a different"
930 " version of LyX, but a temporary"
931 " file for converting it could"
933 from_utf8(filename.absFileName())));
936 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
937 if (lyx2lyx.empty()) {
938 Alert::error(_("Conversion script not found"),
939 bformat(_("%1$s is from a different"
940 " version of LyX, but the"
941 " conversion script lyx2lyx"
942 " could not be found."),
943 from_utf8(filename.absFileName())));
946 ostringstream command;
947 command << os::python()
948 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
949 << " -t " << convert<string>(LYX_FORMAT)
950 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
951 << ' ' << quoteName(filename.toSafeFilesystemEncoding());
952 string const command_str = command.str();
954 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
956 cmd_ret const ret = runCommand(command_str);
957 if (ret.first != 0) {
958 if (file_format < LYX_FORMAT)
959 Alert::error(_("Conversion script failed"),
960 bformat(_("%1$s is from an older version"
961 " of LyX, but the lyx2lyx script"
962 " failed to convert it."),
963 from_utf8(filename.absFileName())));
965 Alert::error(_("Conversion script failed"),
966 bformat(_("%1$s is from a newer version"
967 " of LyX and cannot be converted by the"
969 from_utf8(filename.absFileName())));
972 bool const ret = readFile(tmpfile);
973 // Do stuff with tmpfile name and buffer name here.
974 return ret ? success : failure;
979 if (readDocument(lex)) {
980 Alert::error(_("Document format failure"),
981 bformat(_("%1$s ended unexpectedly, which means"
982 " that it is probably corrupted."),
983 from_utf8(filename.absFileName())));
987 d->file_fully_loaded = true;
992 // Should probably be moved to somewhere else: BufferView? GuiView?
993 bool Buffer::save() const
995 // ask if the disk file has been externally modified (use checksum method)
996 if (fileName().exists() && isExternallyModified(checksum_method)) {
997 docstring const file = makeDisplayPath(absFileName(), 20);
998 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
999 "you want to overwrite this file?"), file);
1000 int const ret = Alert::prompt(_("Overwrite modified file?"),
1001 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1006 // We don't need autosaves in the immediate future. (Asger)
1007 resetAutosaveTimers();
1009 FileName backupName;
1010 bool madeBackup = false;
1012 // make a backup if the file already exists
1013 if (lyxrc.make_backup && fileName().exists()) {
1014 backupName = FileName(absFileName() + '~');
1015 if (!lyxrc.backupdir_path.empty()) {
1016 string const mangledName =
1017 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1018 backupName = FileName(addName(lyxrc.backupdir_path,
1021 // do not copy because of #6587
1022 if (fileName().moveTo(backupName)) {
1025 Alert::error(_("Backup failure"),
1026 bformat(_("Cannot create backup file %1$s.\n"
1027 "Please check whether the directory exists and is writeable."),
1028 from_utf8(backupName.absFileName())));
1029 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1033 if (writeFile(d->filename)) {
1037 // Saving failed, so backup is not backup
1039 backupName.moveTo(d->filename);
1045 bool Buffer::writeFile(FileName const & fname) const
1047 if (d->read_only && fname == d->filename)
1050 bool retval = false;
1052 docstring const str = bformat(_("Saving document %1$s..."),
1053 makeDisplayPath(fname.absFileName()));
1056 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1058 if (params().compressed) {
1059 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1060 retval = ofs && write(ofs);
1062 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1063 retval = ofs && write(ofs);
1067 message(str + _(" could not write file!"));
1072 // removeAutosaveFile();
1074 saveCheckSum(d->filename);
1075 message(str + _(" done."));
1081 docstring Buffer::emergencyWrite()
1083 // No need to save if the buffer has not changed.
1087 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1089 docstring user_message = bformat(
1090 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1092 // We try to save three places:
1093 // 1) Same place as document. Unless it is an unnamed doc.
1095 string s = absFileName();
1098 if (writeFile(FileName(s))) {
1100 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1101 return user_message;
1103 user_message += _(" Save failed! Trying again...\n");
1107 // 2) In HOME directory.
1108 string s = addName(package().home_dir().absFileName(), absFileName());
1110 lyxerr << ' ' << s << endl;
1111 if (writeFile(FileName(s))) {
1113 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1114 return user_message;
1117 user_message += _(" Save failed! Trying yet again...\n");
1119 // 3) In "/tmp" directory.
1120 // MakeAbsPath to prepend the current
1121 // drive letter on OS/2
1122 s = addName(package().temp_dir().absFileName(), absFileName());
1124 lyxerr << ' ' << s << endl;
1125 if (writeFile(FileName(s))) {
1127 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1128 return user_message;
1131 user_message += _(" Save failed! Bummer. Document is lost.");
1134 return user_message;
1138 bool Buffer::write(ostream & ofs) const
1141 // Use the standard "C" locale for file output.
1142 ofs.imbue(locale::classic());
1145 // The top of the file should not be written by params().
1147 // write out a comment in the top of the file
1148 ofs << "#LyX " << lyx_version
1149 << " created this file. For more info see http://www.lyx.org/\n"
1150 << "\\lyxformat " << LYX_FORMAT << "\n"
1151 << "\\begin_document\n";
1153 /// For each author, set 'used' to true if there is a change
1154 /// by this author in the document; otherwise set it to 'false'.
1155 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1156 AuthorList::Authors::const_iterator a_end = params().authors().end();
1157 for (; a_it != a_end; ++a_it)
1158 a_it->setUsed(false);
1160 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1161 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1162 for ( ; it != end; ++it)
1163 it->checkAuthors(params().authors());
1165 // now write out the buffer parameters.
1166 ofs << "\\begin_header\n";
1167 params().writeFile(ofs);
1168 ofs << "\\end_header\n";
1171 ofs << "\n\\begin_body\n";
1173 ofs << "\n\\end_body\n";
1175 // Write marker that shows file is complete
1176 ofs << "\\end_document" << endl;
1178 // Shouldn't really be needed....
1181 // how to check if close went ok?
1182 // Following is an attempt... (BE 20001011)
1184 // good() returns false if any error occured, including some
1185 // formatting error.
1186 // bad() returns true if something bad happened in the buffer,
1187 // which should include file system full errors.
1192 lyxerr << "File was not closed properly." << endl;
1199 bool Buffer::makeLaTeXFile(FileName const & fname,
1200 string const & original_path,
1201 OutputParams const & runparams_in,
1202 bool output_preamble, bool output_body) const
1204 OutputParams runparams = runparams_in;
1205 if (params().useXetex)
1206 runparams.flavor = OutputParams::XETEX;
1208 string const encoding = runparams.encoding->iconvName();
1209 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1212 try { ofs.reset(encoding); }
1213 catch (iconv_codecvt_facet_exception & e) {
1214 lyxerr << "Caught iconv exception: " << e.what() << endl;
1215 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1216 "verify that the support software for your encoding (%1$s) is "
1217 "properly installed"), from_ascii(encoding)));
1220 if (!openFileWrite(ofs, fname))
1223 //TexStream ts(ofs.rdbuf(), &texrow());
1224 ErrorList & errorList = d->errorLists["Export"];
1226 bool failed_export = false;
1229 writeLaTeXSource(ofs, original_path,
1230 runparams, output_preamble, output_body);
1232 catch (EncodingException & e) {
1233 odocstringstream ods;
1234 ods.put(e.failed_char);
1236 oss << "0x" << hex << e.failed_char << dec;
1237 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1238 " (code point %2$s)"),
1239 ods.str(), from_utf8(oss.str()));
1240 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1241 "representable in the chosen encoding.\n"
1242 "Changing the document encoding to utf8 could help."),
1243 e.par_id, e.pos, e.pos + 1));
1244 failed_export = true;
1246 catch (iconv_codecvt_facet_exception & e) {
1247 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1248 _(e.what()), -1, 0, 0));
1249 failed_export = true;
1251 catch (exception const & e) {
1252 errorList.push_back(ErrorItem(_("conversion failed"),
1253 _(e.what()), -1, 0, 0));
1254 failed_export = true;
1257 lyxerr << "Caught some really weird exception..." << endl;
1263 failed_export = true;
1264 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1268 return !failed_export;
1272 void Buffer::writeLaTeXSource(odocstream & os,
1273 string const & original_path,
1274 OutputParams const & runparams_in,
1275 bool const output_preamble, bool const output_body) const
1277 // The child documents, if any, shall be already loaded at this point.
1279 OutputParams runparams = runparams_in;
1281 // Classify the unicode characters appearing in math insets
1282 Encodings::initUnicodeMath(*this);
1284 // validate the buffer.
1285 LYXERR(Debug::LATEX, " Validating buffer...");
1286 LaTeXFeatures features(*this, params(), runparams);
1288 LYXERR(Debug::LATEX, " Buffer validation done.");
1290 // The starting paragraph of the coming rows is the
1291 // first paragraph of the document. (Asger)
1292 if (output_preamble && runparams.nice) {
1293 os << "%% LyX " << lyx_version << " created this file. "
1294 "For more info, see http://www.lyx.org/.\n"
1295 "%% Do not edit unless you really know what "
1297 d->texrow.newline();
1298 d->texrow.newline();
1300 LYXERR(Debug::INFO, "lyx document header finished");
1302 // Don't move this behind the parent_buffer=0 code below,
1303 // because then the macros will not get the right "redefinition"
1304 // flag as they don't see the parent macros which are output before.
1307 // fold macros if possible, still with parent buffer as the
1308 // macros will be put in the prefix anyway.
1309 updateMacroInstances();
1311 // There are a few differences between nice LaTeX and usual files:
1312 // usual is \batchmode and has a
1313 // special input@path to allow the including of figures
1314 // with either \input or \includegraphics (what figinsets do).
1315 // input@path is set when the actual parameter
1316 // original_path is set. This is done for usual tex-file, but not
1317 // for nice-latex-file. (Matthias 250696)
1318 // Note that input@path is only needed for something the user does
1319 // in the preamble, included .tex files or ERT, files included by
1320 // LyX work without it.
1321 if (output_preamble) {
1322 if (!runparams.nice) {
1323 // code for usual, NOT nice-latex-file
1324 os << "\\batchmode\n"; // changed
1325 // from \nonstopmode
1326 d->texrow.newline();
1328 if (!original_path.empty()) {
1330 // We don't know the encoding of inputpath
1331 docstring const inputpath = from_utf8(support::latex_path(original_path));
1332 docstring uncodable_glyphs;
1333 Encoding const * const enc = runparams.encoding;
1335 for (size_t n = 0; n < inputpath.size(); ++n) {
1336 docstring const glyph =
1337 docstring(1, inputpath[n]);
1338 if (enc->latexChar(inputpath[n], true) != glyph) {
1339 LYXERR0("Uncodable character '"
1341 << "' in input path!");
1342 uncodable_glyphs += glyph;
1347 // warn user if we found uncodable glyphs.
1348 if (!uncodable_glyphs.empty()) {
1349 frontend::Alert::warning(_("Uncodable character in file path"),
1350 support::bformat(_("The path of your document\n"
1352 "contains glyphs that are unknown in the\n"
1353 "current document encoding (namely %2$s).\n"
1354 "This will likely result in incomplete output.\n\n"
1355 "Choose an appropriate document encoding (such as utf8)\n"
1356 "or change the file path name."), inputpath, uncodable_glyphs));
1358 os << "\\makeatletter\n"
1359 << "\\def\\input@path{{"
1360 << inputpath << "/}}\n"
1361 << "\\makeatother\n";
1362 d->texrow.newline();
1363 d->texrow.newline();
1364 d->texrow.newline();
1368 // get parent macros (if this buffer has a parent) which will be
1369 // written at the document begin further down.
1370 MacroSet parentMacros;
1371 listParentMacros(parentMacros, features);
1373 // Write the preamble
1374 runparams.use_babel = params().writeLaTeX(os, features,
1376 d->filename.onlyPath());
1378 runparams.use_japanese = features.isRequired("japanese");
1384 os << "\\begin{document}\n";
1385 d->texrow.newline();
1387 // output the parent macros
1388 MacroSet::iterator it = parentMacros.begin();
1389 MacroSet::iterator end = parentMacros.end();
1390 for (; it != end; ++it) {
1391 int num_lines = (*it)->write(os, true);
1392 d->texrow.newlines(num_lines);
1395 } // output_preamble
1397 d->texrow.start(paragraphs().begin()->id(), 0);
1399 LYXERR(Debug::INFO, "preamble finished, now the body.");
1401 // if we are doing a real file with body, even if this is the
1402 // child of some other buffer, let's cut the link here.
1403 // This happens for example if only a child document is printed.
1404 Buffer const * save_parent = 0;
1405 if (output_preamble) {
1406 save_parent = d->parent();
1411 latexParagraphs(*this, text(), os, d->texrow, runparams);
1413 // Restore the parenthood if needed
1414 if (output_preamble)
1415 d->setParent(save_parent);
1417 // add this just in case after all the paragraphs
1419 d->texrow.newline();
1421 if (output_preamble) {
1422 os << "\\end{document}\n";
1423 d->texrow.newline();
1424 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1426 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1428 runparams_in.encoding = runparams.encoding;
1430 // Just to be sure. (Asger)
1431 d->texrow.newline();
1433 //for (int i = 0; i<d->texrow.rows(); i++) {
1435 // if (d->texrow.getIdFromRow(i+1,id,pos) && id>0)
1436 // lyxerr << i+1 << ":" << id << ":" << getParFromID(id).paragraph().asString()<<"\n";
1439 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1440 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1444 bool Buffer::isLatex() const
1446 return params().documentClass().outputType() == LATEX;
1450 bool Buffer::isLiterate() const
1452 return params().documentClass().outputType() == LITERATE;
1456 bool Buffer::isDocBook() const
1458 return params().documentClass().outputType() == DOCBOOK;
1462 void Buffer::makeDocBookFile(FileName const & fname,
1463 OutputParams const & runparams,
1464 bool const body_only) const
1466 LYXERR(Debug::LATEX, "makeDocBookFile...");
1469 if (!openFileWrite(ofs, fname))
1472 writeDocBookSource(ofs, fname.absFileName(), runparams, body_only);
1476 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1480 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1481 OutputParams const & runparams,
1482 bool const only_body) const
1484 LaTeXFeatures features(*this, params(), runparams);
1489 DocumentClass const & tclass = params().documentClass();
1490 string const top_element = tclass.latexname();
1493 if (runparams.flavor == OutputParams::XML)
1494 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1497 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1500 if (! tclass.class_header().empty())
1501 os << from_ascii(tclass.class_header());
1502 else if (runparams.flavor == OutputParams::XML)
1503 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1504 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1506 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1508 docstring preamble = from_utf8(params().preamble);
1509 if (runparams.flavor != OutputParams::XML ) {
1510 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1511 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1512 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1513 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1516 string const name = runparams.nice
1517 ? changeExtension(absFileName(), ".sgml") : fname;
1518 preamble += features.getIncludedFiles(name);
1519 preamble += features.getLyXSGMLEntities();
1521 if (!preamble.empty()) {
1522 os << "\n [ " << preamble << " ]";
1527 string top = top_element;
1529 if (runparams.flavor == OutputParams::XML)
1530 top += params().language->code();
1532 top += params().language->code().substr(0, 2);
1535 if (!params().options.empty()) {
1537 top += params().options;
1540 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1541 << " file was created by LyX " << lyx_version
1542 << "\n See http://www.lyx.org/ for more information -->\n";
1544 params().documentClass().counters().reset();
1548 sgml::openTag(os, top);
1550 docbookParagraphs(text(), *this, os, runparams);
1551 sgml::closeTag(os, top_element);
1555 void Buffer::makeLyXHTMLFile(FileName const & fname,
1556 OutputParams const & runparams,
1557 bool const body_only) const
1559 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1562 if (!openFileWrite(ofs, fname))
1565 writeLyXHTMLSource(ofs, runparams, body_only);
1569 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1573 void Buffer::writeLyXHTMLSource(odocstream & os,
1574 OutputParams const & runparams,
1575 bool const only_body) const
1577 LaTeXFeatures features(*this, params(), runparams);
1579 updateBuffer(UpdateMaster, OutputUpdate);
1580 d->bibinfo_.makeCitationLabels(*this);
1582 updateMacroInstances();
1585 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1586 << "<!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"
1587 // FIXME Language should be set properly.
1588 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
1590 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
1591 // FIXME Presumably need to set this right
1592 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1594 docstring const & doctitle = features.htmlTitle();
1596 << (doctitle.empty() ? from_ascii("LyX Document") : doctitle)
1599 os << "\n<!-- Text Class Preamble -->\n"
1600 << features.getTClassHTMLPreamble()
1601 << "\n<!-- Premable Snippets -->\n"
1602 << from_utf8(features.getPreambleSnippets());
1604 os << "\n<!-- Layout-provided Styles -->\n";
1605 docstring const styleinfo = features.getTClassHTMLStyles();
1606 if (!styleinfo.empty()) {
1607 os << "<style type='text/css'>\n"
1611 os << "</head>\n<body>\n";
1615 params().documentClass().counters().reset();
1616 xhtmlParagraphs(text(), *this, xs, runparams);
1618 os << "</body>\n</html>\n";
1622 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1623 // Other flags: -wall -v0 -x
1624 int Buffer::runChktex()
1628 // get LaTeX-Filename
1629 FileName const path(temppath());
1630 string const name = addName(path.absFileName(), latexName());
1631 string const org_path = filePath();
1633 PathChanger p(path); // path to LaTeX file
1634 message(_("Running chktex..."));
1636 // Generate the LaTeX file if neccessary
1637 OutputParams runparams(¶ms().encoding());
1638 runparams.flavor = OutputParams::LATEX;
1639 runparams.nice = false;
1640 runparams.linelen = lyxrc.plaintext_linelen;
1641 makeLaTeXFile(FileName(name), org_path, runparams);
1644 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
1645 int const res = chktex.run(terr); // run chktex
1648 Alert::error(_("chktex failure"),
1649 _("Could not run chktex successfully."));
1650 } else if (res > 0) {
1651 ErrorList & errlist = d->errorLists["ChkTeX"];
1653 bufferErrors(terr, errlist);
1664 void Buffer::validate(LaTeXFeatures & features) const
1666 params().validate(features);
1670 for_each(paragraphs().begin(), paragraphs().end(),
1671 bind(&Paragraph::validate, _1, ref(features)));
1673 if (lyxerr.debugging(Debug::LATEX)) {
1674 features.showStruct();
1679 void Buffer::getLabelList(vector<docstring> & list) const
1681 // If this is a child document, use the parent's list instead.
1682 Buffer const * const pbuf = d->parent();
1684 pbuf->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 // If this is a child document, use the parent's cache instead.
1702 Buffer const * const pbuf = d->parent();
1703 if (pbuf && scope != UpdateChildOnly) {
1704 pbuf->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 =
1712 static_cast<InsetBibtex const &>(*it);
1713 support::FileNameList const bibfiles = inset.getBibFiles();
1714 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1717 // the bibinfo cache is now invalid
1718 d->bibinfo_cache_valid_ = false;
1719 } else if (it->lyxCode() == INCLUDE_CODE) {
1720 InsetInclude & inset =
1721 static_cast<InsetInclude &>(*it);
1722 Buffer const * const incbuf = inset.getChildBuffer();
1725 incbuf->updateBibfilesCache(UpdateChildOnly);
1726 support::FileNameList const & bibfiles =
1727 incbuf->getBibfilesCache(UpdateChildOnly);
1728 if (!bibfiles.empty()) {
1729 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1732 // the bibinfo cache is now invalid
1733 d->bibinfo_cache_valid_ = false;
1737 d->bibfile_cache_valid_ = true;
1741 void Buffer::invalidateBibinfoCache()
1743 d->bibinfo_cache_valid_ = false;
1747 void Buffer::invalidateBibfileCache()
1749 d->bibfile_cache_valid_ = false;
1750 invalidateBibinfoCache();
1753 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1755 // If this is a child document, use the parent's cache instead.
1756 Buffer const * const pbuf = d->parent();
1757 if (pbuf && scope != UpdateChildOnly)
1758 return pbuf->getBibfilesCache();
1760 if (!d->bibfile_cache_valid_)
1761 this->updateBibfilesCache(scope);
1763 return d->bibfiles_cache_;
1767 BiblioInfo const & Buffer::masterBibInfo() const
1769 // if this is a child document and the parent is already loaded
1770 // use the parent's list instead [ale990412]
1771 Buffer const * const tmp = masterBuffer();
1774 return tmp->masterBibInfo();
1775 return localBibInfo();
1779 BiblioInfo const & Buffer::localBibInfo() const
1785 void Buffer::checkBibInfoCache() const
1787 support::FileNameList const & bibfilesCache = getBibfilesCache();
1788 // compare the cached timestamps with the actual ones.
1789 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1790 support::FileNameList::const_iterator en = bibfilesCache.end();
1791 for (; ei != en; ++ ei) {
1792 time_t lastw = ei->lastModified();
1793 time_t prevw = d->bibfile_status_[*ei];
1794 if (lastw != prevw) {
1795 d->bibinfo_cache_valid_ = false;
1796 d->bibfile_status_[*ei] = lastw;
1800 // FIXME Don't do this here, but instead gather them as we go through
1802 if (!d->bibinfo_cache_valid_) {
1803 d->bibinfo_.clear();
1804 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1805 it->fillWithBibKeys(d->bibinfo_, it);
1806 d->bibinfo_cache_valid_ = true;
1811 bool Buffer::isDepClean(string const & name) const
1813 DepClean::const_iterator const it = d->dep_clean.find(name);
1814 if (it == d->dep_clean.end())
1820 void Buffer::markDepClean(string const & name)
1822 d->dep_clean[name] = true;
1826 bool Buffer::isExportableFormat(string const & format) const
1828 typedef vector<Format const *> Formats;
1830 formats = exportableFormats(true);
1831 Formats::const_iterator fit = formats.begin();
1832 Formats::const_iterator end = formats.end();
1833 for (; fit != end ; ++fit) {
1834 if ((*fit)->name() == format)
1841 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1844 // FIXME? if there is an Buffer LFUN that can be dispatched even
1845 // if internal, put a switch '(cmd.action)' here.
1851 switch (cmd.action()) {
1853 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1854 flag.setOnOff(isReadonly());
1857 // FIXME: There is need for a command-line import.
1858 //case LFUN_BUFFER_IMPORT:
1860 case LFUN_BUFFER_AUTO_SAVE:
1863 case LFUN_BUFFER_EXPORT_CUSTOM:
1864 // FIXME: Nothing to check here?
1867 case LFUN_BUFFER_EXPORT: {
1868 docstring const arg = cmd.argument();
1869 enable = arg == "custom" || isExportable(to_utf8(arg));
1871 flag.message(bformat(
1872 _("Don't know how to export to format: %1$s"), arg));
1876 case LFUN_BUFFER_CHKTEX:
1877 enable = isLatex() && !lyxrc.chktex_command.empty();
1880 case LFUN_BUILD_PROGRAM:
1881 enable = isExportable("program");
1884 case LFUN_BRANCH_ACTIVATE:
1885 case LFUN_BRANCH_DEACTIVATE: {
1886 BranchList const & branchList = params().branchlist();
1887 docstring const branchName = cmd.argument();
1888 enable = !branchName.empty() && branchList.find(branchName);
1892 case LFUN_BRANCH_ADD:
1893 case LFUN_BRANCHES_RENAME:
1894 case LFUN_BUFFER_PRINT:
1895 // if no Buffer is present, then of course we won't be called!
1898 case LFUN_BUFFER_LANGUAGE:
1899 enable = !isReadonly();
1905 flag.setEnabled(enable);
1910 void Buffer::dispatch(string const & command, DispatchResult & result)
1912 return dispatch(lyxaction.lookupFunc(command), result);
1916 // NOTE We can end up here even if we have no GUI, because we are called
1917 // by LyX::exec to handled command-line requests. So we may need to check
1918 // whether we have a GUI or not. The boolean use_gui holds this information.
1919 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
1922 // FIXME? if there is an Buffer LFUN that can be dispatched even
1923 // if internal, put a switch '(cmd.action())' here.
1924 dr.dispatched(false);
1927 string const argument = to_utf8(func.argument());
1928 // We'll set this back to false if need be.
1929 bool dispatched = true;
1930 undo().beginUndoGroup();
1932 switch (func.action()) {
1933 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1934 if (lyxvc().inUse())
1935 lyxvc().toggleReadOnly();
1937 setReadonly(!isReadonly());
1940 case LFUN_BUFFER_EXPORT: {
1941 bool success = doExport(argument, false, false);
1942 dr.setError(!success);
1944 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
1949 case LFUN_BUILD_PROGRAM:
1950 doExport("program", true, false);
1953 case LFUN_BUFFER_CHKTEX:
1957 case LFUN_BUFFER_EXPORT_CUSTOM: {
1959 string command = split(argument, format_name, ' ');
1960 Format const * format = formats.getFormat(format_name);
1962 lyxerr << "Format \"" << format_name
1963 << "\" not recognized!"
1968 // The name of the file created by the conversion process
1971 // Output to filename
1972 if (format->name() == "lyx") {
1973 string const latexname = latexName(false);
1974 filename = changeExtension(latexname,
1975 format->extension());
1976 filename = addName(temppath(), filename);
1978 if (!writeFile(FileName(filename)))
1982 doExport(format_name, true, false, filename);
1985 // Substitute $$FName for filename
1986 if (!contains(command, "$$FName"))
1987 command = "( " + command + " ) < $$FName";
1988 command = subst(command, "$$FName", filename);
1990 // Execute the command in the background
1992 call.startscript(Systemcall::DontWait, command);
1996 // FIXME: There is need for a command-line import.
1998 case LFUN_BUFFER_IMPORT:
2003 case LFUN_BUFFER_AUTO_SAVE:
2007 case LFUN_BRANCH_ADD: {
2008 docstring branch_name = func.argument();
2009 if (branch_name.empty()) {
2013 BranchList & branch_list = params().branchlist();
2014 vector<docstring> const branches =
2015 getVectorFromString(branch_name, branch_list.separator());
2017 for (vector<docstring>::const_iterator it = branches.begin();
2018 it != branches.end(); ++it) {
2020 Branch * branch = branch_list.find(branch_name);
2022 LYXERR0("Branch " << branch_name << " already exists.");
2026 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2028 branch_list.add(branch_name);
2029 branch = branch_list.find(branch_name);
2030 string const x11hexname = X11hexname(branch->color());
2031 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2032 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2034 dr.update(Update::Force);
2042 case LFUN_BRANCH_ACTIVATE:
2043 case LFUN_BRANCH_DEACTIVATE: {
2044 BranchList & branchList = params().branchlist();
2045 docstring const branchName = func.argument();
2046 // the case without a branch name is handled elsewhere
2047 if (branchName.empty()) {
2051 Branch * branch = branchList.find(branchName);
2053 LYXERR0("Branch " << branchName << " does not exist.");
2055 docstring const msg =
2056 bformat(_("Branch \"%1$s\" does not exist."), branchName);
2059 branch->setSelected(func.action() == LFUN_BRANCH_ACTIVATE);
2061 dr.update(Update::Force);
2062 dr.forceBufferUpdate();
2067 case LFUN_BRANCHES_RENAME: {
2068 if (func.argument().empty())
2071 docstring const oldname = from_utf8(func.getArg(0));
2072 docstring const newname = from_utf8(func.getArg(1));
2073 InsetIterator it = inset_iterator_begin(inset());
2074 InsetIterator const end = inset_iterator_end(inset());
2075 bool success = false;
2076 for (; it != end; ++it) {
2077 if (it->lyxCode() == BRANCH_CODE) {
2078 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2079 if (ins.branch() == oldname) {
2080 undo().recordUndo(it);
2081 ins.rename(newname);
2086 if (it->lyxCode() == INCLUDE_CODE) {
2087 // get buffer of external file
2088 InsetInclude const & ins =
2089 static_cast<InsetInclude const &>(*it);
2090 Buffer * child = ins.getChildBuffer();
2093 child->dispatch(func, dr);
2098 dr.update(Update::Force);
2099 dr.forceBufferUpdate();
2104 case LFUN_BUFFER_PRINT: {
2105 // we'll assume there's a problem until we succeed
2107 string target = func.getArg(0);
2108 string target_name = func.getArg(1);
2109 string command = func.getArg(2);
2112 || target_name.empty()
2113 || command.empty()) {
2114 LYXERR0("Unable to parse " << func.argument());
2115 docstring const msg =
2116 bformat(_("Unable to parse \"%1$s\""), func.argument());
2120 if (target != "printer" && target != "file") {
2121 LYXERR0("Unrecognized target \"" << target << '"');
2122 docstring const msg =
2123 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2128 bool const update_unincluded =
2129 params().maintain_unincluded_children
2130 && !params().getIncludedChildren().empty();
2131 if (!doExport("dvi", true, update_unincluded)) {
2132 showPrintError(absFileName());
2133 dr.setMessage(_("Error exporting to DVI."));
2137 // Push directory path.
2138 string const path = temppath();
2139 // Prevent the compiler from optimizing away p
2143 // there are three cases here:
2144 // 1. we print to a file
2145 // 2. we print directly to a printer
2146 // 3. we print using a spool command (print to file first)
2149 string const dviname = changeExtension(latexName(true), "dvi");
2151 if (target == "printer") {
2152 if (!lyxrc.print_spool_command.empty()) {
2153 // case 3: print using a spool
2154 string const psname = changeExtension(dviname,".ps");
2155 command += ' ' + lyxrc.print_to_file
2158 + quoteName(dviname);
2160 string command2 = lyxrc.print_spool_command + ' ';
2161 if (target_name != "default") {
2162 command2 += lyxrc.print_spool_printerprefix
2166 command2 += quoteName(psname);
2168 // If successful, then spool command
2169 res = one.startscript(Systemcall::Wait, command);
2172 // If there's no GUI, we have to wait on this command. Otherwise,
2173 // LyX deletes the temporary directory, and with it the spooled
2174 // file, before it can be printed!!
2175 Systemcall::Starttype stype = use_gui ?
2176 Systemcall::DontWait : Systemcall::Wait;
2177 res = one.startscript(stype, command2);
2180 // case 2: print directly to a printer
2181 if (target_name != "default")
2182 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2184 Systemcall::Starttype stype = use_gui ?
2185 Systemcall::DontWait : Systemcall::Wait;
2186 res = one.startscript(stype, command + quoteName(dviname));
2190 // case 1: print to a file
2191 FileName const filename(makeAbsPath(target_name, filePath()));
2192 FileName const dvifile(makeAbsPath(dviname, path));
2193 if (filename.exists()) {
2194 docstring text = bformat(
2195 _("The file %1$s already exists.\n\n"
2196 "Do you want to overwrite that file?"),
2197 makeDisplayPath(filename.absFileName()));
2198 if (Alert::prompt(_("Overwrite file?"),
2199 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2202 command += ' ' + lyxrc.print_to_file
2203 + quoteName(filename.toFilesystemEncoding())
2205 + quoteName(dvifile.toFilesystemEncoding());
2207 Systemcall::Starttype stype = use_gui ?
2208 Systemcall::DontWait : Systemcall::Wait;
2209 res = one.startscript(stype, command);
2215 dr.setMessage(_("Error running external commands."));
2216 showPrintError(absFileName());
2221 case LFUN_BUFFER_LANGUAGE: {
2222 Language const * oldL = params().language;
2223 Language const * newL = languages.getLanguage(argument);
2224 if (!newL || oldL == newL)
2226 if (oldL->rightToLeft() == newL->rightToLeft() && !isMultiLingual()) {
2227 changeLanguage(oldL, newL);
2228 dr.forceBufferUpdate();
2237 dr.dispatched(dispatched);
2238 undo().endUndoGroup();
2242 void Buffer::changeLanguage(Language const * from, Language const * to)
2244 LASSERT(from, /**/);
2247 for_each(par_iterator_begin(),
2249 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2253 bool Buffer::isMultiLingual() const
2255 ParConstIterator end = par_iterator_end();
2256 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2257 if (it->isMultiLingual(params()))
2264 std::set<Language const *> Buffer::getLanguages() const
2266 std::set<Language const *> languages;
2267 getLanguages(languages);
2272 void Buffer::getLanguages(std::set<Language const *> & languages) const
2274 ParConstIterator end = par_iterator_end();
2275 // add the buffer language, even if it's not actively used
2276 languages.insert(language());
2277 // iterate over the paragraphs
2278 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2279 it->getLanguages(languages);
2281 std::vector<Buffer *> clist = getChildren();
2282 for (vector<Buffer *>::const_iterator cit = clist.begin();
2283 cit != clist.end(); ++cit)
2284 (*cit)->getLanguages(languages);
2288 DocIterator Buffer::getParFromID(int const id) const
2290 Buffer * buf = const_cast<Buffer *>(this);
2292 // John says this is called with id == -1 from undo
2293 lyxerr << "getParFromID(), id: " << id << endl;
2294 return doc_iterator_end(buf);
2297 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2298 if (it.paragraph().id() == id)
2301 return doc_iterator_end(buf);
2305 bool Buffer::hasParWithID(int const id) const
2307 return !getParFromID(id).atEnd();
2311 ParIterator Buffer::par_iterator_begin()
2313 return ParIterator(doc_iterator_begin(this));
2317 ParIterator Buffer::par_iterator_end()
2319 return ParIterator(doc_iterator_end(this));
2323 ParConstIterator Buffer::par_iterator_begin() const
2325 return ParConstIterator(doc_iterator_begin(this));
2329 ParConstIterator Buffer::par_iterator_end() const
2331 return ParConstIterator(doc_iterator_end(this));
2335 Language const * Buffer::language() const
2337 return params().language;
2341 docstring const Buffer::B_(string const & l10n) const
2343 return params().B_(l10n);
2347 bool Buffer::isClean() const
2349 return d->lyx_clean;
2353 bool Buffer::isExternallyModified(CheckMethod method) const
2355 LASSERT(d->filename.exists(), /**/);
2356 // if method == timestamp, check timestamp before checksum
2357 return (method == checksum_method
2358 || d->timestamp_ != d->filename.lastModified())
2359 && d->checksum_ != d->filename.checksum();
2363 void Buffer::saveCheckSum(FileName const & file) const
2365 if (file.exists()) {
2366 d->timestamp_ = file.lastModified();
2367 d->checksum_ = file.checksum();
2369 // in the case of save to a new file.
2376 void Buffer::markClean() const
2378 if (!d->lyx_clean) {
2379 d->lyx_clean = true;
2382 // if the .lyx file has been saved, we don't need an
2384 d->bak_clean = true;
2385 d->undo_.markDirty();
2389 void Buffer::setUnnamed(bool flag)
2395 bool Buffer::isUnnamed() const
2402 /// Don't check unnamed, here: isInternal() is used in
2403 /// newBuffer(), where the unnamed flag has not been set by anyone
2404 /// yet. Also, for an internal buffer, there should be no need for
2405 /// retrieving fileName() nor for checking if it is unnamed or not.
2406 bool Buffer::isInternal() const
2408 return fileName().extension() == "internal";
2412 void Buffer::markDirty()
2415 d->lyx_clean = false;
2418 d->bak_clean = false;
2420 DepClean::iterator it = d->dep_clean.begin();
2421 DepClean::const_iterator const end = d->dep_clean.end();
2423 for (; it != end; ++it)
2428 FileName Buffer::fileName() const
2434 string Buffer::absFileName() const
2436 return d->filename.absFileName();
2440 string Buffer::filePath() const
2442 return d->filename.onlyPath().absFileName() + "/";
2446 bool Buffer::isReadonly() const
2448 return d->read_only;
2452 void Buffer::setParent(Buffer const * buffer)
2454 // Avoids recursive include.
2455 d->setParent(buffer == this ? 0 : buffer);
2460 Buffer const * Buffer::parent() const
2466 void Buffer::Impl::collectRelatives(BufferSet & bufs) const
2468 bufs.insert(owner_);
2470 parent()->d->collectRelatives(bufs);
2472 // loop over children
2473 BufferPositionMap::const_iterator it = children_positions.begin();
2474 BufferPositionMap::const_iterator end = children_positions.end();
2475 for (; it != end; ++it)
2476 bufs.insert(const_cast<Buffer *>(it->first));
2480 std::vector<Buffer const *> Buffer::allRelatives() const
2483 d->collectRelatives(bufs);
2484 BufferSet::iterator it = bufs.begin();
2485 std::vector<Buffer const *> ret;
2486 for (; it != bufs.end(); ++it)
2492 Buffer const * Buffer::masterBuffer() const
2494 Buffer const * const pbuf = d->parent();
2498 return pbuf->masterBuffer();
2502 bool Buffer::isChild(Buffer * child) const
2504 return d->children_positions.find(child) != d->children_positions.end();
2508 DocIterator Buffer::firstChildPosition(Buffer const * child)
2510 Impl::BufferPositionMap::iterator it;
2511 it = d->children_positions.find(child);
2512 if (it == d->children_positions.end())
2513 return DocIterator(this);
2518 void Buffer::getChildren(std::vector<Buffer *> & clist, bool grand_children) const
2520 // loop over children
2521 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2522 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2523 for (; it != end; ++it) {
2524 Buffer * child = const_cast<Buffer *>(it->first);
2525 clist.push_back(child);
2526 if (grand_children) {
2527 // there might be grandchildren
2528 vector<Buffer *> glist = child->getChildren();
2529 clist.insert(clist.end(), glist.begin(), glist.end());
2535 vector<Buffer *> Buffer::getChildren(bool grand_children) const
2538 getChildren(v, grand_children);
2543 template<typename M>
2544 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
2549 typename M::const_iterator it = m.lower_bound(x);
2550 if (it == m.begin())
2558 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
2559 DocIterator const & pos) const
2561 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2563 // if paragraphs have no macro context set, pos will be empty
2567 // we haven't found anything yet
2568 DocIterator bestPos = owner_->par_iterator_begin();
2569 MacroData const * bestData = 0;
2571 // find macro definitions for name
2572 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
2573 if (nameIt != macros.end()) {
2574 // find last definition in front of pos or at pos itself
2575 PositionScopeMacroMap::const_iterator it
2576 = greatest_below(nameIt->second, pos);
2577 if (it != nameIt->second.end()) {
2579 // scope ends behind pos?
2580 if (pos < it->second.first) {
2581 // Looks good, remember this. If there
2582 // is no external macro behind this,
2583 // we found the right one already.
2584 bestPos = it->first;
2585 bestData = &it->second.second;
2589 // try previous macro if there is one
2590 if (it == nameIt->second.begin())
2597 // find macros in included files
2598 PositionScopeBufferMap::const_iterator it
2599 = greatest_below(position_to_children, pos);
2600 if (it == position_to_children.end())
2601 // no children before
2605 // do we know something better (i.e. later) already?
2606 if (it->first < bestPos )
2609 // scope ends behind pos?
2610 if (pos < it->second.first) {
2611 // look for macro in external file
2613 MacroData const * data
2614 = it->second.second->getMacro(name, false);
2617 bestPos = it->first;
2623 // try previous file if there is one
2624 if (it == position_to_children.begin())
2629 // return the best macro we have found
2634 MacroData const * Buffer::getMacro(docstring const & name,
2635 DocIterator const & pos, bool global) const
2640 // query buffer macros
2641 MacroData const * data = d->getBufferMacro(name, pos);
2645 // If there is a master buffer, query that
2646 Buffer const * const pbuf = d->parent();
2648 d->macro_lock = true;
2649 MacroData const * macro = pbuf->getMacro(
2650 name, *this, false);
2651 d->macro_lock = false;
2657 data = MacroTable::globalMacros().get(name);
2666 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2668 // set scope end behind the last paragraph
2669 DocIterator scope = par_iterator_begin();
2670 scope.pit() = scope.lastpit() + 1;
2672 return getMacro(name, scope, global);
2676 MacroData const * Buffer::getMacro(docstring const & name,
2677 Buffer const & child, bool global) const
2679 // look where the child buffer is included first
2680 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2681 if (it == d->children_positions.end())
2684 // check for macros at the inclusion position
2685 return getMacro(name, it->second, global);
2689 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
2691 pit_type const lastpit = it.lastpit();
2693 // look for macros in each paragraph
2694 while (it.pit() <= lastpit) {
2695 Paragraph & par = it.paragraph();
2697 // iterate over the insets of the current paragraph
2698 InsetList const & insets = par.insetList();
2699 InsetList::const_iterator iit = insets.begin();
2700 InsetList::const_iterator end = insets.end();
2701 for (; iit != end; ++iit) {
2702 it.pos() = iit->pos;
2704 // is it a nested text inset?
2705 if (iit->inset->asInsetText()) {
2706 // Inset needs its own scope?
2707 InsetText const * itext = iit->inset->asInsetText();
2708 bool newScope = itext->isMacroScope();
2710 // scope which ends just behind the inset
2711 DocIterator insetScope = it;
2714 // collect macros in inset
2715 it.push_back(CursorSlice(*iit->inset));
2716 updateMacros(it, newScope ? insetScope : scope);
2721 // is it an external file?
2722 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2723 // get buffer of external file
2724 InsetInclude const & inset =
2725 static_cast<InsetInclude const &>(*iit->inset);
2727 Buffer * child = inset.getChildBuffer();
2732 // register its position, but only when it is
2733 // included first in the buffer
2734 if (children_positions.find(child) ==
2735 children_positions.end())
2736 children_positions[child] = it;
2738 // register child with its scope
2739 position_to_children[it] = Impl::ScopeBuffer(scope, child);
2743 if (doing_export && iit->inset->asInsetMath()) {
2744 InsetMath * im = static_cast<InsetMath *>(iit->inset);
2745 if (im->asHullInset()) {
2746 InsetMathHull * hull = static_cast<InsetMathHull *>(im);
2747 hull->recordLocation(it);
2751 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2755 MathMacroTemplate & macroTemplate =
2756 static_cast<MathMacroTemplate &>(*iit->inset);
2757 MacroContext mc(owner_, it);
2758 macroTemplate.updateToContext(mc);
2761 bool valid = macroTemplate.validMacro();
2762 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2763 // then the BufferView's cursor will be invalid in
2764 // some cases which leads to crashes.
2769 // FIXME (Abdel), I don't understandt why we pass 'it' here
2770 // instead of 'macroTemplate' defined above... is this correct?
2771 macros[macroTemplate.name()][it] =
2772 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
2782 void Buffer::updateMacros() const
2787 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2789 // start with empty table
2791 d->children_positions.clear();
2792 d->position_to_children.clear();
2794 // Iterate over buffer, starting with first paragraph
2795 // The scope must be bigger than any lookup DocIterator
2796 // later. For the global lookup, lastpit+1 is used, hence
2797 // we use lastpit+2 here.
2798 DocIterator it = par_iterator_begin();
2799 DocIterator outerScope = it;
2800 outerScope.pit() = outerScope.lastpit() + 2;
2801 d->updateMacros(it, outerScope);
2805 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
2807 InsetIterator it = inset_iterator_begin(inset());
2808 InsetIterator const end = inset_iterator_end(inset());
2809 for (; it != end; ++it) {
2810 if (it->lyxCode() == BRANCH_CODE) {
2811 InsetBranch & br = static_cast<InsetBranch &>(*it);
2812 docstring const name = br.branch();
2813 if (!from_master && !params().branchlist().find(name))
2814 result.push_back(name);
2815 else if (from_master && !masterBuffer()->params().branchlist().find(name))
2816 result.push_back(name);
2819 if (it->lyxCode() == INCLUDE_CODE) {
2820 // get buffer of external file
2821 InsetInclude const & ins =
2822 static_cast<InsetInclude const &>(*it);
2823 Buffer * child = ins.getChildBuffer();
2826 child->getUsedBranches(result, true);
2829 // remove duplicates
2834 void Buffer::updateMacroInstances() const
2836 LYXERR(Debug::MACROS, "updateMacroInstances for "
2837 << d->filename.onlyFileName());
2838 DocIterator it = doc_iterator_begin(this);
2840 DocIterator const end = doc_iterator_end(this);
2841 for (; it != end; it.forwardInset()) {
2842 // look for MathData cells in InsetMathNest insets
2843 InsetMath * minset = it.nextInset()->asInsetMath();
2847 // update macro in all cells of the InsetMathNest
2848 DocIterator::idx_type n = minset->nargs();
2849 MacroContext mc = MacroContext(this, it);
2850 for (DocIterator::idx_type i = 0; i < n; ++i) {
2851 MathData & data = minset->cell(i);
2852 data.updateMacros(0, mc);
2858 void Buffer::listMacroNames(MacroNameSet & macros) const
2863 d->macro_lock = true;
2865 // loop over macro names
2866 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2867 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2868 for (; nameIt != nameEnd; ++nameIt)
2869 macros.insert(nameIt->first);
2871 // loop over children
2872 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2873 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2874 for (; it != end; ++it)
2875 it->first->listMacroNames(macros);
2878 Buffer const * const pbuf = d->parent();
2880 pbuf->listMacroNames(macros);
2882 d->macro_lock = false;
2886 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2888 Buffer const * const pbuf = d->parent();
2893 pbuf->listMacroNames(names);
2896 MacroNameSet::iterator it = names.begin();
2897 MacroNameSet::iterator end = names.end();
2898 for (; it != end; ++it) {
2900 MacroData const * data =
2901 pbuf->getMacro(*it, *this, false);
2903 macros.insert(data);
2905 // we cannot access the original MathMacroTemplate anymore
2906 // here to calls validate method. So we do its work here manually.
2907 // FIXME: somehow make the template accessible here.
2908 if (data->optionals() > 0)
2909 features.require("xargs");
2915 Buffer::References & Buffer::references(docstring const & label)
2918 return const_cast<Buffer *>(masterBuffer())->references(label);
2920 RefCache::iterator it = d->ref_cache_.find(label);
2921 if (it != d->ref_cache_.end())
2922 return it->second.second;
2924 static InsetLabel const * dummy_il = 0;
2925 static References const dummy_refs;
2926 it = d->ref_cache_.insert(
2927 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2928 return it->second.second;
2932 Buffer::References const & Buffer::references(docstring const & label) const
2934 return const_cast<Buffer *>(this)->references(label);
2938 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2940 masterBuffer()->d->ref_cache_[label].first = il;
2944 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2946 return masterBuffer()->d->ref_cache_[label].first;
2950 void Buffer::clearReferenceCache() const
2953 d->ref_cache_.clear();
2957 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2960 //FIXME: This does not work for child documents yet.
2961 LASSERT(code == CITE_CODE, /**/);
2962 // Check if the label 'from' appears more than once
2963 vector<docstring> labels;
2965 checkBibInfoCache();
2966 BiblioInfo const & keys = masterBibInfo();
2967 BiblioInfo::const_iterator bit = keys.begin();
2968 BiblioInfo::const_iterator bend = keys.end();
2970 for (; bit != bend; ++bit)
2972 labels.push_back(bit->first);
2975 if (count(labels.begin(), labels.end(), from) > 1)
2978 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2979 if (it->lyxCode() == code) {
2980 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2981 docstring const oldValue = inset.getParam(paramName);
2982 if (oldValue == from)
2983 inset.setParam(paramName, to);
2989 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2990 pit_type par_end, bool full_source) const
2992 OutputParams runparams(¶ms().encoding());
2993 runparams.nice = true;
2994 runparams.flavor = params().useXetex ?
2995 OutputParams::XETEX : OutputParams::LATEX;
2996 runparams.linelen = lyxrc.plaintext_linelen;
2997 // No side effect of file copying and image conversion
2998 runparams.dryrun = true;
3001 os << "% " << _("Preview source code") << "\n\n";
3003 d->texrow.newline();
3004 d->texrow.newline();
3006 writeDocBookSource(os, absFileName(), runparams, false);
3008 // latex or literate
3009 writeLaTeXSource(os, string(), runparams, true, true);
3011 runparams.par_begin = par_begin;
3012 runparams.par_end = par_end;
3013 if (par_begin + 1 == par_end) {
3015 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3019 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3020 convert<docstring>(par_begin),
3021 convert<docstring>(par_end - 1))
3028 // output paragraphs
3030 docbookParagraphs(text(), *this, os, runparams);
3032 // latex or literate
3033 latexParagraphs(*this, text(), os, texrow, runparams);
3038 ErrorList & Buffer::errorList(string const & type) const
3040 static ErrorList emptyErrorList;
3041 map<string, ErrorList>::iterator it = d->errorLists.find(type);
3042 if (it == d->errorLists.end())
3043 return emptyErrorList;
3049 void Buffer::updateTocItem(std::string const & type,
3050 DocIterator const & dit) const
3053 d->gui_->updateTocItem(type, dit);
3057 void Buffer::structureChanged() const
3060 d->gui_->structureChanged();
3064 void Buffer::errors(string const & err, bool from_master) const
3067 d->gui_->errors(err, from_master);
3071 void Buffer::message(docstring const & msg) const
3074 d->gui_->message(msg);
3078 void Buffer::setBusy(bool on) const
3081 d->gui_->setBusy(on);
3085 void Buffer::updateTitles() const
3088 d->wa_->updateTitles();
3092 void Buffer::resetAutosaveTimers() const
3095 d->gui_->resetAutosaveTimers();
3099 bool Buffer::hasGuiDelegate() const
3105 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3114 class AutoSaveBuffer : public ForkedProcess {
3117 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3118 : buffer_(buffer), fname_(fname) {}
3120 virtual shared_ptr<ForkedProcess> clone() const
3122 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3127 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3128 from_utf8(fname_.absFileName())));
3129 return run(DontWait);
3133 virtual int generateChild();
3135 Buffer const & buffer_;
3140 int AutoSaveBuffer::generateChild()
3142 #if defined(__APPLE__)
3143 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3144 * We should use something else like threads.
3146 * Since I do not know how to determine at run time what is the OS X
3147 * version, I just disable forking altogether for now (JMarc)
3149 pid_t const pid = -1;
3151 // tmp_ret will be located (usually) in /tmp
3152 // will that be a problem?
3153 // Note that this calls ForkedCalls::fork(), so it's
3154 // ok cross-platform.
3155 pid_t const pid = fork();
3156 // If you want to debug the autosave
3157 // you should set pid to -1, and comment out the fork.
3158 if (pid != 0 && pid != -1)
3162 // pid = -1 signifies that lyx was unable
3163 // to fork. But we will do the save
3165 bool failed = false;
3166 FileName const tmp_ret = FileName::tempName("lyxauto");
3167 if (!tmp_ret.empty()) {
3168 buffer_.writeFile(tmp_ret);
3169 // assume successful write of tmp_ret
3170 if (!tmp_ret.moveTo(fname_))
3176 // failed to write/rename tmp_ret so try writing direct
3177 if (!buffer_.writeFile(fname_)) {
3178 // It is dangerous to do this in the child,
3179 // but safe in the parent, so...
3180 if (pid == -1) // emit message signal.
3181 buffer_.message(_("Autosave failed!"));
3185 if (pid == 0) // we are the child so...
3194 FileName Buffer::getAutosaveFileName() const
3196 // if the document is unnamed try to save in the backup dir, else
3197 // in the default document path, and as a last try in the filePath,
3198 // which will most often be the temporary directory
3201 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3202 : lyxrc.backupdir_path;
3203 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3206 string const fname = "#" + d->filename.onlyFileName() + "#";
3207 return makeAbsPath(fname, fpath);
3211 void Buffer::removeAutosaveFile() const
3213 FileName const f = getAutosaveFileName();
3219 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3221 FileName const newauto = getAutosaveFileName();
3223 if (newauto != oldauto && oldauto.exists())
3224 if (!oldauto.moveTo(newauto))
3225 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3229 // Perfect target for a thread...
3230 void Buffer::autoSave() const
3232 if (d->bak_clean || isReadonly()) {
3233 // We don't save now, but we'll try again later
3234 resetAutosaveTimers();
3238 // emit message signal.
3239 message(_("Autosaving current document..."));
3240 AutoSaveBuffer autosave(*this, getAutosaveFileName());
3243 d->bak_clean = true;
3245 resetAutosaveTimers();
3249 string Buffer::bufferFormat() const
3251 string format = params().documentClass().outputFormat();
3252 if (format == "latex") {
3253 if (params().useXetex)
3255 if (params().encoding().package() == Encoding::japanese)
3262 string Buffer::getDefaultOutputFormat() const
3264 if (!params().defaultOutputFormat.empty()
3265 && params().defaultOutputFormat != "default")
3266 return params().defaultOutputFormat;
3267 typedef vector<Format const *> Formats;
3268 Formats formats = exportableFormats(true);
3271 || params().useXetex
3272 || params().encoding().package() == Encoding::japanese) {
3273 if (formats.empty())
3275 // return the first we find
3276 return formats.front()->name();
3278 return lyxrc.default_view_format;
3283 // helper class, to guarantee this gets reset properly
3284 class MarkAsExporting {
3286 MarkAsExporting(Buffer const * buf) : buf_(buf)
3288 LASSERT(buf_, /* */);
3289 buf_->setExportStatus(true);
3293 buf_->setExportStatus(false);
3296 Buffer const * const buf_;
3301 void Buffer::setExportStatus(bool e) const
3303 d->doing_export = e;
3307 bool Buffer::isExporting() const
3309 return d->doing_export;
3313 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3314 bool includeall, string & result_file) const
3316 MarkAsExporting exporting(this);
3317 string backend_format;
3318 OutputParams runparams(¶ms().encoding());
3319 runparams.flavor = OutputParams::LATEX;
3320 runparams.linelen = lyxrc.plaintext_linelen;
3321 runparams.includeall = includeall;
3322 vector<string> backs = backends();
3323 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3324 // Get shortest path to format
3325 Graph::EdgePath path;
3326 for (vector<string>::const_iterator it = backs.begin();
3327 it != backs.end(); ++it) {
3328 Graph::EdgePath p = theConverters().getPath(*it, format);
3329 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3330 backend_format = *it;
3335 if (!put_in_tempdir) {
3336 // Only show this alert if this is an export to a non-temporary
3337 // file (not for previewing).
3338 Alert::error(_("Couldn't export file"), bformat(
3339 _("No information for exporting the format %1$s."),
3340 formats.prettyName(format)));
3344 runparams.flavor = theConverters().getFlavor(path);
3347 backend_format = format;
3348 // FIXME: Don't hardcode format names here, but use a flag
3349 if (backend_format == "pdflatex")
3350 runparams.flavor = OutputParams::PDFLATEX;
3353 string filename = latexName(false);
3354 filename = addName(temppath(), filename);
3355 filename = changeExtension(filename,
3356 formats.extension(backend_format));
3359 updateMacroInstances();
3361 // Plain text backend
3362 if (backend_format == "text") {
3363 runparams.flavor = OutputParams::TEXT;
3364 writePlaintextFile(*this, FileName(filename), runparams);
3367 else if (backend_format == "xhtml") {
3368 runparams.flavor = OutputParams::HTML;
3369 switch (params().html_math_output) {
3370 case BufferParams::MathML:
3371 runparams.math_flavor = OutputParams::MathAsMathML;
3373 case BufferParams::HTML:
3374 runparams.math_flavor = OutputParams::MathAsHTML;
3376 case BufferParams::Images:
3377 runparams.math_flavor = OutputParams::MathAsImages;
3379 case BufferParams::LaTeX:
3380 runparams.math_flavor = OutputParams::MathAsLaTeX;
3384 makeLyXHTMLFile(FileName(filename), runparams);
3385 } else if (backend_format == "lyx")
3386 writeFile(FileName(filename));
3388 else if (isDocBook()) {
3389 runparams.nice = !put_in_tempdir;
3390 makeDocBookFile(FileName(filename), runparams);
3393 else if (backend_format == format) {
3394 runparams.nice = true;
3395 if (!makeLaTeXFile(FileName(filename), string(), runparams))
3397 } else if (!lyxrc.tex_allows_spaces
3398 && contains(filePath(), ' ')) {
3399 Alert::error(_("File name error"),
3400 _("The directory path to the document cannot contain spaces."));
3403 runparams.nice = false;
3404 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
3408 string const error_type = (format == "program")
3409 ? "Build" : bufferFormat();
3410 ErrorList & error_list = d->errorLists[error_type];
3411 string const ext = formats.extension(format);
3412 FileName const tmp_result_file(changeExtension(filename, ext));
3413 bool const success = theConverters().convert(this, FileName(filename),
3414 tmp_result_file, FileName(absFileName()), backend_format, format,
3417 // Emit the signal to show the error list or copy it back to the
3418 // cloned Buffer so that it cab be emitted afterwards.
3419 if (format != backend_format) {
3420 if (d->cloned_buffer_) {
3421 d->cloned_buffer_->d->errorLists[error_type] =
3422 d->errorLists[error_type];
3425 // also to the children, in case of master-buffer-view
3426 std::vector<Buffer *> clist = getChildren();
3427 for (vector<Buffer *>::const_iterator cit = clist.begin();
3428 cit != clist.end(); ++cit) {
3429 if (d->cloned_buffer_) {
3430 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
3431 (*cit)->d->errorLists[error_type];
3433 (*cit)->errors(error_type, true);
3437 if (d->cloned_buffer_) {
3438 // Enable reverse dvi or pdf to work by copying back the texrow
3439 // object to the cloned buffer.
3440 // FIXME: There is a possibility of concurrent access to texrow
3441 // here from the main GUI thread that should be securized.
3442 d->cloned_buffer_->d->texrow = d->texrow;
3443 string const error_type = bufferFormat();
3444 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
3450 if (put_in_tempdir) {
3451 result_file = tmp_result_file.absFileName();
3455 result_file = changeExtension(d->exportFileName().absFileName(), ext);
3456 // We need to copy referenced files (e. g. included graphics
3457 // if format == "dvi") to the result dir.
3458 vector<ExportedFile> const files =
3459 runparams.exportdata->externalFiles(format);
3460 string const dest = onlyPath(result_file);
3461 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
3462 : force_overwrite == ALL_FILES;
3463 CopyStatus status = use_force ? FORCE : SUCCESS;
3465 vector<ExportedFile>::const_iterator it = files.begin();
3466 vector<ExportedFile>::const_iterator const en = files.end();
3467 for (; it != en && status != CANCEL; ++it) {
3468 string const fmt = formats.getFormatFromFile(it->sourceName);
3469 status = copyFile(fmt, it->sourceName,
3470 makeAbsPath(it->exportName, dest),
3471 it->exportName, status == FORCE);
3474 if (status == CANCEL) {
3475 message(_("Document export cancelled."));
3476 } else if (tmp_result_file.exists()) {
3477 // Finally copy the main file
3478 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
3479 : force_overwrite != NO_FILES;
3480 if (status == SUCCESS && use_force)
3482 status = copyFile(format, tmp_result_file,
3483 FileName(result_file), result_file,
3485 message(bformat(_("Document exported as %1$s "
3487 formats.prettyName(format),
3488 makeDisplayPath(result_file)));
3490 // This must be a dummy converter like fax (bug 1888)
3491 message(bformat(_("Document exported as %1$s"),
3492 formats.prettyName(format)));
3499 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3500 bool includeall) const
3503 // (1) export with all included children (omit \includeonly)
3504 if (includeall && !doExport(format, put_in_tempdir, true, result_file))
3506 // (2) export with included children only
3507 return doExport(format, put_in_tempdir, false, result_file);
3511 bool Buffer::preview(string const & format, bool includeall) const
3513 MarkAsExporting exporting(this);
3515 // (1) export with all included children (omit \includeonly)
3516 if (includeall && !doExport(format, true, true))
3518 // (2) export with included children only
3519 if (!doExport(format, true, false, result_file))
3521 return formats.view(*this, FileName(result_file), format);
3525 bool Buffer::isExportable(string const & format) const
3527 vector<string> backs = backends();
3528 for (vector<string>::const_iterator it = backs.begin();
3529 it != backs.end(); ++it)
3530 if (theConverters().isReachable(*it, format))
3536 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
3538 vector<string> const backs = backends();
3539 vector<Format const *> result =
3540 theConverters().getReachable(backs[0], only_viewable, true);
3541 for (vector<string>::const_iterator it = backs.begin() + 1;
3542 it != backs.end(); ++it) {
3543 vector<Format const *> r =
3544 theConverters().getReachable(*it, only_viewable, false);
3545 result.insert(result.end(), r.begin(), r.end());
3551 vector<string> Buffer::backends() const
3554 v.push_back(bufferFormat());
3555 // FIXME: Don't hardcode format names here, but use a flag
3556 if (v.back() == "latex")
3557 v.push_back("pdflatex");
3558 v.push_back("xhtml");
3559 v.push_back("text");
3565 bool Buffer::readFileHelper(FileName const & s)
3567 // File information about normal file
3569 docstring const file = makeDisplayPath(s.absFileName(), 50);
3570 docstring text = bformat(_("The specified document\n%1$s"
3571 "\ncould not be read."), file);
3572 Alert::error(_("Could not read document"), text);
3576 // Check if emergency save file exists and is newer.
3577 FileName const e(s.absFileName() + ".emergency");
3579 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
3580 docstring const file = makeDisplayPath(s.absFileName(), 20);
3581 docstring const text =
3582 bformat(_("An emergency save of the document "
3584 "Recover emergency save?"), file);
3585 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
3586 _("&Recover"), _("&Load Original"),
3590 // the file is not saved if we load the emergency file.
3595 if ((res = readFile(e)) == success)
3596 str = _("Document was successfully recovered.");
3598 str = _("Document was NOT successfully recovered.");
3599 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3600 makeDisplayPath(e.absFileName()));
3602 if (!Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3603 _("&Remove"), _("&Keep it"))) {
3606 Alert::warning(_("Emergency file deleted"),
3607 _("Do not forget to save your file now!"), true);
3612 if (!Alert::prompt(_("Delete emergency file?"),
3613 _("Remove emergency file now?"), 1, 1,
3614 _("&Remove"), _("&Keep it")))
3622 // Now check if autosave file is newer.
3623 FileName const a(onlyPath(s.absFileName()) + '#' + onlyFileName(s.absFileName()) + '#');
3625 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
3626 docstring const file = makeDisplayPath(s.absFileName(), 20);
3627 docstring const text =
3628 bformat(_("The backup of the document "
3629 "%1$s is newer.\n\nLoad the "
3630 "backup instead?"), file);
3631 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
3632 _("&Load backup"), _("Load &original"),
3636 // the file is not saved if we load the autosave file.
3640 // Here we delete the autosave
3651 bool Buffer::loadLyXFile(FileName const & s)
3653 // If the file is not readable, we try to
3654 // retrieve the file from version control.
3655 if (!s.isReadableFile()
3656 && !LyXVC::file_not_found_hook(s))
3659 if (s.isReadableFile()){
3660 // InsetInfo needs to know if file is under VCS
3661 lyxvc().file_found_hook(s);
3662 if (readFileHelper(s)) {
3663 d->read_only = !s.isWritable();
3671 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3673 TeXErrors::Errors::const_iterator cit = terr.begin();
3674 TeXErrors::Errors::const_iterator end = terr.end();
3676 for (; cit != end; ++cit) {
3679 int errorRow = cit->error_in_line;
3680 bool found = d->texrow.getIdFromRow(errorRow, id_start,
3686 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
3687 } while (found && id_start == id_end && pos_start == pos_end);
3689 errorList.push_back(ErrorItem(cit->error_desc,
3690 cit->error_text, id_start, pos_start, pos_end));
3695 void Buffer::setBuffersForInsets() const
3697 inset().setBuffer(const_cast<Buffer &>(*this));
3701 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
3703 // Use the master text class also for child documents
3704 Buffer const * const master = masterBuffer();
3705 DocumentClass const & textclass = master->params().documentClass();
3707 // do this only if we are the top-level Buffer
3708 if (scope != UpdateMaster || master == this)
3709 checkBibInfoCache();
3711 // keep the buffers to be children in this set. If the call from the
3712 // master comes back we can see which of them were actually seen (i.e.
3713 // via an InsetInclude). The remaining ones in the set need still be updated.
3714 static std::set<Buffer const *> bufToUpdate;
3715 if (scope == UpdateMaster) {
3716 // If this is a child document start with the master
3717 if (master != this) {
3718 bufToUpdate.insert(this);
3719 master->updateBuffer(UpdateMaster, utype);
3720 // Do this here in case the master has no gui associated with it. Then,
3721 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3722 if (!master->d->gui_)
3725 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3726 if (bufToUpdate.find(this) == bufToUpdate.end())
3730 // start over the counters in the master
3731 textclass.counters().reset();
3734 // update will be done below for this buffer
3735 bufToUpdate.erase(this);
3737 // update all caches
3738 clearReferenceCache();
3741 Buffer & cbuf = const_cast<Buffer &>(*this);
3743 LASSERT(!text().paragraphs().empty(), /**/);
3746 ParIterator parit = cbuf.par_iterator_begin();
3747 updateBuffer(parit, utype);
3750 // TocBackend update will be done later.
3753 cbuf.tocBackend().update();
3754 if (scope == UpdateMaster)
3755 cbuf.structureChanged();
3759 static depth_type getDepth(DocIterator const & it)
3761 depth_type depth = 0;
3762 for (size_t i = 0 ; i < it.depth() ; ++i)
3763 if (!it[i].inset().inMathed())
3764 depth += it[i].paragraph().getDepth() + 1;
3765 // remove 1 since the outer inset does not count
3769 static depth_type getItemDepth(ParIterator const & it)
3771 Paragraph const & par = *it;
3772 LabelType const labeltype = par.layout().labeltype;
3774 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3777 // this will hold the lowest depth encountered up to now.
3778 depth_type min_depth = getDepth(it);
3779 ParIterator prev_it = it;
3782 --prev_it.top().pit();
3784 // start of nested inset: go to outer par
3786 if (prev_it.empty()) {
3787 // start of document: nothing to do
3792 // We search for the first paragraph with same label
3793 // that is not more deeply nested.
3794 Paragraph & prev_par = *prev_it;
3795 depth_type const prev_depth = getDepth(prev_it);
3796 if (labeltype == prev_par.layout().labeltype) {
3797 if (prev_depth < min_depth)
3798 return prev_par.itemdepth + 1;
3799 if (prev_depth == min_depth)
3800 return prev_par.itemdepth;
3802 min_depth = min(min_depth, prev_depth);
3803 // small optimization: if we are at depth 0, we won't
3804 // find anything else
3805 if (prev_depth == 0)
3811 static bool needEnumCounterReset(ParIterator const & it)
3813 Paragraph const & par = *it;
3814 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3815 depth_type const cur_depth = par.getDepth();
3816 ParIterator prev_it = it;
3817 while (prev_it.pit()) {
3818 --prev_it.top().pit();
3819 Paragraph const & prev_par = *prev_it;
3820 if (prev_par.getDepth() <= cur_depth)
3821 return prev_par.layout().labeltype != LABEL_ENUMERATE;
3823 // start of nested inset: reset
3828 // set the label of a paragraph. This includes the counters.
3829 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
3831 BufferParams const & bp = owner_->masterBuffer()->params();
3832 DocumentClass const & textclass = bp.documentClass();
3833 Paragraph & par = it.paragraph();
3834 Layout const & layout = par.layout();
3835 Counters & counters = textclass.counters();
3837 if (par.params().startOfAppendix()) {
3838 // FIXME: only the counter corresponding to toplevel
3839 // sectioning should be reset
3841 counters.appendix(true);
3843 par.params().appendix(counters.appendix());
3845 // Compute the item depth of the paragraph
3846 par.itemdepth = getItemDepth(it);
3848 if (layout.margintype == MARGIN_MANUAL
3849 || layout.latextype == LATEX_BIB_ENVIRONMENT) {
3850 if (par.params().labelWidthString().empty())
3851 par.params().labelWidthString(par.expandLabel(layout, bp));
3853 par.params().labelWidthString(docstring());
3856 switch(layout.labeltype) {
3858 if (layout.toclevel <= bp.secnumdepth
3859 && (layout.latextype != LATEX_ENVIRONMENT
3860 || it.text()->isFirstInSequence(it.pit()))) {
3861 counters.step(layout.counter, utype);
3862 par.params().labelString(
3863 par.expandLabel(layout, bp));
3865 par.params().labelString(docstring());
3868 case LABEL_ITEMIZE: {
3869 // At some point of time we should do something more
3870 // clever here, like:
3871 // par.params().labelString(
3872 // bp.user_defined_bullet(par.itemdepth).getText());
3873 // for now, use a simple hardcoded label
3874 docstring itemlabel;
3875 switch (par.itemdepth) {
3877 itemlabel = char_type(0x2022);
3880 itemlabel = char_type(0x2013);
3883 itemlabel = char_type(0x2217);
3886 itemlabel = char_type(0x2219); // or 0x00b7
3889 par.params().labelString(itemlabel);
3893 case LABEL_ENUMERATE: {
3894 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
3896 switch (par.itemdepth) {
3905 enumcounter += "iv";
3908 // not a valid enumdepth...
3912 // Maybe we have to reset the enumeration counter.
3913 if (needEnumCounterReset(it))
3914 counters.reset(enumcounter);
3915 counters.step(enumcounter, utype);
3917 string const & lang = par.getParLanguage(bp)->code();
3918 par.params().labelString(counters.theCounter(enumcounter, lang));
3923 case LABEL_SENSITIVE: {
3924 string const & type = counters.current_float();
3925 docstring full_label;
3927 full_label = owner_->B_("Senseless!!! ");
3929 docstring name = owner_->B_(textclass.floats().getType(type).name());
3930 if (counters.hasCounter(from_utf8(type))) {
3931 string const & lang = par.getParLanguage(bp)->code();
3932 counters.step(from_utf8(type), utype);
3933 full_label = bformat(from_ascii("%1$s %2$s:"),
3935 counters.theCounter(from_utf8(type), lang));
3937 full_label = bformat(from_ascii("%1$s #:"), name);
3939 par.params().labelString(full_label);
3943 case LABEL_NO_LABEL:
3944 par.params().labelString(docstring());
3948 case LABEL_TOP_ENVIRONMENT:
3949 case LABEL_CENTERED_TOP_ENVIRONMENT:
3952 par.params().labelString(par.expandLabel(layout, bp));
3958 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
3960 LASSERT(parit.pit() == 0, /**/);
3962 // set the position of the text in the buffer to be able
3963 // to resolve macros in it. This has nothing to do with
3964 // labels, but by putting it here we avoid implementing
3965 // a whole bunch of traversal routines just for this call.
3966 parit.text()->setMacrocontextPosition(parit);
3968 depth_type maxdepth = 0;
3969 pit_type const lastpit = parit.lastpit();
3970 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
3971 // reduce depth if necessary
3972 parit->params().depth(min(parit->params().depth(), maxdepth));
3973 maxdepth = parit->getMaxDepthAfter();
3975 if (utype == OutputUpdate) {
3976 // track the active counters
3977 // we have to do this for the master buffer, since the local
3978 // buffer isn't tracking anything.
3979 masterBuffer()->params().documentClass().counters().
3980 setActiveLayout(parit->layout());
3983 // set the counter for this paragraph
3984 d->setLabel(parit, utype);
3987 InsetList::const_iterator iit = parit->insetList().begin();
3988 InsetList::const_iterator end = parit->insetList().end();
3989 for (; iit != end; ++iit) {
3990 parit.pos() = iit->pos;
3991 iit->inset->updateBuffer(parit, utype);
3997 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
3998 WordLangTuple & word_lang, docstring_list & suggestions) const
4002 suggestions.clear();
4003 word_lang = WordLangTuple();
4004 // OK, we start from here.
4005 DocIterator const end = doc_iterator_end(this);
4006 for (; from != end; from.forwardPos()) {
4007 // We are only interested in text so remove the math CursorSlice.
4008 while (from.inMathed()) {
4012 // If from is at the end of the document (which is possible
4013 // when leaving the mathed) LyX will crash later.
4017 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4018 if (SpellChecker::misspelled(res)) {
4023 // Do not increase progress when from == to, otherwise the word
4024 // count will be wrong.
4034 bool Buffer::reload()
4038 removeAutosaveFile();
4039 // e.g., read-only status could have changed due to version control
4040 d->filename.refresh();
4041 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4043 bool const success = loadLyXFile(d->filename);
4049 message(bformat(_("Document %1$s reloaded."), disp_fn));
4051 message(bformat(_("Could not reload document %1$s."), disp_fn));
4054 thePreviews().removeLoader(*this);
4055 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
4056 thePreviews().generateBufferPreviews(*this);
4062 // FIXME We could do better here, but it is complicated. What would be
4063 // nice is to offer either (a) to save the child buffer to an appropriate
4064 // location, so that it would "move with the master", or else (b) to update
4065 // the InsetInclude so that it pointed to the same file. But (a) is a bit
4066 // complicated, because the code for this lives in GuiView.
4067 void Buffer::checkChildBuffers()
4069 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4070 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4071 for (; it != en; ++it) {
4072 DocIterator dit = it->second;
4073 Buffer * cbuf = const_cast<Buffer *>(it->first);
4074 if (!cbuf || !theBufferList().isLoaded(cbuf))
4076 Inset * inset = dit.nextInset();
4077 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4078 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4079 docstring const & incfile = inset_inc->getParam("filename");
4080 string oldloc = cbuf->absFileName();
4081 string newloc = makeAbsPath(to_utf8(incfile),
4082 onlyPath(absFileName())).absFileName();
4083 if (oldloc == newloc)
4085 // the location of the child file is incorrect.
4086 Alert::warning(_("Included File Invalid"),
4087 bformat(_("Saving this document to a new location has made the file:\n"
4089 "inaccessible. You will need to update the included filename."),
4090 from_utf8(oldloc)));
4092 inset_inc->setChildBuffer(0);
4094 // invalidate cache of children
4095 d->children_positions.clear();
4096 d->position_to_children.clear();