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 /// Cache of timestamps of .bib files
260 map<FileName, time_t> bibfile_status_;
262 mutable RefCache ref_cache_;
264 /// our Text that should be wrapped in an InsetText
267 /// This is here to force the test to be done whenever parent_buffer
269 Buffer const * parent() const {
270 // if parent_buffer is not loaded, then it has been unloaded,
271 // which means that parent_buffer is an invalid pointer. So we
272 // set it to null in that case.
273 // however, the BufferList doesn't know about cloned buffers, so
274 // they will always be regarded as unloaded. in that case, we hope
276 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
278 return parent_buffer;
281 void setParent(Buffer const * pb) {
283 && parent_buffer && pb && parent_buffer != pb)
284 LYXERR0("Warning: a buffer should not have two parents!");
288 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
289 /// This one is useful for preview detached in a thread.
290 Buffer const * cloned_buffer_;
291 /// are we in the process of exporting this buffer?
292 mutable bool doing_export;
295 /// So we can force access via the accessors.
296 mutable Buffer const * parent_buffer;
301 /// Creates the per buffer temporary directory
302 static FileName createBufferTmpDir()
305 // We are in our own directory. Why bother to mangle name?
306 // In fact I wrote this code to circumvent a problematic behaviour
307 // (bug?) of EMX mkstemp().
308 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
309 convert<string>(count++));
311 if (!tmpfl.createDirectory(0777)) {
312 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
313 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
314 from_utf8(tmpfl.absFileName())));
320 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
321 Buffer const * cloned_buffer)
322 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
323 read_only(readonly_), filename(file), file_fully_loaded(false),
324 toc_backend(owner), macro_lock(false), timestamp_(0),
325 checksum_(0), wa_(0), gui_(0), undo_(*owner), bibinfo_cache_valid_(false),
326 cloned_buffer_(cloned_buffer), doing_export(false), parent_buffer(0)
328 if (!cloned_buffer_) {
329 temppath = createBufferTmpDir();
330 lyxvc.setBuffer(owner_);
332 wa_ = new frontend::WorkAreaManager;
335 temppath = cloned_buffer_->d->temppath;
336 file_fully_loaded = true;
337 params = cloned_buffer_->d->params;
338 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
339 bibinfo_ = cloned_buffer_->d->bibinfo_;
340 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
341 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
345 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
346 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
348 LYXERR(Debug::INFO, "Buffer::Buffer()");
350 d->inset = new InsetText(*cloned_buffer->d->inset);
351 d->inset->setBuffer(*this);
352 // FIXME: optimize this loop somewhat, maybe by creating a new
353 // general recursive Inset::setId().
354 DocIterator it = doc_iterator_begin(this);
355 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
356 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
357 it.paragraph().setId(cloned_it.paragraph().id());
359 d->inset = new InsetText(this);
360 d->inset->setAutoBreakRows(true);
361 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
367 LYXERR(Debug::INFO, "Buffer::~Buffer()");
368 // here the buffer should take care that it is
369 // saved properly, before it goes into the void.
371 // GuiView already destroyed
375 // No need to do additional cleanups for internal buffer.
380 // loop over children
381 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
382 Impl::BufferPositionMap::iterator end = d->children_positions.end();
383 for (; it != end; ++it) {
384 Buffer * child = const_cast<Buffer *>(it->first);
385 if (d->cloned_buffer_)
387 // The child buffer might have been closed already.
388 else if (theBufferList().isLoaded(child))
389 theBufferList().releaseChild(this, child);
393 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
394 msg += emergencyWrite();
395 Alert::warning(_("Attempting to close changed document!"), msg);
398 // clear references to children in macro tables
399 d->children_positions.clear();
400 d->position_to_children.clear();
402 if (!d->cloned_buffer_ && !d->temppath.destroyDirectory()) {
403 Alert::warning(_("Could not remove temporary directory"),
404 bformat(_("Could not remove the temporary directory %1$s"),
405 from_utf8(d->temppath.absFileName())));
408 // Remove any previewed LaTeX snippets associated with this buffer.
410 thePreviews().removeLoader(*this);
416 Buffer * Buffer::clone() const
418 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
419 buffer_clone->d->macro_lock = true;
420 buffer_clone->d->children_positions.clear();
421 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
422 // math macro caches need to be rethought and simplified.
423 // I am not sure wether we should handle Buffer cloning here or in BufferList.
424 // Right now BufferList knows nothing about buffer clones.
425 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
426 Impl::BufferPositionMap::iterator end = d->children_positions.end();
427 for (; it != end; ++it) {
428 DocIterator dit = it->second.clone(buffer_clone);
429 dit.setBuffer(buffer_clone);
430 Buffer * child = const_cast<Buffer *>(it->first);
431 Buffer * child_clone = child->clone();
432 Inset * inset = dit.nextInset();
433 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
434 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
435 inset_inc->setChildBuffer(child_clone);
436 child_clone->d->setParent(buffer_clone);
437 buffer_clone->setChild(dit, child_clone);
439 buffer_clone->d->macro_lock = false;
444 bool Buffer::isClone() const
446 return d->cloned_buffer_;
450 void Buffer::changed(bool update_metrics) const
453 d->wa_->redrawAll(update_metrics);
457 frontend::WorkAreaManager & Buffer::workAreaManager() const
459 LASSERT(d->wa_, /**/);
464 Text & Buffer::text() const
466 return d->inset->text();
470 Inset & Buffer::inset() const
476 BufferParams & Buffer::params()
482 BufferParams const & Buffer::params() const
488 ParagraphList & Buffer::paragraphs()
490 return text().paragraphs();
494 ParagraphList const & Buffer::paragraphs() const
496 return text().paragraphs();
500 LyXVC & Buffer::lyxvc()
506 LyXVC const & Buffer::lyxvc() const
512 string const Buffer::temppath() const
514 return d->temppath.absFileName();
518 TexRow & Buffer::texrow()
524 TexRow const & Buffer::texrow() const
530 TocBackend & Buffer::tocBackend() const
532 return d->toc_backend;
536 Undo & Buffer::undo()
542 void Buffer::setChild(DocIterator const & dit, Buffer * child)
544 d->children_positions[child] = dit;
548 string Buffer::latexName(bool const no_path) const
550 FileName latex_name =
551 makeLatexName(d->exportFileName());
552 return no_path ? latex_name.onlyFileName()
553 : latex_name.absFileName();
557 FileName Buffer::Impl::exportFileName() const
559 docstring const branch_suffix =
560 params.branchlist().getFileNameSuffix();
561 if (branch_suffix.empty())
564 string const name = filename.onlyFileNameWithoutExt()
565 + to_utf8(branch_suffix);
566 FileName res(filename.onlyPath().absFileName() + "/" + name);
567 res.changeExtension(filename.extension());
573 string Buffer::logName(LogType * type) const
575 string const filename = latexName(false);
577 if (filename.empty()) {
583 string const path = temppath();
585 FileName const fname(addName(temppath(),
586 onlyFileName(changeExtension(filename,
589 // FIXME: how do we know this is the name of the build log?
590 FileName const bname(
591 addName(path, onlyFileName(
592 changeExtension(filename,
593 formats.extension(bufferFormat()) + ".out"))));
595 // Also consider the master buffer log file
596 FileName masterfname = fname;
598 if (masterBuffer() != this) {
599 string const mlogfile = masterBuffer()->logName(&mtype);
600 masterfname = FileName(mlogfile);
603 // If no Latex log or Build log is newer, show Build log
604 if (bname.exists() &&
605 ((!fname.exists() && !masterfname.exists())
606 || (fname.lastModified() < bname.lastModified()
607 && masterfname.lastModified() < bname.lastModified()))) {
608 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
611 return bname.absFileName();
612 // If we have a newer master file log or only a master log, show this
613 } else if (fname != masterfname
614 && (!fname.exists() && (masterfname.exists()
615 || fname.lastModified() < masterfname.lastModified()))) {
616 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
619 return masterfname.absFileName();
621 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
624 return fname.absFileName();
628 void Buffer::setReadonly(bool const flag)
630 if (d->read_only != flag) {
637 void Buffer::setFileName(string const & newfile)
639 d->filename = makeAbsPath(newfile);
640 setReadonly(d->filename.isReadOnly());
645 int Buffer::readHeader(Lexer & lex)
647 int unknown_tokens = 0;
649 int begin_header_line = -1;
651 // Initialize parameters that may be/go lacking in header:
652 params().branchlist().clear();
653 params().preamble.erase();
654 params().options.erase();
655 params().master.erase();
656 params().float_placement.erase();
657 params().paperwidth.erase();
658 params().paperheight.erase();
659 params().leftmargin.erase();
660 params().rightmargin.erase();
661 params().topmargin.erase();
662 params().bottommargin.erase();
663 params().headheight.erase();
664 params().headsep.erase();
665 params().footskip.erase();
666 params().columnsep.erase();
667 params().fontsCJK.erase();
668 params().listings_params.clear();
669 params().clearLayoutModules();
670 params().clearRemovedModules();
671 params().clearIncludedChildren();
672 params().pdfoptions().clear();
673 params().indiceslist().clear();
674 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
675 params().isbackgroundcolor = false;
676 params().fontcolor = lyx::rgbFromHexName("#000000");
677 params().isfontcolor = false;
678 params().notefontcolor = lyx::rgbFromHexName("#cccccc");
679 params().boxbgcolor = lyx::rgbFromHexName("#ff0000");
680 params().html_latex_start.clear();
681 params().html_latex_end.clear();
682 params().html_math_img_scale = 1.0;
683 params().output_sync_macro.erase();
685 for (int i = 0; i < 4; ++i) {
686 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
687 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
690 ErrorList & errorList = d->errorLists["Parse"];
699 if (token == "\\end_header")
703 if (token == "\\begin_header") {
704 begin_header_line = line;
708 LYXERR(Debug::PARSER, "Handling document header token: `"
711 string unknown = params().readToken(lex, token, d->filename.onlyPath());
712 if (!unknown.empty()) {
713 if (unknown[0] != '\\' && token == "\\textclass") {
714 Alert::warning(_("Unknown document class"),
715 bformat(_("Using the default document class, because the "
716 "class %1$s is unknown."), from_utf8(unknown)));
719 docstring const s = bformat(_("Unknown token: "
723 errorList.push_back(ErrorItem(_("Document header error"),
728 if (begin_header_line) {
729 docstring const s = _("\\begin_header is missing");
730 errorList.push_back(ErrorItem(_("Document header error"),
734 params().makeDocumentClass();
736 return unknown_tokens;
741 // changed to be public and have one parameter
742 // Returns true if "\end_document" is not read (Asger)
743 bool Buffer::readDocument(Lexer & lex)
745 ErrorList & errorList = d->errorLists["Parse"];
748 if (!lex.checkFor("\\begin_document")) {
749 docstring const s = _("\\begin_document is missing");
750 errorList.push_back(ErrorItem(_("Document header error"),
754 // we are reading in a brand new document
755 LASSERT(paragraphs().empty(), /**/);
759 if (params().outputChanges) {
760 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
761 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
762 LaTeXFeatures::isAvailable("xcolor");
764 if (!dvipost && !xcolorulem) {
765 Alert::warning(_("Changes not shown in LaTeX output"),
766 _("Changes will not be highlighted in LaTeX output, "
767 "because neither dvipost nor xcolor/ulem are installed.\n"
768 "Please install these packages or redefine "
769 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
770 } else if (!xcolorulem) {
771 Alert::warning(_("Changes not shown in LaTeX output"),
772 _("Changes will not be highlighted in LaTeX output "
773 "when using pdflatex, because xcolor and ulem are not installed.\n"
774 "Please install both packages or redefine "
775 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
779 if (!params().master.empty()) {
780 FileName const master_file = makeAbsPath(params().master,
781 onlyPath(absFileName()));
782 if (isLyXFileName(master_file.absFileName())) {
784 checkAndLoadLyXFile(master_file, true);
786 // necessary e.g. after a reload
787 // to re-register the child (bug 5873)
788 // FIXME: clean up updateMacros (here, only
789 // child registering is needed).
790 master->updateMacros();
791 // set master as master buffer, but only
792 // if we are a real child
793 if (master->isChild(this))
795 // if the master is not fully loaded
796 // it is probably just loading this
797 // child. No warning needed then.
798 else if (master->isFullyLoaded())
799 LYXERR0("The master '"
801 << "' assigned to this document ("
803 << ") does not include "
804 "this document. Ignoring the master assignment.");
809 // assure we have a default index
810 params().indiceslist().addDefault(B_("Index"));
813 bool const res = text().read(lex, errorList, d->inset);
817 updateMacroInstances();
822 bool Buffer::readString(string const & s)
824 params().compressed = false;
826 // remove dummy empty par
827 paragraphs().clear();
831 FileName const name = FileName::tempName("Buffer_readString");
832 switch (readFile(lex, name, true)) {
836 // We need to call lyx2lyx, so write the input to a file
837 ofstream os(name.toFilesystemEncoding().c_str());
840 return readFile(name);
850 bool Buffer::readFile(FileName const & filename)
852 FileName fname(filename);
854 params().compressed = fname.isZippedFile();
856 // remove dummy empty par
857 paragraphs().clear();
860 if (readFile(lex, fname) != success)
867 bool Buffer::isFullyLoaded() const
869 return d->file_fully_loaded;
873 void Buffer::setFullyLoaded(bool value)
875 d->file_fully_loaded = value;
879 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
882 LASSERT(!filename.empty(), /**/);
884 // the first (non-comment) token _must_ be...
885 if (!lex.checkFor("\\lyxformat")) {
886 Alert::error(_("Document format failure"),
887 bformat(_("%1$s is not a readable LyX document."),
888 from_utf8(filename.absFileName())));
894 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
895 // if present remove ".," from string.
896 size_t dot = tmp_format.find_first_of(".,");
897 //lyxerr << " dot found at " << dot << endl;
898 if (dot != string::npos)
899 tmp_format.erase(dot, 1);
900 int const file_format = convert<int>(tmp_format);
901 //lyxerr << "format: " << file_format << endl;
903 // save timestamp and checksum of the original disk file, making sure
904 // to not overwrite them with those of the file created in the tempdir
905 // when it has to be converted to the current format.
907 // Save the timestamp and checksum of disk file. If filename is an
908 // emergency file, save the timestamp and checksum of the original lyx file
909 // because isExternallyModified will check for this file. (BUG4193)
910 string diskfile = filename.absFileName();
911 if (suffixIs(diskfile, ".emergency"))
912 diskfile = diskfile.substr(0, diskfile.size() - 10);
913 saveCheckSum(FileName(diskfile));
916 if (file_format != LYX_FORMAT) {
919 // lyx2lyx would fail
922 FileName const tmpfile = FileName::tempName("Buffer_readFile");
923 if (tmpfile.empty()) {
924 Alert::error(_("Conversion failed"),
925 bformat(_("%1$s is from a different"
926 " version of LyX, but a temporary"
927 " file for converting it could"
929 from_utf8(filename.absFileName())));
932 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
933 if (lyx2lyx.empty()) {
934 Alert::error(_("Conversion script not found"),
935 bformat(_("%1$s is from a different"
936 " version of LyX, but the"
937 " conversion script lyx2lyx"
938 " could not be found."),
939 from_utf8(filename.absFileName())));
942 ostringstream command;
943 command << os::python()
944 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
945 << " -t " << convert<string>(LYX_FORMAT)
946 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
947 << ' ' << quoteName(filename.toSafeFilesystemEncoding());
948 string const command_str = command.str();
950 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
952 cmd_ret const ret = runCommand(command_str);
953 if (ret.first != 0) {
954 if (file_format < LYX_FORMAT)
955 Alert::error(_("Conversion script failed"),
956 bformat(_("%1$s is from an older version"
957 " of LyX, but the lyx2lyx script"
958 " failed to convert it."),
959 from_utf8(filename.absFileName())));
961 Alert::error(_("Conversion script failed"),
962 bformat(_("%1$s is from a newer version"
963 " of LyX and cannot be converted by the"
965 from_utf8(filename.absFileName())));
968 bool const ret = readFile(tmpfile);
969 // Do stuff with tmpfile name and buffer name here.
970 return ret ? success : failure;
975 if (readDocument(lex)) {
976 Alert::error(_("Document format failure"),
977 bformat(_("%1$s ended unexpectedly, which means"
978 " that it is probably corrupted."),
979 from_utf8(filename.absFileName())));
983 d->file_fully_loaded = true;
988 // Should probably be moved to somewhere else: BufferView? GuiView?
989 bool Buffer::save() const
991 // ask if the disk file has been externally modified (use checksum method)
992 if (fileName().exists() && isExternallyModified(checksum_method)) {
993 docstring const file = makeDisplayPath(absFileName(), 20);
994 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
995 "you want to overwrite this file?"), file);
996 int const ret = Alert::prompt(_("Overwrite modified file?"),
997 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1002 // We don't need autosaves in the immediate future. (Asger)
1003 resetAutosaveTimers();
1005 FileName backupName;
1006 bool madeBackup = false;
1008 // make a backup if the file already exists
1009 if (lyxrc.make_backup && fileName().exists()) {
1010 backupName = FileName(absFileName() + '~');
1011 if (!lyxrc.backupdir_path.empty()) {
1012 string const mangledName =
1013 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1014 backupName = FileName(addName(lyxrc.backupdir_path,
1017 // do not copy because of #6587
1018 if (fileName().moveTo(backupName)) {
1021 Alert::error(_("Backup failure"),
1022 bformat(_("Cannot create backup file %1$s.\n"
1023 "Please check whether the directory exists and is writeable."),
1024 from_utf8(backupName.absFileName())));
1025 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1029 if (writeFile(d->filename)) {
1033 // Saving failed, so backup is not backup
1035 backupName.moveTo(d->filename);
1041 bool Buffer::writeFile(FileName const & fname) const
1043 if (d->read_only && fname == d->filename)
1046 bool retval = false;
1048 docstring const str = bformat(_("Saving document %1$s..."),
1049 makeDisplayPath(fname.absFileName()));
1052 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1054 if (params().compressed) {
1055 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1056 retval = ofs && write(ofs);
1058 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1059 retval = ofs && write(ofs);
1063 message(str + _(" could not write file!"));
1068 // removeAutosaveFile();
1070 saveCheckSum(d->filename);
1071 message(str + _(" done."));
1077 docstring Buffer::emergencyWrite()
1079 // No need to save if the buffer has not changed.
1083 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1085 docstring user_message = bformat(
1086 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1088 // We try to save three places:
1089 // 1) Same place as document. Unless it is an unnamed doc.
1091 string s = absFileName();
1094 if (writeFile(FileName(s))) {
1096 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1097 return user_message;
1099 user_message += _(" Save failed! Trying again...\n");
1103 // 2) In HOME directory.
1104 string s = addName(package().home_dir().absFileName(), absFileName());
1106 lyxerr << ' ' << s << endl;
1107 if (writeFile(FileName(s))) {
1109 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1110 return user_message;
1113 user_message += _(" Save failed! Trying yet again...\n");
1115 // 3) In "/tmp" directory.
1116 // MakeAbsPath to prepend the current
1117 // drive letter on OS/2
1118 s = addName(package().temp_dir().absFileName(), absFileName());
1120 lyxerr << ' ' << s << endl;
1121 if (writeFile(FileName(s))) {
1123 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1124 return user_message;
1127 user_message += _(" Save failed! Bummer. Document is lost.");
1130 return user_message;
1134 bool Buffer::write(ostream & ofs) const
1137 // Use the standard "C" locale for file output.
1138 ofs.imbue(locale::classic());
1141 // The top of the file should not be written by params().
1143 // write out a comment in the top of the file
1144 ofs << "#LyX " << lyx_version
1145 << " created this file. For more info see http://www.lyx.org/\n"
1146 << "\\lyxformat " << LYX_FORMAT << "\n"
1147 << "\\begin_document\n";
1149 /// For each author, set 'used' to true if there is a change
1150 /// by this author in the document; otherwise set it to 'false'.
1151 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1152 AuthorList::Authors::const_iterator a_end = params().authors().end();
1153 for (; a_it != a_end; ++a_it)
1154 a_it->setUsed(false);
1156 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1157 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1158 for ( ; it != end; ++it)
1159 it->checkAuthors(params().authors());
1161 // now write out the buffer parameters.
1162 ofs << "\\begin_header\n";
1163 params().writeFile(ofs);
1164 ofs << "\\end_header\n";
1167 ofs << "\n\\begin_body\n";
1169 ofs << "\n\\end_body\n";
1171 // Write marker that shows file is complete
1172 ofs << "\\end_document" << endl;
1174 // Shouldn't really be needed....
1177 // how to check if close went ok?
1178 // Following is an attempt... (BE 20001011)
1180 // good() returns false if any error occured, including some
1181 // formatting error.
1182 // bad() returns true if something bad happened in the buffer,
1183 // which should include file system full errors.
1188 lyxerr << "File was not closed properly." << endl;
1195 bool Buffer::makeLaTeXFile(FileName const & fname,
1196 string const & original_path,
1197 OutputParams const & runparams_in,
1198 bool output_preamble, bool output_body) const
1200 OutputParams runparams = runparams_in;
1201 if (params().useXetex)
1202 runparams.flavor = OutputParams::XETEX;
1204 string const encoding = runparams.encoding->iconvName();
1205 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1208 try { ofs.reset(encoding); }
1209 catch (iconv_codecvt_facet_exception & e) {
1210 lyxerr << "Caught iconv exception: " << e.what() << endl;
1211 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1212 "verify that the support software for your encoding (%1$s) is "
1213 "properly installed"), from_ascii(encoding)));
1216 if (!openFileWrite(ofs, fname))
1219 //TexStream ts(ofs.rdbuf(), &texrow());
1220 ErrorList & errorList = d->errorLists["Export"];
1222 bool failed_export = false;
1225 writeLaTeXSource(ofs, original_path,
1226 runparams, output_preamble, output_body);
1228 catch (EncodingException & e) {
1229 odocstringstream ods;
1230 ods.put(e.failed_char);
1232 oss << "0x" << hex << e.failed_char << dec;
1233 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1234 " (code point %2$s)"),
1235 ods.str(), from_utf8(oss.str()));
1236 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1237 "representable in the chosen encoding.\n"
1238 "Changing the document encoding to utf8 could help."),
1239 e.par_id, e.pos, e.pos + 1));
1240 failed_export = true;
1242 catch (iconv_codecvt_facet_exception & e) {
1243 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1244 _(e.what()), -1, 0, 0));
1245 failed_export = true;
1247 catch (exception const & e) {
1248 errorList.push_back(ErrorItem(_("conversion failed"),
1249 _(e.what()), -1, 0, 0));
1250 failed_export = true;
1253 lyxerr << "Caught some really weird exception..." << endl;
1259 failed_export = true;
1260 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1264 return !failed_export;
1268 void Buffer::writeLaTeXSource(odocstream & os,
1269 string const & original_path,
1270 OutputParams const & runparams_in,
1271 bool const output_preamble, bool const output_body) const
1273 // The child documents, if any, shall be already loaded at this point.
1275 OutputParams runparams = runparams_in;
1277 // Classify the unicode characters appearing in math insets
1278 Encodings::initUnicodeMath(*this);
1280 // validate the buffer.
1281 LYXERR(Debug::LATEX, " Validating buffer...");
1282 LaTeXFeatures features(*this, params(), runparams);
1284 LYXERR(Debug::LATEX, " Buffer validation done.");
1286 // The starting paragraph of the coming rows is the
1287 // first paragraph of the document. (Asger)
1288 if (output_preamble && runparams.nice) {
1289 os << "%% LyX " << lyx_version << " created this file. "
1290 "For more info, see http://www.lyx.org/.\n"
1291 "%% Do not edit unless you really know what "
1293 d->texrow.newline();
1294 d->texrow.newline();
1296 LYXERR(Debug::INFO, "lyx document header finished");
1298 // Don't move this behind the parent_buffer=0 code below,
1299 // because then the macros will not get the right "redefinition"
1300 // flag as they don't see the parent macros which are output before.
1303 // fold macros if possible, still with parent buffer as the
1304 // macros will be put in the prefix anyway.
1305 updateMacroInstances();
1307 // There are a few differences between nice LaTeX and usual files:
1308 // usual is \batchmode and has a
1309 // special input@path to allow the including of figures
1310 // with either \input or \includegraphics (what figinsets do).
1311 // input@path is set when the actual parameter
1312 // original_path is set. This is done for usual tex-file, but not
1313 // for nice-latex-file. (Matthias 250696)
1314 // Note that input@path is only needed for something the user does
1315 // in the preamble, included .tex files or ERT, files included by
1316 // LyX work without it.
1317 if (output_preamble) {
1318 if (!runparams.nice) {
1319 // code for usual, NOT nice-latex-file
1320 os << "\\batchmode\n"; // changed
1321 // from \nonstopmode
1322 d->texrow.newline();
1324 if (!original_path.empty()) {
1326 // We don't know the encoding of inputpath
1327 docstring const inputpath = from_utf8(support::latex_path(original_path));
1328 docstring uncodable_glyphs;
1329 Encoding const * const enc = runparams.encoding;
1331 for (size_t n = 0; n < inputpath.size(); ++n) {
1332 docstring const glyph =
1333 docstring(1, inputpath[n]);
1334 if (enc->latexChar(inputpath[n], true) != glyph) {
1335 LYXERR0("Uncodable character '"
1337 << "' in input path!");
1338 uncodable_glyphs += glyph;
1343 // warn user if we found uncodable glyphs.
1344 if (!uncodable_glyphs.empty()) {
1345 frontend::Alert::warning(_("Uncodable character in file path"),
1346 support::bformat(_("The path of your document\n"
1348 "contains glyphs that are unknown in the\n"
1349 "current document encoding (namely %2$s).\n"
1350 "This will likely result in incomplete output.\n\n"
1351 "Choose an appropriate document encoding (such as utf8)\n"
1352 "or change the file path name."), inputpath, uncodable_glyphs));
1354 os << "\\makeatletter\n"
1355 << "\\def\\input@path{{"
1356 << inputpath << "/}}\n"
1357 << "\\makeatother\n";
1358 d->texrow.newline();
1359 d->texrow.newline();
1360 d->texrow.newline();
1364 // get parent macros (if this buffer has a parent) which will be
1365 // written at the document begin further down.
1366 MacroSet parentMacros;
1367 listParentMacros(parentMacros, features);
1369 // Write the preamble
1370 runparams.use_babel = params().writeLaTeX(os, features,
1372 d->filename.onlyPath());
1374 runparams.use_japanese = features.isRequired("japanese");
1380 os << "\\begin{document}\n";
1381 d->texrow.newline();
1383 // output the parent macros
1384 MacroSet::iterator it = parentMacros.begin();
1385 MacroSet::iterator end = parentMacros.end();
1386 for (; it != end; ++it) {
1387 int num_lines = (*it)->write(os, true);
1388 d->texrow.newlines(num_lines);
1391 } // output_preamble
1393 d->texrow.start(paragraphs().begin()->id(), 0);
1395 LYXERR(Debug::INFO, "preamble finished, now the body.");
1397 // if we are doing a real file with body, even if this is the
1398 // child of some other buffer, let's cut the link here.
1399 // This happens for example if only a child document is printed.
1400 Buffer const * save_parent = 0;
1401 if (output_preamble) {
1402 save_parent = d->parent();
1407 latexParagraphs(*this, text(), os, d->texrow, runparams);
1409 // Restore the parenthood if needed
1410 if (output_preamble)
1411 d->setParent(save_parent);
1413 // add this just in case after all the paragraphs
1415 d->texrow.newline();
1417 if (output_preamble) {
1418 os << "\\end{document}\n";
1419 d->texrow.newline();
1420 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1422 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1424 runparams_in.encoding = runparams.encoding;
1426 // Just to be sure. (Asger)
1427 d->texrow.newline();
1429 //for (int i = 0; i<d->texrow.rows(); i++) {
1431 // if (d->texrow.getIdFromRow(i+1,id,pos) && id>0)
1432 // lyxerr << i+1 << ":" << id << ":" << getParFromID(id).paragraph().asString()<<"\n";
1435 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1436 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1440 bool Buffer::isLatex() const
1442 return params().documentClass().outputType() == LATEX;
1446 bool Buffer::isLiterate() const
1448 return params().documentClass().outputType() == LITERATE;
1452 bool Buffer::isDocBook() const
1454 return params().documentClass().outputType() == DOCBOOK;
1458 void Buffer::makeDocBookFile(FileName const & fname,
1459 OutputParams const & runparams,
1460 bool const body_only) const
1462 LYXERR(Debug::LATEX, "makeDocBookFile...");
1465 if (!openFileWrite(ofs, fname))
1468 writeDocBookSource(ofs, fname.absFileName(), runparams, body_only);
1472 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1476 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1477 OutputParams const & runparams,
1478 bool const only_body) const
1480 LaTeXFeatures features(*this, params(), runparams);
1485 DocumentClass const & tclass = params().documentClass();
1486 string const top_element = tclass.latexname();
1489 if (runparams.flavor == OutputParams::XML)
1490 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1493 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1496 if (! tclass.class_header().empty())
1497 os << from_ascii(tclass.class_header());
1498 else if (runparams.flavor == OutputParams::XML)
1499 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1500 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1502 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1504 docstring preamble = from_utf8(params().preamble);
1505 if (runparams.flavor != OutputParams::XML ) {
1506 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1507 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1508 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1509 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1512 string const name = runparams.nice
1513 ? changeExtension(absFileName(), ".sgml") : fname;
1514 preamble += features.getIncludedFiles(name);
1515 preamble += features.getLyXSGMLEntities();
1517 if (!preamble.empty()) {
1518 os << "\n [ " << preamble << " ]";
1523 string top = top_element;
1525 if (runparams.flavor == OutputParams::XML)
1526 top += params().language->code();
1528 top += params().language->code().substr(0, 2);
1531 if (!params().options.empty()) {
1533 top += params().options;
1536 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1537 << " file was created by LyX " << lyx_version
1538 << "\n See http://www.lyx.org/ for more information -->\n";
1540 params().documentClass().counters().reset();
1544 sgml::openTag(os, top);
1546 docbookParagraphs(text(), *this, os, runparams);
1547 sgml::closeTag(os, top_element);
1551 void Buffer::makeLyXHTMLFile(FileName const & fname,
1552 OutputParams const & runparams,
1553 bool const body_only) const
1555 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1558 if (!openFileWrite(ofs, fname))
1561 writeLyXHTMLSource(ofs, runparams, body_only);
1565 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1569 void Buffer::writeLyXHTMLSource(odocstream & os,
1570 OutputParams const & runparams,
1571 bool const only_body) const
1573 LaTeXFeatures features(*this, params(), runparams);
1575 updateBuffer(UpdateMaster, OutputUpdate);
1576 checkBibInfoCache();
1577 d->bibinfo_.makeCitationLabels(*this);
1579 updateMacroInstances();
1582 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1583 << "<!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"
1584 // FIXME Language should be set properly.
1585 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
1587 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
1588 // FIXME Presumably need to set this right
1589 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1591 docstring const & doctitle = features.htmlTitle();
1593 << (doctitle.empty() ? from_ascii("LyX Document") : doctitle)
1596 os << "\n<!-- Text Class Preamble -->\n"
1597 << features.getTClassHTMLPreamble()
1598 << "\n<!-- Premable Snippets -->\n"
1599 << from_utf8(features.getPreambleSnippets());
1601 os << "\n<!-- Layout-provided Styles -->\n";
1602 docstring const styleinfo = features.getTClassHTMLStyles();
1603 if (!styleinfo.empty()) {
1604 os << "<style type='text/css'>\n"
1608 os << "</head>\n<body>\n";
1612 params().documentClass().counters().reset();
1613 xhtmlParagraphs(text(), *this, xs, runparams);
1615 os << "</body>\n</html>\n";
1619 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1620 // Other flags: -wall -v0 -x
1621 int Buffer::runChktex()
1625 // get LaTeX-Filename
1626 FileName const path(temppath());
1627 string const name = addName(path.absFileName(), latexName());
1628 string const org_path = filePath();
1630 PathChanger p(path); // path to LaTeX file
1631 message(_("Running chktex..."));
1633 // Generate the LaTeX file if neccessary
1634 OutputParams runparams(¶ms().encoding());
1635 runparams.flavor = OutputParams::LATEX;
1636 runparams.nice = false;
1637 runparams.linelen = lyxrc.plaintext_linelen;
1638 makeLaTeXFile(FileName(name), org_path, runparams);
1641 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
1642 int const res = chktex.run(terr); // run chktex
1645 Alert::error(_("chktex failure"),
1646 _("Could not run chktex successfully."));
1647 } else if (res > 0) {
1648 ErrorList & errlist = d->errorLists["ChkTeX"];
1650 bufferErrors(terr, errlist);
1661 void Buffer::validate(LaTeXFeatures & features) const
1663 params().validate(features);
1667 for_each(paragraphs().begin(), paragraphs().end(),
1668 bind(&Paragraph::validate, _1, ref(features)));
1670 if (lyxerr.debugging(Debug::LATEX)) {
1671 features.showStruct();
1676 void Buffer::getLabelList(vector<docstring> & list) const
1678 // If this is a child document, use the parent's list instead.
1679 Buffer const * const pbuf = d->parent();
1681 pbuf->getLabelList(list);
1686 Toc & toc = d->toc_backend.toc("label");
1687 TocIterator toc_it = toc.begin();
1688 TocIterator end = toc.end();
1689 for (; toc_it != end; ++toc_it) {
1690 if (toc_it->depth() == 0)
1691 list.push_back(toc_it->str());
1696 void Buffer::updateBibfilesCache(UpdateScope scope) const
1698 // If this is a child document, use the parent's cache instead.
1699 Buffer const * const pbuf = d->parent();
1700 if (pbuf && scope != UpdateChildOnly) {
1701 pbuf->updateBibfilesCache();
1705 d->bibfiles_cache_.clear();
1706 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1707 if (it->lyxCode() == BIBTEX_CODE) {
1708 InsetBibtex const & inset =
1709 static_cast<InsetBibtex const &>(*it);
1710 support::FileNameList const bibfiles = inset.getBibFiles();
1711 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1714 } else if (it->lyxCode() == INCLUDE_CODE) {
1715 InsetInclude & inset =
1716 static_cast<InsetInclude &>(*it);
1717 inset.updateBibfilesCache();
1718 support::FileNameList const & bibfiles =
1719 inset.getBibfilesCache();
1720 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1725 // the bibinfo cache is now invalid
1726 d->bibinfo_cache_valid_ = false;
1730 void Buffer::invalidateBibinfoCache()
1732 d->bibinfo_cache_valid_ = false;
1736 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1738 // If this is a child document, use the parent's cache instead.
1739 Buffer const * const pbuf = d->parent();
1740 if (pbuf && scope != UpdateChildOnly)
1741 return pbuf->getBibfilesCache();
1743 // We update the cache when first used instead of at loading time.
1744 if (d->bibfiles_cache_.empty())
1745 const_cast<Buffer *>(this)->updateBibfilesCache(scope);
1747 return d->bibfiles_cache_;
1751 BiblioInfo const & Buffer::masterBibInfo() const
1753 // if this is a child document and the parent is already loaded
1754 // use the parent's list instead [ale990412]
1755 Buffer const * const tmp = masterBuffer();
1758 return tmp->masterBibInfo();
1759 return localBibInfo();
1763 BiblioInfo const & Buffer::localBibInfo() const
1769 void Buffer::checkBibInfoCache() const
1771 support::FileNameList const & bibfilesCache = getBibfilesCache();
1772 // compare the cached timestamps with the actual ones.
1773 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1774 support::FileNameList::const_iterator en = bibfilesCache.end();
1775 for (; ei != en; ++ ei) {
1776 time_t lastw = ei->lastModified();
1777 time_t prevw = d->bibfile_status_[*ei];
1778 if (lastw != prevw) {
1779 d->bibinfo_cache_valid_ = false;
1780 d->bibfile_status_[*ei] = lastw;
1784 if (!d->bibinfo_cache_valid_) {
1785 d->bibinfo_.clear();
1786 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1787 it->fillWithBibKeys(d->bibinfo_, it);
1788 d->bibinfo_cache_valid_ = true;
1793 bool Buffer::isDepClean(string const & name) const
1795 DepClean::const_iterator const it = d->dep_clean.find(name);
1796 if (it == d->dep_clean.end())
1802 void Buffer::markDepClean(string const & name)
1804 d->dep_clean[name] = true;
1808 bool Buffer::isExportableFormat(string const & format) const
1810 typedef vector<Format const *> Formats;
1812 formats = exportableFormats(true);
1813 Formats::const_iterator fit = formats.begin();
1814 Formats::const_iterator end = formats.end();
1815 for (; fit != end ; ++fit) {
1816 if ((*fit)->name() == format)
1823 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1826 // FIXME? if there is an Buffer LFUN that can be dispatched even
1827 // if internal, put a switch '(cmd.action)' here.
1833 switch (cmd.action()) {
1835 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1836 flag.setOnOff(isReadonly());
1839 // FIXME: There is need for a command-line import.
1840 //case LFUN_BUFFER_IMPORT:
1842 case LFUN_BUFFER_AUTO_SAVE:
1845 case LFUN_BUFFER_EXPORT_CUSTOM:
1846 // FIXME: Nothing to check here?
1849 case LFUN_BUFFER_EXPORT: {
1850 docstring const arg = cmd.argument();
1851 enable = arg == "custom" || isExportable(to_utf8(arg));
1853 flag.message(bformat(
1854 _("Don't know how to export to format: %1$s"), arg));
1858 case LFUN_BUFFER_CHKTEX:
1859 enable = isLatex() && !lyxrc.chktex_command.empty();
1862 case LFUN_BUILD_PROGRAM:
1863 enable = isExportable("program");
1866 case LFUN_BRANCH_ACTIVATE:
1867 case LFUN_BRANCH_DEACTIVATE: {
1868 BranchList const & branchList = params().branchlist();
1869 docstring const branchName = cmd.argument();
1870 enable = !branchName.empty() && branchList.find(branchName);
1874 case LFUN_BRANCH_ADD:
1875 case LFUN_BRANCHES_RENAME:
1876 case LFUN_BUFFER_PRINT:
1877 // if no Buffer is present, then of course we won't be called!
1880 case LFUN_BUFFER_LANGUAGE:
1881 enable = !isReadonly();
1887 flag.setEnabled(enable);
1892 void Buffer::dispatch(string const & command, DispatchResult & result)
1894 return dispatch(lyxaction.lookupFunc(command), result);
1898 // NOTE We can end up here even if we have no GUI, because we are called
1899 // by LyX::exec to handled command-line requests. So we may need to check
1900 // whether we have a GUI or not. The boolean use_gui holds this information.
1901 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
1904 // FIXME? if there is an Buffer LFUN that can be dispatched even
1905 // if internal, put a switch '(cmd.action())' here.
1906 dr.dispatched(false);
1909 string const argument = to_utf8(func.argument());
1910 // We'll set this back to false if need be.
1911 bool dispatched = true;
1912 undo().beginUndoGroup();
1914 switch (func.action()) {
1915 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1916 if (lyxvc().inUse())
1917 lyxvc().toggleReadOnly();
1919 setReadonly(!isReadonly());
1922 case LFUN_BUFFER_EXPORT: {
1923 bool success = doExport(argument, false, false);
1924 dr.setError(!success);
1926 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
1931 case LFUN_BUILD_PROGRAM:
1932 doExport("program", true, false);
1935 case LFUN_BUFFER_CHKTEX:
1939 case LFUN_BUFFER_EXPORT_CUSTOM: {
1941 string command = split(argument, format_name, ' ');
1942 Format const * format = formats.getFormat(format_name);
1944 lyxerr << "Format \"" << format_name
1945 << "\" not recognized!"
1950 // The name of the file created by the conversion process
1953 // Output to filename
1954 if (format->name() == "lyx") {
1955 string const latexname = latexName(false);
1956 filename = changeExtension(latexname,
1957 format->extension());
1958 filename = addName(temppath(), filename);
1960 if (!writeFile(FileName(filename)))
1964 doExport(format_name, true, false, filename);
1967 // Substitute $$FName for filename
1968 if (!contains(command, "$$FName"))
1969 command = "( " + command + " ) < $$FName";
1970 command = subst(command, "$$FName", filename);
1972 // Execute the command in the background
1974 call.startscript(Systemcall::DontWait, command);
1978 // FIXME: There is need for a command-line import.
1980 case LFUN_BUFFER_IMPORT:
1985 case LFUN_BUFFER_AUTO_SAVE:
1989 case LFUN_BRANCH_ADD: {
1990 docstring branch_name = func.argument();
1991 if (branch_name.empty()) {
1995 BranchList & branch_list = params().branchlist();
1996 vector<docstring> const branches =
1997 getVectorFromString(branch_name, branch_list.separator());
1999 for (vector<docstring>::const_iterator it = branches.begin();
2000 it != branches.end(); ++it) {
2002 Branch * branch = branch_list.find(branch_name);
2004 LYXERR0("Branch " << branch_name << " already exists.");
2008 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2010 branch_list.add(branch_name);
2011 branch = branch_list.find(branch_name);
2012 string const x11hexname = X11hexname(branch->color());
2013 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2014 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2016 dr.update(Update::Force);
2024 case LFUN_BRANCH_ACTIVATE:
2025 case LFUN_BRANCH_DEACTIVATE: {
2026 BranchList & branchList = params().branchlist();
2027 docstring const branchName = func.argument();
2028 // the case without a branch name is handled elsewhere
2029 if (branchName.empty()) {
2033 Branch * branch = branchList.find(branchName);
2035 LYXERR0("Branch " << branchName << " does not exist.");
2037 docstring const msg =
2038 bformat(_("Branch \"%1$s\" does not exist."), branchName);
2041 branch->setSelected(func.action() == LFUN_BRANCH_ACTIVATE);
2043 dr.update(Update::Force);
2044 dr.forceBufferUpdate();
2049 case LFUN_BRANCHES_RENAME: {
2050 if (func.argument().empty())
2053 docstring const oldname = from_utf8(func.getArg(0));
2054 docstring const newname = from_utf8(func.getArg(1));
2055 InsetIterator it = inset_iterator_begin(inset());
2056 InsetIterator const end = inset_iterator_end(inset());
2057 bool success = false;
2058 for (; it != end; ++it) {
2059 if (it->lyxCode() == BRANCH_CODE) {
2060 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2061 if (ins.branch() == oldname) {
2062 undo().recordUndo(it);
2063 ins.rename(newname);
2068 if (it->lyxCode() == INCLUDE_CODE) {
2069 // get buffer of external file
2070 InsetInclude const & ins =
2071 static_cast<InsetInclude const &>(*it);
2072 Buffer * child = ins.getChildBuffer();
2075 child->dispatch(func, dr);
2080 dr.update(Update::Force);
2081 dr.forceBufferUpdate();
2086 case LFUN_BUFFER_PRINT: {
2087 // we'll assume there's a problem until we succeed
2089 string target = func.getArg(0);
2090 string target_name = func.getArg(1);
2091 string command = func.getArg(2);
2094 || target_name.empty()
2095 || command.empty()) {
2096 LYXERR0("Unable to parse " << func.argument());
2097 docstring const msg =
2098 bformat(_("Unable to parse \"%1$s\""), func.argument());
2102 if (target != "printer" && target != "file") {
2103 LYXERR0("Unrecognized target \"" << target << '"');
2104 docstring const msg =
2105 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2110 bool const update_unincluded =
2111 params().maintain_unincluded_children
2112 && !params().getIncludedChildren().empty();
2113 if (!doExport("dvi", true, update_unincluded)) {
2114 showPrintError(absFileName());
2115 dr.setMessage(_("Error exporting to DVI."));
2119 // Push directory path.
2120 string const path = temppath();
2121 // Prevent the compiler from optimizing away p
2125 // there are three cases here:
2126 // 1. we print to a file
2127 // 2. we print directly to a printer
2128 // 3. we print using a spool command (print to file first)
2131 string const dviname = changeExtension(latexName(true), "dvi");
2133 if (target == "printer") {
2134 if (!lyxrc.print_spool_command.empty()) {
2135 // case 3: print using a spool
2136 string const psname = changeExtension(dviname,".ps");
2137 command += ' ' + lyxrc.print_to_file
2140 + quoteName(dviname);
2142 string command2 = lyxrc.print_spool_command + ' ';
2143 if (target_name != "default") {
2144 command2 += lyxrc.print_spool_printerprefix
2148 command2 += quoteName(psname);
2150 // If successful, then spool command
2151 res = one.startscript(Systemcall::Wait, command);
2154 // If there's no GUI, we have to wait on this command. Otherwise,
2155 // LyX deletes the temporary directory, and with it the spooled
2156 // file, before it can be printed!!
2157 Systemcall::Starttype stype = use_gui ?
2158 Systemcall::DontWait : Systemcall::Wait;
2159 res = one.startscript(stype, command2);
2162 // case 2: print directly to a printer
2163 if (target_name != "default")
2164 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2166 Systemcall::Starttype stype = use_gui ?
2167 Systemcall::DontWait : Systemcall::Wait;
2168 res = one.startscript(stype, command + quoteName(dviname));
2172 // case 1: print to a file
2173 FileName const filename(makeAbsPath(target_name, filePath()));
2174 FileName const dvifile(makeAbsPath(dviname, path));
2175 if (filename.exists()) {
2176 docstring text = bformat(
2177 _("The file %1$s already exists.\n\n"
2178 "Do you want to overwrite that file?"),
2179 makeDisplayPath(filename.absFileName()));
2180 if (Alert::prompt(_("Overwrite file?"),
2181 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2184 command += ' ' + lyxrc.print_to_file
2185 + quoteName(filename.toFilesystemEncoding())
2187 + quoteName(dvifile.toFilesystemEncoding());
2189 Systemcall::Starttype stype = use_gui ?
2190 Systemcall::DontWait : Systemcall::Wait;
2191 res = one.startscript(stype, command);
2197 dr.setMessage(_("Error running external commands."));
2198 showPrintError(absFileName());
2203 case LFUN_BUFFER_LANGUAGE: {
2204 Language const * oldL = params().language;
2205 Language const * newL = languages.getLanguage(argument);
2206 if (!newL || oldL == newL)
2208 if (oldL->rightToLeft() == newL->rightToLeft() && !isMultiLingual()) {
2209 changeLanguage(oldL, newL);
2210 dr.forceBufferUpdate();
2219 dr.dispatched(dispatched);
2220 undo().endUndoGroup();
2224 void Buffer::changeLanguage(Language const * from, Language const * to)
2226 LASSERT(from, /**/);
2229 for_each(par_iterator_begin(),
2231 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2235 bool Buffer::isMultiLingual() const
2237 ParConstIterator end = par_iterator_end();
2238 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2239 if (it->isMultiLingual(params()))
2246 std::set<Language const *> Buffer::getLanguages() const
2248 std::set<Language const *> languages;
2249 getLanguages(languages);
2254 void Buffer::getLanguages(std::set<Language const *> & languages) const
2256 ParConstIterator end = par_iterator_end();
2257 // add the buffer language, even if it's not actively used
2258 languages.insert(language());
2259 // iterate over the paragraphs
2260 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2261 it->getLanguages(languages);
2263 std::vector<Buffer *> clist = getChildren();
2264 for (vector<Buffer *>::const_iterator cit = clist.begin();
2265 cit != clist.end(); ++cit)
2266 (*cit)->getLanguages(languages);
2270 DocIterator Buffer::getParFromID(int const id) const
2272 Buffer * buf = const_cast<Buffer *>(this);
2274 // John says this is called with id == -1 from undo
2275 lyxerr << "getParFromID(), id: " << id << endl;
2276 return doc_iterator_end(buf);
2279 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2280 if (it.paragraph().id() == id)
2283 return doc_iterator_end(buf);
2287 bool Buffer::hasParWithID(int const id) const
2289 return !getParFromID(id).atEnd();
2293 ParIterator Buffer::par_iterator_begin()
2295 return ParIterator(doc_iterator_begin(this));
2299 ParIterator Buffer::par_iterator_end()
2301 return ParIterator(doc_iterator_end(this));
2305 ParConstIterator Buffer::par_iterator_begin() const
2307 return ParConstIterator(doc_iterator_begin(this));
2311 ParConstIterator Buffer::par_iterator_end() const
2313 return ParConstIterator(doc_iterator_end(this));
2317 Language const * Buffer::language() const
2319 return params().language;
2323 docstring const Buffer::B_(string const & l10n) const
2325 return params().B_(l10n);
2329 bool Buffer::isClean() const
2331 return d->lyx_clean;
2335 bool Buffer::isExternallyModified(CheckMethod method) const
2337 LASSERT(d->filename.exists(), /**/);
2338 // if method == timestamp, check timestamp before checksum
2339 return (method == checksum_method
2340 || d->timestamp_ != d->filename.lastModified())
2341 && d->checksum_ != d->filename.checksum();
2345 void Buffer::saveCheckSum(FileName const & file) const
2347 if (file.exists()) {
2348 d->timestamp_ = file.lastModified();
2349 d->checksum_ = file.checksum();
2351 // in the case of save to a new file.
2358 void Buffer::markClean() const
2360 if (!d->lyx_clean) {
2361 d->lyx_clean = true;
2364 // if the .lyx file has been saved, we don't need an
2366 d->bak_clean = true;
2367 d->undo_.markDirty();
2371 void Buffer::setUnnamed(bool flag)
2377 bool Buffer::isUnnamed() const
2384 /// Don't check unnamed, here: isInternal() is used in
2385 /// newBuffer(), where the unnamed flag has not been set by anyone
2386 /// yet. Also, for an internal buffer, there should be no need for
2387 /// retrieving fileName() nor for checking if it is unnamed or not.
2388 bool Buffer::isInternal() const
2390 return fileName().extension() == "internal";
2394 void Buffer::markDirty()
2397 d->lyx_clean = false;
2400 d->bak_clean = false;
2402 DepClean::iterator it = d->dep_clean.begin();
2403 DepClean::const_iterator const end = d->dep_clean.end();
2405 for (; it != end; ++it)
2410 FileName Buffer::fileName() const
2416 string Buffer::absFileName() const
2418 return d->filename.absFileName();
2422 string Buffer::filePath() const
2424 return d->filename.onlyPath().absFileName() + "/";
2428 bool Buffer::isReadonly() const
2430 return d->read_only;
2434 void Buffer::setParent(Buffer const * buffer)
2436 // Avoids recursive include.
2437 d->setParent(buffer == this ? 0 : buffer);
2442 Buffer const * Buffer::parent() const
2448 void Buffer::Impl::collectRelatives(BufferSet & bufs) const
2450 bufs.insert(owner_);
2452 parent()->d->collectRelatives(bufs);
2454 // loop over children
2455 BufferPositionMap::const_iterator it = children_positions.begin();
2456 BufferPositionMap::const_iterator end = children_positions.end();
2457 for (; it != end; ++it)
2458 bufs.insert(const_cast<Buffer *>(it->first));
2462 std::vector<Buffer const *> Buffer::allRelatives() const
2465 d->collectRelatives(bufs);
2466 BufferSet::iterator it = bufs.begin();
2467 std::vector<Buffer const *> ret;
2468 for (; it != bufs.end(); ++it)
2474 Buffer const * Buffer::masterBuffer() const
2476 Buffer const * const pbuf = d->parent();
2480 return pbuf->masterBuffer();
2484 bool Buffer::isChild(Buffer * child) const
2486 return d->children_positions.find(child) != d->children_positions.end();
2490 DocIterator Buffer::firstChildPosition(Buffer const * child)
2492 Impl::BufferPositionMap::iterator it;
2493 it = d->children_positions.find(child);
2494 if (it == d->children_positions.end())
2495 return DocIterator(this);
2500 void Buffer::getChildren(std::vector<Buffer *> & clist, bool grand_children) const
2502 // loop over children
2503 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2504 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2505 for (; it != end; ++it) {
2506 Buffer * child = const_cast<Buffer *>(it->first);
2507 clist.push_back(child);
2508 if (grand_children) {
2509 // there might be grandchildren
2510 vector<Buffer *> glist = child->getChildren();
2511 clist.insert(clist.end(), glist.begin(), glist.end());
2517 vector<Buffer *> Buffer::getChildren(bool grand_children) const
2520 getChildren(v, grand_children);
2525 template<typename M>
2526 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
2531 typename M::const_iterator it = m.lower_bound(x);
2532 if (it == m.begin())
2540 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
2541 DocIterator const & pos) const
2543 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2545 // if paragraphs have no macro context set, pos will be empty
2549 // we haven't found anything yet
2550 DocIterator bestPos = owner_->par_iterator_begin();
2551 MacroData const * bestData = 0;
2553 // find macro definitions for name
2554 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
2555 if (nameIt != macros.end()) {
2556 // find last definition in front of pos or at pos itself
2557 PositionScopeMacroMap::const_iterator it
2558 = greatest_below(nameIt->second, pos);
2559 if (it != nameIt->second.end()) {
2561 // scope ends behind pos?
2562 if (pos < it->second.first) {
2563 // Looks good, remember this. If there
2564 // is no external macro behind this,
2565 // we found the right one already.
2566 bestPos = it->first;
2567 bestData = &it->second.second;
2571 // try previous macro if there is one
2572 if (it == nameIt->second.begin())
2579 // find macros in included files
2580 PositionScopeBufferMap::const_iterator it
2581 = greatest_below(position_to_children, pos);
2582 if (it == position_to_children.end())
2583 // no children before
2587 // do we know something better (i.e. later) already?
2588 if (it->first < bestPos )
2591 // scope ends behind pos?
2592 if (pos < it->second.first) {
2593 // look for macro in external file
2595 MacroData const * data
2596 = it->second.second->getMacro(name, false);
2599 bestPos = it->first;
2605 // try previous file if there is one
2606 if (it == position_to_children.begin())
2611 // return the best macro we have found
2616 MacroData const * Buffer::getMacro(docstring const & name,
2617 DocIterator const & pos, bool global) const
2622 // query buffer macros
2623 MacroData const * data = d->getBufferMacro(name, pos);
2627 // If there is a master buffer, query that
2628 Buffer const * const pbuf = d->parent();
2630 d->macro_lock = true;
2631 MacroData const * macro = pbuf->getMacro(
2632 name, *this, false);
2633 d->macro_lock = false;
2639 data = MacroTable::globalMacros().get(name);
2648 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2650 // set scope end behind the last paragraph
2651 DocIterator scope = par_iterator_begin();
2652 scope.pit() = scope.lastpit() + 1;
2654 return getMacro(name, scope, global);
2658 MacroData const * Buffer::getMacro(docstring const & name,
2659 Buffer const & child, bool global) const
2661 // look where the child buffer is included first
2662 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2663 if (it == d->children_positions.end())
2666 // check for macros at the inclusion position
2667 return getMacro(name, it->second, global);
2671 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
2673 pit_type const lastpit = it.lastpit();
2675 // look for macros in each paragraph
2676 while (it.pit() <= lastpit) {
2677 Paragraph & par = it.paragraph();
2679 // iterate over the insets of the current paragraph
2680 InsetList const & insets = par.insetList();
2681 InsetList::const_iterator iit = insets.begin();
2682 InsetList::const_iterator end = insets.end();
2683 for (; iit != end; ++iit) {
2684 it.pos() = iit->pos;
2686 // is it a nested text inset?
2687 if (iit->inset->asInsetText()) {
2688 // Inset needs its own scope?
2689 InsetText const * itext = iit->inset->asInsetText();
2690 bool newScope = itext->isMacroScope();
2692 // scope which ends just behind the inset
2693 DocIterator insetScope = it;
2696 // collect macros in inset
2697 it.push_back(CursorSlice(*iit->inset));
2698 updateMacros(it, newScope ? insetScope : scope);
2703 // is it an external file?
2704 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2705 // get buffer of external file
2706 InsetInclude const & inset =
2707 static_cast<InsetInclude const &>(*iit->inset);
2709 Buffer * child = inset.getChildBuffer();
2714 // register its position, but only when it is
2715 // included first in the buffer
2716 if (children_positions.find(child) ==
2717 children_positions.end())
2718 children_positions[child] = it;
2720 // register child with its scope
2721 position_to_children[it] = Impl::ScopeBuffer(scope, child);
2725 if (doing_export && iit->inset->asInsetMath()) {
2726 InsetMath * im = static_cast<InsetMath *>(iit->inset);
2727 if (im->asHullInset()) {
2728 InsetMathHull * hull = static_cast<InsetMathHull *>(im);
2729 hull->recordLocation(it);
2733 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2737 MathMacroTemplate & macroTemplate =
2738 static_cast<MathMacroTemplate &>(*iit->inset);
2739 MacroContext mc(owner_, it);
2740 macroTemplate.updateToContext(mc);
2743 bool valid = macroTemplate.validMacro();
2744 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2745 // then the BufferView's cursor will be invalid in
2746 // some cases which leads to crashes.
2751 // FIXME (Abdel), I don't understandt why we pass 'it' here
2752 // instead of 'macroTemplate' defined above... is this correct?
2753 macros[macroTemplate.name()][it] =
2754 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
2764 void Buffer::updateMacros() const
2769 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2771 // start with empty table
2773 d->children_positions.clear();
2774 d->position_to_children.clear();
2776 // Iterate over buffer, starting with first paragraph
2777 // The scope must be bigger than any lookup DocIterator
2778 // later. For the global lookup, lastpit+1 is used, hence
2779 // we use lastpit+2 here.
2780 DocIterator it = par_iterator_begin();
2781 DocIterator outerScope = it;
2782 outerScope.pit() = outerScope.lastpit() + 2;
2783 d->updateMacros(it, outerScope);
2787 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
2789 InsetIterator it = inset_iterator_begin(inset());
2790 InsetIterator const end = inset_iterator_end(inset());
2791 for (; it != end; ++it) {
2792 if (it->lyxCode() == BRANCH_CODE) {
2793 InsetBranch & br = static_cast<InsetBranch &>(*it);
2794 docstring const name = br.branch();
2795 if (!from_master && !params().branchlist().find(name))
2796 result.push_back(name);
2797 else if (from_master && !masterBuffer()->params().branchlist().find(name))
2798 result.push_back(name);
2801 if (it->lyxCode() == INCLUDE_CODE) {
2802 // get buffer of external file
2803 InsetInclude const & ins =
2804 static_cast<InsetInclude const &>(*it);
2805 Buffer * child = ins.getChildBuffer();
2808 child->getUsedBranches(result, true);
2811 // remove duplicates
2816 void Buffer::updateMacroInstances() const
2818 LYXERR(Debug::MACROS, "updateMacroInstances for "
2819 << d->filename.onlyFileName());
2820 DocIterator it = doc_iterator_begin(this);
2822 DocIterator const end = doc_iterator_end(this);
2823 for (; it != end; it.forwardInset()) {
2824 // look for MathData cells in InsetMathNest insets
2825 InsetMath * minset = it.nextInset()->asInsetMath();
2829 // update macro in all cells of the InsetMathNest
2830 DocIterator::idx_type n = minset->nargs();
2831 MacroContext mc = MacroContext(this, it);
2832 for (DocIterator::idx_type i = 0; i < n; ++i) {
2833 MathData & data = minset->cell(i);
2834 data.updateMacros(0, mc);
2840 void Buffer::listMacroNames(MacroNameSet & macros) const
2845 d->macro_lock = true;
2847 // loop over macro names
2848 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2849 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2850 for (; nameIt != nameEnd; ++nameIt)
2851 macros.insert(nameIt->first);
2853 // loop over children
2854 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2855 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2856 for (; it != end; ++it)
2857 it->first->listMacroNames(macros);
2860 Buffer const * const pbuf = d->parent();
2862 pbuf->listMacroNames(macros);
2864 d->macro_lock = false;
2868 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2870 Buffer const * const pbuf = d->parent();
2875 pbuf->listMacroNames(names);
2878 MacroNameSet::iterator it = names.begin();
2879 MacroNameSet::iterator end = names.end();
2880 for (; it != end; ++it) {
2882 MacroData const * data =
2883 pbuf->getMacro(*it, *this, false);
2885 macros.insert(data);
2887 // we cannot access the original MathMacroTemplate anymore
2888 // here to calls validate method. So we do its work here manually.
2889 // FIXME: somehow make the template accessible here.
2890 if (data->optionals() > 0)
2891 features.require("xargs");
2897 Buffer::References & Buffer::references(docstring const & label)
2900 return const_cast<Buffer *>(masterBuffer())->references(label);
2902 RefCache::iterator it = d->ref_cache_.find(label);
2903 if (it != d->ref_cache_.end())
2904 return it->second.second;
2906 static InsetLabel const * dummy_il = 0;
2907 static References const dummy_refs;
2908 it = d->ref_cache_.insert(
2909 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2910 return it->second.second;
2914 Buffer::References const & Buffer::references(docstring const & label) const
2916 return const_cast<Buffer *>(this)->references(label);
2920 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2922 masterBuffer()->d->ref_cache_[label].first = il;
2926 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2928 return masterBuffer()->d->ref_cache_[label].first;
2932 void Buffer::clearReferenceCache() const
2935 d->ref_cache_.clear();
2939 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2942 //FIXME: This does not work for child documents yet.
2943 LASSERT(code == CITE_CODE, /**/);
2944 // Check if the label 'from' appears more than once
2945 vector<docstring> labels;
2947 checkBibInfoCache();
2948 BiblioInfo const & keys = masterBibInfo();
2949 BiblioInfo::const_iterator bit = keys.begin();
2950 BiblioInfo::const_iterator bend = keys.end();
2952 for (; bit != bend; ++bit)
2954 labels.push_back(bit->first);
2957 if (count(labels.begin(), labels.end(), from) > 1)
2960 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2961 if (it->lyxCode() == code) {
2962 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2963 docstring const oldValue = inset.getParam(paramName);
2964 if (oldValue == from)
2965 inset.setParam(paramName, to);
2971 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2972 pit_type par_end, bool full_source) const
2974 OutputParams runparams(¶ms().encoding());
2975 runparams.nice = true;
2976 runparams.flavor = params().useXetex ?
2977 OutputParams::XETEX : OutputParams::LATEX;
2978 runparams.linelen = lyxrc.plaintext_linelen;
2979 // No side effect of file copying and image conversion
2980 runparams.dryrun = true;
2983 os << "% " << _("Preview source code") << "\n\n";
2985 d->texrow.newline();
2986 d->texrow.newline();
2988 writeDocBookSource(os, absFileName(), runparams, false);
2990 // latex or literate
2991 writeLaTeXSource(os, string(), runparams, true, true);
2993 runparams.par_begin = par_begin;
2994 runparams.par_end = par_end;
2995 if (par_begin + 1 == par_end) {
2997 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3001 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3002 convert<docstring>(par_begin),
3003 convert<docstring>(par_end - 1))
3010 // output paragraphs
3012 docbookParagraphs(text(), *this, os, runparams);
3014 // latex or literate
3015 latexParagraphs(*this, text(), os, texrow, runparams);
3020 ErrorList & Buffer::errorList(string const & type) const
3022 static ErrorList emptyErrorList;
3023 map<string, ErrorList>::iterator it = d->errorLists.find(type);
3024 if (it == d->errorLists.end())
3025 return emptyErrorList;
3031 void Buffer::updateTocItem(std::string const & type,
3032 DocIterator const & dit) const
3035 d->gui_->updateTocItem(type, dit);
3039 void Buffer::structureChanged() const
3042 d->gui_->structureChanged();
3046 void Buffer::errors(string const & err, bool from_master) const
3049 d->gui_->errors(err, from_master);
3053 void Buffer::message(docstring const & msg) const
3056 d->gui_->message(msg);
3060 void Buffer::setBusy(bool on) const
3063 d->gui_->setBusy(on);
3067 void Buffer::updateTitles() const
3070 d->wa_->updateTitles();
3074 void Buffer::resetAutosaveTimers() const
3077 d->gui_->resetAutosaveTimers();
3081 bool Buffer::hasGuiDelegate() const
3087 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3096 class AutoSaveBuffer : public ForkedProcess {
3099 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3100 : buffer_(buffer), fname_(fname) {}
3102 virtual shared_ptr<ForkedProcess> clone() const
3104 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3109 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3110 from_utf8(fname_.absFileName())));
3111 return run(DontWait);
3115 virtual int generateChild();
3117 Buffer const & buffer_;
3122 int AutoSaveBuffer::generateChild()
3124 #if defined(__APPLE__)
3125 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3126 * We should use something else like threads.
3128 * Since I do not know how to determine at run time what is the OS X
3129 * version, I just disable forking altogether for now (JMarc)
3131 pid_t const pid = -1;
3133 // tmp_ret will be located (usually) in /tmp
3134 // will that be a problem?
3135 // Note that this calls ForkedCalls::fork(), so it's
3136 // ok cross-platform.
3137 pid_t const pid = fork();
3138 // If you want to debug the autosave
3139 // you should set pid to -1, and comment out the fork.
3140 if (pid != 0 && pid != -1)
3144 // pid = -1 signifies that lyx was unable
3145 // to fork. But we will do the save
3147 bool failed = false;
3148 FileName const tmp_ret = FileName::tempName("lyxauto");
3149 if (!tmp_ret.empty()) {
3150 buffer_.writeFile(tmp_ret);
3151 // assume successful write of tmp_ret
3152 if (!tmp_ret.moveTo(fname_))
3158 // failed to write/rename tmp_ret so try writing direct
3159 if (!buffer_.writeFile(fname_)) {
3160 // It is dangerous to do this in the child,
3161 // but safe in the parent, so...
3162 if (pid == -1) // emit message signal.
3163 buffer_.message(_("Autosave failed!"));
3167 if (pid == 0) // we are the child so...
3176 FileName Buffer::getAutosaveFileName() const
3178 // if the document is unnamed try to save in the backup dir, else
3179 // in the default document path, and as a last try in the filePath,
3180 // which will most often be the temporary directory
3183 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3184 : lyxrc.backupdir_path;
3185 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3188 string const fname = "#" + d->filename.onlyFileName() + "#";
3189 return makeAbsPath(fname, fpath);
3193 void Buffer::removeAutosaveFile() const
3195 FileName const f = getAutosaveFileName();
3201 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3203 FileName const newauto = getAutosaveFileName();
3205 if (newauto != oldauto && oldauto.exists())
3206 if (!oldauto.moveTo(newauto))
3207 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3211 // Perfect target for a thread...
3212 void Buffer::autoSave() const
3214 if (d->bak_clean || isReadonly()) {
3215 // We don't save now, but we'll try again later
3216 resetAutosaveTimers();
3220 // emit message signal.
3221 message(_("Autosaving current document..."));
3222 AutoSaveBuffer autosave(*this, getAutosaveFileName());
3225 d->bak_clean = true;
3227 resetAutosaveTimers();
3231 string Buffer::bufferFormat() const
3233 string format = params().documentClass().outputFormat();
3234 if (format == "latex") {
3235 if (params().useXetex)
3237 if (params().encoding().package() == Encoding::japanese)
3244 string Buffer::getDefaultOutputFormat() const
3246 if (!params().defaultOutputFormat.empty()
3247 && params().defaultOutputFormat != "default")
3248 return params().defaultOutputFormat;
3249 typedef vector<Format const *> Formats;
3250 Formats formats = exportableFormats(true);
3253 || params().useXetex
3254 || params().encoding().package() == Encoding::japanese) {
3255 if (formats.empty())
3257 // return the first we find
3258 return formats.front()->name();
3260 return lyxrc.default_view_format;
3265 // helper class, to guarantee this gets reset properly
3266 class MarkAsExporting {
3268 MarkAsExporting(Buffer const * buf) : buf_(buf)
3270 LASSERT(buf_, /* */);
3271 buf_->setExportStatus(true);
3275 buf_->setExportStatus(false);
3278 Buffer const * const buf_;
3283 void Buffer::setExportStatus(bool e) const
3285 d->doing_export = e;
3289 bool Buffer::isExporting() const
3291 return d->doing_export;
3295 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3296 bool includeall, string & result_file) const
3298 MarkAsExporting exporting(this);
3299 string backend_format;
3300 OutputParams runparams(¶ms().encoding());
3301 runparams.flavor = OutputParams::LATEX;
3302 runparams.linelen = lyxrc.plaintext_linelen;
3303 runparams.includeall = includeall;
3304 vector<string> backs = backends();
3305 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3306 // Get shortest path to format
3307 Graph::EdgePath path;
3308 for (vector<string>::const_iterator it = backs.begin();
3309 it != backs.end(); ++it) {
3310 Graph::EdgePath p = theConverters().getPath(*it, format);
3311 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3312 backend_format = *it;
3317 if (!put_in_tempdir) {
3318 // Only show this alert if this is an export to a non-temporary
3319 // file (not for previewing).
3320 Alert::error(_("Couldn't export file"), bformat(
3321 _("No information for exporting the format %1$s."),
3322 formats.prettyName(format)));
3326 runparams.flavor = theConverters().getFlavor(path);
3329 backend_format = format;
3330 // FIXME: Don't hardcode format names here, but use a flag
3331 if (backend_format == "pdflatex")
3332 runparams.flavor = OutputParams::PDFLATEX;
3335 string filename = latexName(false);
3336 filename = addName(temppath(), filename);
3337 filename = changeExtension(filename,
3338 formats.extension(backend_format));
3341 updateMacroInstances();
3343 // Plain text backend
3344 if (backend_format == "text") {
3345 runparams.flavor = OutputParams::TEXT;
3346 writePlaintextFile(*this, FileName(filename), runparams);
3349 else if (backend_format == "xhtml") {
3350 runparams.flavor = OutputParams::HTML;
3351 switch (params().html_math_output) {
3352 case BufferParams::MathML:
3353 runparams.math_flavor = OutputParams::MathAsMathML;
3355 case BufferParams::HTML:
3356 runparams.math_flavor = OutputParams::MathAsHTML;
3358 case BufferParams::Images:
3359 runparams.math_flavor = OutputParams::MathAsImages;
3361 case BufferParams::LaTeX:
3362 runparams.math_flavor = OutputParams::MathAsLaTeX;
3366 makeLyXHTMLFile(FileName(filename), runparams);
3367 } else if (backend_format == "lyx")
3368 writeFile(FileName(filename));
3370 else if (isDocBook()) {
3371 runparams.nice = !put_in_tempdir;
3372 makeDocBookFile(FileName(filename), runparams);
3375 else if (backend_format == format) {
3376 runparams.nice = true;
3377 if (!makeLaTeXFile(FileName(filename), string(), runparams))
3379 } else if (!lyxrc.tex_allows_spaces
3380 && contains(filePath(), ' ')) {
3381 Alert::error(_("File name error"),
3382 _("The directory path to the document cannot contain spaces."));
3385 runparams.nice = false;
3386 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
3390 string const error_type = (format == "program")
3391 ? "Build" : bufferFormat();
3392 ErrorList & error_list = d->errorLists[error_type];
3393 string const ext = formats.extension(format);
3394 FileName const tmp_result_file(changeExtension(filename, ext));
3395 bool const success = theConverters().convert(this, FileName(filename),
3396 tmp_result_file, FileName(absFileName()), backend_format, format,
3399 // Emit the signal to show the error list or copy it back to the
3400 // cloned Buffer so that it cab be emitted afterwards.
3401 if (format != backend_format) {
3402 if (d->cloned_buffer_) {
3403 d->cloned_buffer_->d->errorLists[error_type] =
3404 d->errorLists[error_type];
3407 // also to the children, in case of master-buffer-view
3408 std::vector<Buffer *> clist = getChildren();
3409 for (vector<Buffer *>::const_iterator cit = clist.begin();
3410 cit != clist.end(); ++cit) {
3411 if (d->cloned_buffer_) {
3412 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
3413 (*cit)->d->errorLists[error_type];
3415 (*cit)->errors(error_type, true);
3419 if (d->cloned_buffer_) {
3420 // Enable reverse dvi or pdf to work by copying back the texrow
3421 // object to the cloned buffer.
3422 // FIXME: There is a possibility of concurrent access to texrow
3423 // here from the main GUI thread that should be securized.
3424 d->cloned_buffer_->d->texrow = d->texrow;
3425 string const error_type = bufferFormat();
3426 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
3432 if (put_in_tempdir) {
3433 result_file = tmp_result_file.absFileName();
3437 result_file = changeExtension(d->exportFileName().absFileName(), ext);
3438 // We need to copy referenced files (e. g. included graphics
3439 // if format == "dvi") to the result dir.
3440 vector<ExportedFile> const files =
3441 runparams.exportdata->externalFiles(format);
3442 string const dest = onlyPath(result_file);
3443 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
3444 : force_overwrite == ALL_FILES;
3445 CopyStatus status = use_force ? FORCE : SUCCESS;
3447 vector<ExportedFile>::const_iterator it = files.begin();
3448 vector<ExportedFile>::const_iterator const en = files.end();
3449 for (; it != en && status != CANCEL; ++it) {
3450 string const fmt = formats.getFormatFromFile(it->sourceName);
3451 status = copyFile(fmt, it->sourceName,
3452 makeAbsPath(it->exportName, dest),
3453 it->exportName, status == FORCE);
3456 if (status == CANCEL) {
3457 message(_("Document export cancelled."));
3458 } else if (tmp_result_file.exists()) {
3459 // Finally copy the main file
3460 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
3461 : force_overwrite != NO_FILES;
3462 if (status == SUCCESS && use_force)
3464 status = copyFile(format, tmp_result_file,
3465 FileName(result_file), result_file,
3467 message(bformat(_("Document exported as %1$s "
3469 formats.prettyName(format),
3470 makeDisplayPath(result_file)));
3472 // This must be a dummy converter like fax (bug 1888)
3473 message(bformat(_("Document exported as %1$s"),
3474 formats.prettyName(format)));
3481 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3482 bool includeall) const
3485 // (1) export with all included children (omit \includeonly)
3486 if (includeall && !doExport(format, put_in_tempdir, true, result_file))
3488 // (2) export with included children only
3489 return doExport(format, put_in_tempdir, false, result_file);
3493 bool Buffer::preview(string const & format, bool includeall) const
3495 MarkAsExporting exporting(this);
3497 // (1) export with all included children (omit \includeonly)
3498 if (includeall && !doExport(format, true, true))
3500 // (2) export with included children only
3501 if (!doExport(format, true, false, result_file))
3503 return formats.view(*this, FileName(result_file), format);
3507 bool Buffer::isExportable(string const & format) const
3509 vector<string> backs = backends();
3510 for (vector<string>::const_iterator it = backs.begin();
3511 it != backs.end(); ++it)
3512 if (theConverters().isReachable(*it, format))
3518 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
3520 vector<string> const backs = backends();
3521 vector<Format const *> result =
3522 theConverters().getReachable(backs[0], only_viewable, true);
3523 for (vector<string>::const_iterator it = backs.begin() + 1;
3524 it != backs.end(); ++it) {
3525 vector<Format const *> r =
3526 theConverters().getReachable(*it, only_viewable, false);
3527 result.insert(result.end(), r.begin(), r.end());
3533 vector<string> Buffer::backends() const
3536 v.push_back(bufferFormat());
3537 // FIXME: Don't hardcode format names here, but use a flag
3538 if (v.back() == "latex")
3539 v.push_back("pdflatex");
3540 v.push_back("xhtml");
3541 v.push_back("text");
3547 bool Buffer::readFileHelper(FileName const & s)
3549 // File information about normal file
3551 docstring const file = makeDisplayPath(s.absFileName(), 50);
3552 docstring text = bformat(_("The specified document\n%1$s"
3553 "\ncould not be read."), file);
3554 Alert::error(_("Could not read document"), text);
3558 // Check if emergency save file exists and is newer.
3559 FileName const e(s.absFileName() + ".emergency");
3561 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
3562 docstring const file = makeDisplayPath(s.absFileName(), 20);
3563 docstring const text =
3564 bformat(_("An emergency save of the document "
3566 "Recover emergency save?"), file);
3567 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
3568 _("&Recover"), _("&Load Original"),
3572 // the file is not saved if we load the emergency file.
3577 if ((res = readFile(e)) == success)
3578 str = _("Document was successfully recovered.");
3580 str = _("Document was NOT successfully recovered.");
3581 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3582 makeDisplayPath(e.absFileName()));
3584 if (!Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3585 _("&Remove"), _("&Keep it"))) {
3588 Alert::warning(_("Emergency file deleted"),
3589 _("Do not forget to save your file now!"), true);
3594 if (!Alert::prompt(_("Delete emergency file?"),
3595 _("Remove emergency file now?"), 1, 1,
3596 _("&Remove"), _("&Keep it")))
3604 // Now check if autosave file is newer.
3605 FileName const a(onlyPath(s.absFileName()) + '#' + onlyFileName(s.absFileName()) + '#');
3607 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
3608 docstring const file = makeDisplayPath(s.absFileName(), 20);
3609 docstring const text =
3610 bformat(_("The backup of the document "
3611 "%1$s is newer.\n\nLoad the "
3612 "backup instead?"), file);
3613 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
3614 _("&Load backup"), _("Load &original"),
3618 // the file is not saved if we load the autosave file.
3622 // Here we delete the autosave
3633 bool Buffer::loadLyXFile(FileName const & s)
3635 // If the file is not readable, we try to
3636 // retrieve the file from version control.
3637 if (!s.isReadableFile()
3638 && !LyXVC::file_not_found_hook(s))
3641 if (s.isReadableFile()){
3642 // InsetInfo needs to know if file is under VCS
3643 lyxvc().file_found_hook(s);
3644 if (readFileHelper(s)) {
3645 d->read_only = !s.isWritable();
3653 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3655 TeXErrors::Errors::const_iterator cit = terr.begin();
3656 TeXErrors::Errors::const_iterator end = terr.end();
3658 for (; cit != end; ++cit) {
3661 int errorRow = cit->error_in_line;
3662 bool found = d->texrow.getIdFromRow(errorRow, id_start,
3668 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
3669 } while (found && id_start == id_end && pos_start == pos_end);
3671 errorList.push_back(ErrorItem(cit->error_desc,
3672 cit->error_text, id_start, pos_start, pos_end));
3677 void Buffer::setBuffersForInsets() const
3679 inset().setBuffer(const_cast<Buffer &>(*this));
3683 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
3685 // Use the master text class also for child documents
3686 Buffer const * const master = masterBuffer();
3687 DocumentClass const & textclass = master->params().documentClass();
3689 // do this only if we are the top-level Buffer
3690 if (scope != UpdateMaster || master == this)
3691 checkBibInfoCache();
3693 // keep the buffers to be children in this set. If the call from the
3694 // master comes back we can see which of them were actually seen (i.e.
3695 // via an InsetInclude). The remaining ones in the set need still be updated.
3696 static std::set<Buffer const *> bufToUpdate;
3697 if (scope == UpdateMaster) {
3698 // If this is a child document start with the master
3699 if (master != this) {
3700 bufToUpdate.insert(this);
3701 master->updateBuffer(UpdateMaster, utype);
3702 // Do this here in case the master has no gui associated with it. Then,
3703 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3704 if (!master->d->gui_)
3707 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3708 if (bufToUpdate.find(this) == bufToUpdate.end())
3712 // start over the counters in the master
3713 textclass.counters().reset();
3716 // update will be done below for this buffer
3717 bufToUpdate.erase(this);
3719 // update all caches
3720 clearReferenceCache();
3723 Buffer & cbuf = const_cast<Buffer &>(*this);
3725 LASSERT(!text().paragraphs().empty(), /**/);
3728 ParIterator parit = cbuf.par_iterator_begin();
3729 updateBuffer(parit, utype);
3732 // TocBackend update will be done later.
3735 cbuf.tocBackend().update();
3736 if (scope == UpdateMaster)
3737 cbuf.structureChanged();
3741 static depth_type getDepth(DocIterator const & it)
3743 depth_type depth = 0;
3744 for (size_t i = 0 ; i < it.depth() ; ++i)
3745 if (!it[i].inset().inMathed())
3746 depth += it[i].paragraph().getDepth() + 1;
3747 // remove 1 since the outer inset does not count
3751 static depth_type getItemDepth(ParIterator const & it)
3753 Paragraph const & par = *it;
3754 LabelType const labeltype = par.layout().labeltype;
3756 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3759 // this will hold the lowest depth encountered up to now.
3760 depth_type min_depth = getDepth(it);
3761 ParIterator prev_it = it;
3764 --prev_it.top().pit();
3766 // start of nested inset: go to outer par
3768 if (prev_it.empty()) {
3769 // start of document: nothing to do
3774 // We search for the first paragraph with same label
3775 // that is not more deeply nested.
3776 Paragraph & prev_par = *prev_it;
3777 depth_type const prev_depth = getDepth(prev_it);
3778 if (labeltype == prev_par.layout().labeltype) {
3779 if (prev_depth < min_depth)
3780 return prev_par.itemdepth + 1;
3781 if (prev_depth == min_depth)
3782 return prev_par.itemdepth;
3784 min_depth = min(min_depth, prev_depth);
3785 // small optimization: if we are at depth 0, we won't
3786 // find anything else
3787 if (prev_depth == 0)
3793 static bool needEnumCounterReset(ParIterator const & it)
3795 Paragraph const & par = *it;
3796 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3797 depth_type const cur_depth = par.getDepth();
3798 ParIterator prev_it = it;
3799 while (prev_it.pit()) {
3800 --prev_it.top().pit();
3801 Paragraph const & prev_par = *prev_it;
3802 if (prev_par.getDepth() <= cur_depth)
3803 return prev_par.layout().labeltype != LABEL_ENUMERATE;
3805 // start of nested inset: reset
3810 // set the label of a paragraph. This includes the counters.
3811 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
3813 BufferParams const & bp = owner_->masterBuffer()->params();
3814 DocumentClass const & textclass = bp.documentClass();
3815 Paragraph & par = it.paragraph();
3816 Layout const & layout = par.layout();
3817 Counters & counters = textclass.counters();
3819 if (par.params().startOfAppendix()) {
3820 // FIXME: only the counter corresponding to toplevel
3821 // sectioning should be reset
3823 counters.appendix(true);
3825 par.params().appendix(counters.appendix());
3827 // Compute the item depth of the paragraph
3828 par.itemdepth = getItemDepth(it);
3830 if (layout.margintype == MARGIN_MANUAL
3831 || layout.latextype == LATEX_BIB_ENVIRONMENT) {
3832 if (par.params().labelWidthString().empty())
3833 par.params().labelWidthString(par.expandLabel(layout, bp));
3835 par.params().labelWidthString(docstring());
3838 switch(layout.labeltype) {
3840 if (layout.toclevel <= bp.secnumdepth
3841 && (layout.latextype != LATEX_ENVIRONMENT
3842 || it.text()->isFirstInSequence(it.pit()))) {
3843 counters.step(layout.counter, utype);
3844 par.params().labelString(
3845 par.expandLabel(layout, bp));
3847 par.params().labelString(docstring());
3850 case LABEL_ITEMIZE: {
3851 // At some point of time we should do something more
3852 // clever here, like:
3853 // par.params().labelString(
3854 // bp.user_defined_bullet(par.itemdepth).getText());
3855 // for now, use a simple hardcoded label
3856 docstring itemlabel;
3857 switch (par.itemdepth) {
3859 itemlabel = char_type(0x2022);
3862 itemlabel = char_type(0x2013);
3865 itemlabel = char_type(0x2217);
3868 itemlabel = char_type(0x2219); // or 0x00b7
3871 par.params().labelString(itemlabel);
3875 case LABEL_ENUMERATE: {
3876 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
3878 switch (par.itemdepth) {
3887 enumcounter += "iv";
3890 // not a valid enumdepth...
3894 // Maybe we have to reset the enumeration counter.
3895 if (needEnumCounterReset(it))
3896 counters.reset(enumcounter);
3897 counters.step(enumcounter, utype);
3899 string const & lang = par.getParLanguage(bp)->code();
3900 par.params().labelString(counters.theCounter(enumcounter, lang));
3905 case LABEL_SENSITIVE: {
3906 string const & type = counters.current_float();
3907 docstring full_label;
3909 full_label = owner_->B_("Senseless!!! ");
3911 docstring name = owner_->B_(textclass.floats().getType(type).name());
3912 if (counters.hasCounter(from_utf8(type))) {
3913 string const & lang = par.getParLanguage(bp)->code();
3914 counters.step(from_utf8(type), utype);
3915 full_label = bformat(from_ascii("%1$s %2$s:"),
3917 counters.theCounter(from_utf8(type), lang));
3919 full_label = bformat(from_ascii("%1$s #:"), name);
3921 par.params().labelString(full_label);
3925 case LABEL_NO_LABEL:
3926 par.params().labelString(docstring());
3930 case LABEL_TOP_ENVIRONMENT:
3931 case LABEL_CENTERED_TOP_ENVIRONMENT:
3934 par.params().labelString(par.expandLabel(layout, bp));
3940 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
3942 LASSERT(parit.pit() == 0, /**/);
3944 // set the position of the text in the buffer to be able
3945 // to resolve macros in it. This has nothing to do with
3946 // labels, but by putting it here we avoid implementing
3947 // a whole bunch of traversal routines just for this call.
3948 parit.text()->setMacrocontextPosition(parit);
3950 depth_type maxdepth = 0;
3951 pit_type const lastpit = parit.lastpit();
3952 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
3953 // reduce depth if necessary
3954 parit->params().depth(min(parit->params().depth(), maxdepth));
3955 maxdepth = parit->getMaxDepthAfter();
3957 if (utype == OutputUpdate) {
3958 // track the active counters
3959 // we have to do this for the master buffer, since the local
3960 // buffer isn't tracking anything.
3961 masterBuffer()->params().documentClass().counters().
3962 setActiveLayout(parit->layout());
3965 // set the counter for this paragraph
3966 d->setLabel(parit, utype);
3969 InsetList::const_iterator iit = parit->insetList().begin();
3970 InsetList::const_iterator end = parit->insetList().end();
3971 for (; iit != end; ++iit) {
3972 parit.pos() = iit->pos;
3973 iit->inset->updateBuffer(parit, utype);
3979 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
3980 WordLangTuple & word_lang, docstring_list & suggestions) const
3984 suggestions.clear();
3985 word_lang = WordLangTuple();
3986 // OK, we start from here.
3987 DocIterator const end = doc_iterator_end(this);
3988 for (; from != end; from.forwardPos()) {
3989 // We are only interested in text so remove the math CursorSlice.
3990 while (from.inMathed()) {
3994 // If from is at the end of the document (which is possible
3995 // when leaving the mathed) LyX will crash later.
3999 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4000 if (SpellChecker::misspelled(res)) {
4005 // Do not increase progress when from == to, otherwise the word
4006 // count will be wrong.
4016 bool Buffer::reload()
4020 removeAutosaveFile();
4021 // e.g., read-only status could have changed due to version control
4022 d->filename.refresh();
4023 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4025 bool const success = loadLyXFile(d->filename);
4031 message(bformat(_("Document %1$s reloaded."), disp_fn));
4033 message(bformat(_("Could not reload document %1$s."), disp_fn));
4036 thePreviews().removeLoader(*this);
4037 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
4038 thePreviews().generateBufferPreviews(*this);
4044 // FIXME We could do better here, but it is complicated. What would be
4045 // nice is to offer either (a) to save the child buffer to an appropriate
4046 // location, so that it would "move with the master", or else (b) to update
4047 // the InsetInclude so that it pointed to the same file. But (a) is a bit
4048 // complicated, because the code for this lives in GuiView.
4049 void Buffer::checkChildBuffers()
4051 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4052 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4053 for (; it != en; ++it) {
4054 DocIterator dit = it->second;
4055 Buffer * cbuf = const_cast<Buffer *>(it->first);
4056 if (!cbuf || !theBufferList().isLoaded(cbuf))
4058 Inset * inset = dit.nextInset();
4059 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4060 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4061 docstring const & incfile = inset_inc->getParam("filename");
4062 string oldloc = cbuf->absFileName();
4063 string newloc = makeAbsPath(to_utf8(incfile),
4064 onlyPath(absFileName())).absFileName();
4065 if (oldloc == newloc)
4067 // the location of the child file is incorrect.
4068 Alert::warning(_("Included File Invalid"),
4069 bformat(_("Saving this document to a new location has made the file:\n"
4071 "inaccessible. You will need to update the included filename."),
4072 from_utf8(oldloc)));
4074 inset_inc->setChildBuffer(0);
4076 // invalidate cache of children
4077 d->children_positions.clear();
4078 d->position_to_children.clear();