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/MacroTable.h"
76 #include "mathed/MathMacroTemplate.h"
77 #include "mathed/MathSupport.h"
79 #include "frontends/alert.h"
80 #include "frontends/Delegates.h"
81 #include "frontends/WorkAreaManager.h"
83 #include "graphics/Previews.h"
85 #include "support/lassert.h"
86 #include "support/convert.h"
87 #include "support/debug.h"
88 #include "support/docstring_list.h"
89 #include "support/ExceptionMessage.h"
90 #include "support/FileName.h"
91 #include "support/FileNameList.h"
92 #include "support/filetools.h"
93 #include "support/ForkedCalls.h"
94 #include "support/gettext.h"
95 #include "support/gzstream.h"
96 #include "support/lstrings.h"
97 #include "support/lyxalgo.h"
98 #include "support/os.h"
99 #include "support/Package.h"
100 #include "support/Path.h"
101 #include "support/Systemcall.h"
102 #include "support/textutils.h"
103 #include "support/types.h"
105 #include <boost/bind.hpp>
106 #include <boost/shared_ptr.hpp>
118 using namespace lyx::support;
122 namespace Alert = frontend::Alert;
123 namespace os = support::os;
127 // Do not remove the comment below, so we get merge conflict in
128 // independent branches. Instead add your own.
129 int const LYX_FORMAT = 378; // ps: rev insetinfo
131 typedef map<string, bool> DepClean;
132 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
134 void showPrintError(string const & name)
136 docstring str = bformat(_("Could not print the document %1$s.\n"
137 "Check that your printer is set up correctly."),
138 makeDisplayPath(name, 50));
139 Alert::error(_("Print document failed"), str);
144 class BufferSet : public std::set<Buffer const *> {};
149 Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
160 /// search for macro in local (buffer) table or in children
161 MacroData const * getBufferMacro(docstring const & name,
162 DocIterator const & pos) const;
164 /// Update macro table starting with position of it \param it in some
166 void updateMacros(DocIterator & it, DocIterator & scope);
168 void setLabel(ParIterator & it, UpdateType utype) const;
170 void collectRelatives(BufferSet & bufs) const;
172 /** If we have branches that use the file suffix
173 feature, return the file name with suffix appended.
175 support::FileName exportFileName() const;
182 mutable TexRow texrow;
184 /// need to regenerate .tex?
188 mutable bool lyx_clean;
190 /// is autosave needed?
191 mutable bool bak_clean;
193 /// is this a unnamed file (New...)?
199 /// name of the file the buffer is associated with.
202 /** Set to true only when the file is fully loaded.
203 * Used to prevent the premature generation of previews
204 * and by the citation inset.
206 bool file_fully_loaded;
209 mutable TocBackend toc_backend;
212 typedef pair<DocIterator, MacroData> ScopeMacro;
213 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
214 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
215 /// map from the macro name to the position map,
216 /// which maps the macro definition position to the scope and the MacroData.
217 NamePositionScopeMacroMap macros;
218 /// This seem to change the way Buffer::getMacro() works
219 mutable bool macro_lock;
221 /// positions of child buffers in the buffer
222 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
223 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
224 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
225 /// position of children buffers in this buffer
226 BufferPositionMap children_positions;
227 /// map from children inclusion positions to their scope and their buffer
228 PositionScopeBufferMap position_to_children;
230 /// Container for all sort of Buffer dependant errors.
231 map<string, ErrorList> errorLists;
233 /// timestamp and checksum used to test if the file has been externally
234 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
236 unsigned long checksum_;
239 frontend::WorkAreaManager * wa_;
241 frontend::GuiBufferDelegate * gui_;
246 /// A cache for the bibfiles (including bibfiles of loaded child
247 /// documents), needed for appropriate update of natbib labels.
248 mutable support::FileNameList bibfiles_cache_;
250 // FIXME The caching mechanism could be improved. At present, we have a
251 // cache for each Buffer, that caches all the bibliography info for that
252 // Buffer. A more efficient solution would be to have a global cache per
253 // file, and then to construct the Buffer's bibinfo from that.
254 /// A cache for bibliography info
255 mutable BiblioInfo bibinfo_;
256 /// whether the bibinfo cache is valid
257 bool bibinfo_cache_valid_;
258 /// Cache of timestamps of .bib files
259 map<FileName, time_t> bibfile_status_;
261 mutable RefCache ref_cache_;
263 /// our Text that should be wrapped in an InsetText
266 /// This is here to force the test to be done whenever parent_buffer
268 Buffer const * parent() const {
269 // if parent_buffer is not loaded, then it has been unloaded,
270 // which means that parent_buffer is an invalid pointer. So we
271 // set it to null in that case.
272 // however, the BufferList doesn't know about cloned buffers, so
273 // they will always be regarded as unloaded. in that case, we hope
275 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
277 return parent_buffer;
280 void setParent(Buffer const * pb) {
281 if (parent_buffer && pb && parent_buffer != pb)
282 LYXERR0("Warning: a buffer should not have two parents!");
286 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
287 /// This one is useful for preview detached in a thread.
288 Buffer const * cloned_buffer_;
291 /// So we can force access via the accessors.
292 mutable Buffer const * parent_buffer;
297 /// Creates the per buffer temporary directory
298 static FileName createBufferTmpDir()
301 // We are in our own directory. Why bother to mangle name?
302 // In fact I wrote this code to circumvent a problematic behaviour
303 // (bug?) of EMX mkstemp().
304 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
305 convert<string>(count++));
307 if (!tmpfl.createDirectory(0777)) {
308 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
309 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
310 from_utf8(tmpfl.absFilename())));
316 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
317 Buffer const * cloned_buffer)
318 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
319 read_only(readonly_), filename(file), file_fully_loaded(false),
320 toc_backend(owner), macro_lock(false), timestamp_(0),
321 checksum_(0), wa_(0), gui_(0), undo_(*owner), bibinfo_cache_valid_(false),
322 cloned_buffer_(cloned_buffer), parent_buffer(0)
324 if (!cloned_buffer_) {
325 temppath = createBufferTmpDir();
326 lyxvc.setBuffer(owner_);
328 wa_ = new frontend::WorkAreaManager;
331 temppath = cloned_buffer_->d->temppath;
332 file_fully_loaded = true;
333 params = cloned_buffer_->d->params;
334 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
335 bibinfo_ = cloned_buffer_->d->bibinfo_;
336 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
337 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
341 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
342 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
344 LYXERR(Debug::INFO, "Buffer::Buffer()");
346 d->inset = new InsetText(*cloned_buffer->d->inset);
347 d->inset->setBuffer(*this);
348 // FIXME: optimize this loop somewhat, maybe by creating a new
349 // general recursive Inset::setId().
350 DocIterator it = doc_iterator_begin(this);
351 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
352 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
353 it.paragraph().setId(cloned_it.paragraph().id());
355 d->inset = new InsetText(this);
356 d->inset->setAutoBreakRows(true);
357 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
363 LYXERR(Debug::INFO, "Buffer::~Buffer()");
364 // here the buffer should take care that it is
365 // saved properly, before it goes into the void.
367 // GuiView already destroyed
371 // No need to do additional cleanups for internal buffer.
376 // loop over children
377 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
378 Impl::BufferPositionMap::iterator end = d->children_positions.end();
379 for (; it != end; ++it) {
380 Buffer * child = const_cast<Buffer *>(it->first);
381 if (d->cloned_buffer_)
383 // The child buffer might have been closed already.
384 else if (theBufferList().isLoaded(child))
385 theBufferList().releaseChild(this, child);
389 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
390 msg += emergencyWrite();
391 Alert::warning(_("Attempting to close changed document!"), msg);
394 // clear references to children in macro tables
395 d->children_positions.clear();
396 d->position_to_children.clear();
398 if (!d->cloned_buffer_ && !d->temppath.destroyDirectory()) {
399 Alert::warning(_("Could not remove temporary directory"),
400 bformat(_("Could not remove the temporary directory %1$s"),
401 from_utf8(d->temppath.absFilename())));
404 // Remove any previewed LaTeX snippets associated with this buffer.
405 thePreviews().removeLoader(*this);
411 Buffer * Buffer::clone() const
413 Buffer * buffer_clone = new Buffer(fileName().absFilename(), false, this);
414 buffer_clone->d->macro_lock = true;
415 buffer_clone->d->children_positions.clear();
416 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
417 // math macro caches need to be rethought and simplified.
418 // I am not sure wether we should handle Buffer cloning here or in BufferList.
419 // Right now BufferList knows nothing about buffer clones.
420 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
421 Impl::BufferPositionMap::iterator end = d->children_positions.end();
422 for (; it != end; ++it) {
423 DocIterator dit = it->second.clone(buffer_clone);
424 dit.setBuffer(buffer_clone);
425 Buffer * child = const_cast<Buffer *>(it->first);
426 Buffer * child_clone = child->clone();
427 Inset * inset = dit.nextInset();
428 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
429 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
430 inset_inc->setChildBuffer(child_clone);
431 child_clone->d->setParent(buffer_clone);
432 buffer_clone->setChild(dit, child_clone);
434 buffer_clone->d->macro_lock = false;
439 bool Buffer::isClone() const
441 return d->cloned_buffer_;
445 void Buffer::changed(bool update_metrics) const
448 d->wa_->redrawAll(update_metrics);
452 frontend::WorkAreaManager & Buffer::workAreaManager() const
454 LASSERT(d->wa_, /**/);
459 Text & Buffer::text() const
461 return d->inset->text();
465 Inset & Buffer::inset() const
471 BufferParams & Buffer::params()
477 BufferParams const & Buffer::params() const
483 ParagraphList & Buffer::paragraphs()
485 return text().paragraphs();
489 ParagraphList const & Buffer::paragraphs() const
491 return text().paragraphs();
495 LyXVC & Buffer::lyxvc()
501 LyXVC const & Buffer::lyxvc() const
507 string const Buffer::temppath() const
509 return d->temppath.absFilename();
513 TexRow & Buffer::texrow()
519 TexRow const & Buffer::texrow() const
525 TocBackend & Buffer::tocBackend() const
527 return d->toc_backend;
531 Undo & Buffer::undo()
537 void Buffer::setChild(DocIterator const & dit, Buffer * child)
539 d->children_positions[child] = dit;
543 string Buffer::latexName(bool const no_path) const
545 FileName latex_name =
546 makeLatexName(d->exportFileName());
547 return no_path ? latex_name.onlyFileName()
548 : latex_name.absFilename();
552 FileName Buffer::Impl::exportFileName() const
554 docstring const branch_suffix =
555 params.branchlist().getFilenameSuffix();
556 if (branch_suffix.empty())
559 string const name = filename.onlyFileNameWithoutExt()
560 + to_utf8(branch_suffix);
561 FileName res(filename.onlyPath().absFilename() + "/" + name);
562 res.changeExtension(filename.extension());
568 string Buffer::logName(LogType * type) const
570 string const filename = latexName(false);
572 if (filename.empty()) {
578 string const path = temppath();
580 FileName const fname(addName(temppath(),
581 onlyFilename(changeExtension(filename,
584 // FIXME: how do we know this is the name of the build log?
585 FileName const bname(
586 addName(path, onlyFilename(
587 changeExtension(filename,
588 formats.extension(bufferFormat()) + ".out"))));
590 // Also consider the master buffer log file
591 FileName masterfname = fname;
593 if (masterBuffer() != this) {
594 string const mlogfile = masterBuffer()->logName(&mtype);
595 masterfname = FileName(mlogfile);
598 // If no Latex log or Build log is newer, show Build log
599 if (bname.exists() &&
600 ((!fname.exists() && !masterfname.exists())
601 || (fname.lastModified() < bname.lastModified()
602 && masterfname.lastModified() < bname.lastModified()))) {
603 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
606 return bname.absFilename();
607 // If we have a newer master file log or only a master log, show this
608 } else if (fname != masterfname
609 && (!fname.exists() && (masterfname.exists()
610 || fname.lastModified() < masterfname.lastModified()))) {
611 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
614 return masterfname.absFilename();
616 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
619 return fname.absFilename();
623 void Buffer::setReadonly(bool const flag)
625 if (d->read_only != flag) {
632 void Buffer::setFileName(string const & newfile)
634 d->filename = makeAbsPath(newfile);
635 setReadonly(d->filename.isReadOnly());
640 int Buffer::readHeader(Lexer & lex)
642 int unknown_tokens = 0;
644 int begin_header_line = -1;
646 // Initialize parameters that may be/go lacking in header:
647 params().branchlist().clear();
648 params().preamble.erase();
649 params().options.erase();
650 params().master.erase();
651 params().float_placement.erase();
652 params().paperwidth.erase();
653 params().paperheight.erase();
654 params().leftmargin.erase();
655 params().rightmargin.erase();
656 params().topmargin.erase();
657 params().bottommargin.erase();
658 params().headheight.erase();
659 params().headsep.erase();
660 params().footskip.erase();
661 params().columnsep.erase();
662 params().fontsCJK.erase();
663 params().listings_params.clear();
664 params().clearLayoutModules();
665 params().clearRemovedModules();
666 params().clearIncludedChildren();
667 params().pdfoptions().clear();
668 params().indiceslist().clear();
669 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
671 for (int i = 0; i < 4; ++i) {
672 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
673 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
676 ErrorList & errorList = d->errorLists["Parse"];
685 if (token == "\\end_header")
689 if (token == "\\begin_header") {
690 begin_header_line = line;
694 LYXERR(Debug::PARSER, "Handling document header token: `"
697 string unknown = params().readToken(lex, token, d->filename.onlyPath());
698 if (!unknown.empty()) {
699 if (unknown[0] != '\\' && token == "\\textclass") {
700 Alert::warning(_("Unknown document class"),
701 bformat(_("Using the default document class, because the "
702 "class %1$s is unknown."), from_utf8(unknown)));
705 docstring const s = bformat(_("Unknown token: "
709 errorList.push_back(ErrorItem(_("Document header error"),
714 if (begin_header_line) {
715 docstring const s = _("\\begin_header is missing");
716 errorList.push_back(ErrorItem(_("Document header error"),
720 params().makeDocumentClass();
722 return unknown_tokens;
727 // changed to be public and have one parameter
728 // Returns true if "\end_document" is not read (Asger)
729 bool Buffer::readDocument(Lexer & lex)
731 ErrorList & errorList = d->errorLists["Parse"];
734 if (!lex.checkFor("\\begin_document")) {
735 docstring const s = _("\\begin_document is missing");
736 errorList.push_back(ErrorItem(_("Document header error"),
740 // we are reading in a brand new document
741 LASSERT(paragraphs().empty(), /**/);
745 if (params().outputChanges) {
746 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
747 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
748 LaTeXFeatures::isAvailable("xcolor");
750 if (!dvipost && !xcolorulem) {
751 Alert::warning(_("Changes not shown in LaTeX output"),
752 _("Changes will not be highlighted in LaTeX output, "
753 "because neither dvipost nor xcolor/ulem are installed.\n"
754 "Please install these packages or redefine "
755 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
756 } else if (!xcolorulem) {
757 Alert::warning(_("Changes not shown in LaTeX output"),
758 _("Changes will not be highlighted in LaTeX output "
759 "when using pdflatex, because xcolor and ulem are not installed.\n"
760 "Please install both packages or redefine "
761 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
765 if (!params().master.empty()) {
766 FileName const master_file = makeAbsPath(params().master,
767 onlyPath(absFileName()));
768 if (isLyXFilename(master_file.absFilename())) {
770 checkAndLoadLyXFile(master_file, true);
772 // necessary e.g. after a reload
773 // to re-register the child (bug 5873)
774 // FIXME: clean up updateMacros (here, only
775 // child registering is needed).
776 master->updateMacros();
777 // set master as master buffer, but only
778 // if we are a real child
779 if (master->isChild(this))
781 // if the master is not fully loaded
782 // it is probably just loading this
783 // child. No warning needed then.
784 else if (master->isFullyLoaded())
785 LYXERR0("The master '"
787 << "' assigned to this document ("
789 << ") does not include "
790 "this document. Ignoring the master assignment.");
795 // assure we have a default index
796 params().indiceslist().addDefault(B_("Index"));
799 bool const res = text().read(lex, errorList, d->inset);
803 updateMacroInstances();
808 bool Buffer::readString(string const & s)
810 params().compressed = false;
812 // remove dummy empty par
813 paragraphs().clear();
817 FileName const name = FileName::tempName("Buffer_readString");
818 switch (readFile(lex, name, true)) {
822 // We need to call lyx2lyx, so write the input to a file
823 ofstream os(name.toFilesystemEncoding().c_str());
826 return readFile(name);
836 bool Buffer::readFile(FileName const & filename)
838 FileName fname(filename);
840 params().compressed = fname.isZippedFile();
842 // remove dummy empty par
843 paragraphs().clear();
846 if (readFile(lex, fname) != success)
853 bool Buffer::isFullyLoaded() const
855 return d->file_fully_loaded;
859 void Buffer::setFullyLoaded(bool value)
861 d->file_fully_loaded = value;
865 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
868 LASSERT(!filename.empty(), /**/);
870 // the first (non-comment) token _must_ be...
871 if (!lex.checkFor("\\lyxformat")) {
872 Alert::error(_("Document format failure"),
873 bformat(_("%1$s is not a readable LyX document."),
874 from_utf8(filename.absFilename())));
880 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
881 // if present remove ".," from string.
882 size_t dot = tmp_format.find_first_of(".,");
883 //lyxerr << " dot found at " << dot << endl;
884 if (dot != string::npos)
885 tmp_format.erase(dot, 1);
886 int const file_format = convert<int>(tmp_format);
887 //lyxerr << "format: " << file_format << endl;
889 // save timestamp and checksum of the original disk file, making sure
890 // to not overwrite them with those of the file created in the tempdir
891 // when it has to be converted to the current format.
893 // Save the timestamp and checksum of disk file. If filename is an
894 // emergency file, save the timestamp and checksum of the original lyx file
895 // because isExternallyModified will check for this file. (BUG4193)
896 string diskfile = filename.absFilename();
897 if (suffixIs(diskfile, ".emergency"))
898 diskfile = diskfile.substr(0, diskfile.size() - 10);
899 saveCheckSum(FileName(diskfile));
902 if (file_format != LYX_FORMAT) {
905 // lyx2lyx would fail
908 FileName const tmpfile = FileName::tempName("Buffer_readFile");
909 if (tmpfile.empty()) {
910 Alert::error(_("Conversion failed"),
911 bformat(_("%1$s is from a different"
912 " version of LyX, but a temporary"
913 " file for converting it could"
915 from_utf8(filename.absFilename())));
918 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
919 if (lyx2lyx.empty()) {
920 Alert::error(_("Conversion script not found"),
921 bformat(_("%1$s is from a different"
922 " version of LyX, but the"
923 " conversion script lyx2lyx"
924 " could not be found."),
925 from_utf8(filename.absFilename())));
928 ostringstream command;
929 command << os::python()
930 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
931 << " -t " << convert<string>(LYX_FORMAT)
932 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
933 << ' ' << quoteName(filename.toSafeFilesystemEncoding());
934 string const command_str = command.str();
936 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
938 cmd_ret const ret = runCommand(command_str);
939 if (ret.first != 0) {
940 if (file_format < LYX_FORMAT)
941 Alert::error(_("Conversion script failed"),
942 bformat(_("%1$s is from an older version"
943 " of LyX, but the lyx2lyx script"
944 " failed to convert it."),
945 from_utf8(filename.absFilename())));
947 Alert::error(_("Conversion script failed"),
948 bformat(_("%1$s is from a newer version"
949 " of LyX and cannot be converted by the"
951 from_utf8(filename.absFilename())));
954 bool const ret = readFile(tmpfile);
955 // Do stuff with tmpfile name and buffer name here.
956 return ret ? success : failure;
961 if (readDocument(lex)) {
962 Alert::error(_("Document format failure"),
963 bformat(_("%1$s ended unexpectedly, which means"
964 " that it is probably corrupted."),
965 from_utf8(filename.absFilename())));
969 d->file_fully_loaded = true;
974 // Should probably be moved to somewhere else: BufferView? GuiView?
975 bool Buffer::save() const
977 // We don't need autosaves in the immediate future. (Asger)
978 resetAutosaveTimers();
981 bool madeBackup = false;
983 // make a backup if the file already exists
984 if (lyxrc.make_backup && fileName().exists()) {
985 backupName = FileName(absFileName() + '~');
986 if (!lyxrc.backupdir_path.empty()) {
987 string const mangledName =
988 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
989 backupName = FileName(addName(lyxrc.backupdir_path,
992 if (fileName().copyTo(backupName)) {
995 Alert::error(_("Backup failure"),
996 bformat(_("Cannot create backup file %1$s.\n"
997 "Please check whether the directory exists and is writeable."),
998 from_utf8(backupName.absFilename())));
999 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1003 // ask if the disk file has been externally modified (use checksum method)
1004 if (fileName().exists() && isExternallyModified(checksum_method)) {
1005 docstring const file = makeDisplayPath(absFileName(), 20);
1006 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
1007 "you want to overwrite this file?"), file);
1008 int const ret = Alert::prompt(_("Overwrite modified file?"),
1009 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1014 if (writeFile(d->filename)) {
1018 // Saving failed, so backup is not backup
1020 backupName.moveTo(d->filename);
1026 bool Buffer::writeFile(FileName const & fname) const
1028 if (d->read_only && fname == d->filename)
1031 bool retval = false;
1033 docstring const str = bformat(_("Saving document %1$s..."),
1034 makeDisplayPath(fname.absFilename()));
1037 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1039 if (params().compressed) {
1040 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1041 retval = ofs && write(ofs);
1043 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1044 retval = ofs && write(ofs);
1048 message(str + _(" could not write file!"));
1052 removeAutosaveFile();
1054 saveCheckSum(d->filename);
1055 message(str + _(" done."));
1061 docstring Buffer::emergencyWrite()
1063 // No need to save if the buffer has not changed.
1067 string const doc = isUnnamed() ? onlyFilename(absFileName()) : absFileName();
1069 docstring user_message = bformat(
1070 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1072 // We try to save three places:
1073 // 1) Same place as document. Unless it is an unnamed doc.
1075 string s = absFileName();
1078 if (writeFile(FileName(s))) {
1080 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1081 return user_message;
1083 user_message += _(" Save failed! Trying again...\n");
1087 // 2) In HOME directory.
1088 string s = addName(package().home_dir().absFilename(), absFileName());
1090 lyxerr << ' ' << s << endl;
1091 if (writeFile(FileName(s))) {
1093 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1094 return user_message;
1097 user_message += _(" Save failed! Trying yet again...\n");
1099 // 3) In "/tmp" directory.
1100 // MakeAbsPath to prepend the current
1101 // drive letter on OS/2
1102 s = addName(package().temp_dir().absFilename(), absFileName());
1104 lyxerr << ' ' << s << endl;
1105 if (writeFile(FileName(s))) {
1107 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1108 return user_message;
1111 user_message += _(" Save failed! Bummer. Document is lost.");
1114 return user_message;
1118 bool Buffer::write(ostream & ofs) const
1121 // Use the standard "C" locale for file output.
1122 ofs.imbue(locale::classic());
1125 // The top of the file should not be written by params().
1127 // write out a comment in the top of the file
1128 ofs << "#LyX " << lyx_version
1129 << " created this file. For more info see http://www.lyx.org/\n"
1130 << "\\lyxformat " << LYX_FORMAT << "\n"
1131 << "\\begin_document\n";
1133 /// For each author, set 'used' to true if there is a change
1134 /// by this author in the document; otherwise set it to 'false'.
1135 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1136 AuthorList::Authors::const_iterator a_end = params().authors().end();
1137 for (; a_it != a_end; ++a_it)
1138 a_it->setUsed(false);
1140 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1141 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1142 for ( ; it != end; ++it)
1143 it->checkAuthors(params().authors());
1145 // now write out the buffer parameters.
1146 ofs << "\\begin_header\n";
1147 params().writeFile(ofs);
1148 ofs << "\\end_header\n";
1151 ofs << "\n\\begin_body\n";
1153 ofs << "\n\\end_body\n";
1155 // Write marker that shows file is complete
1156 ofs << "\\end_document" << endl;
1158 // Shouldn't really be needed....
1161 // how to check if close went ok?
1162 // Following is an attempt... (BE 20001011)
1164 // good() returns false if any error occured, including some
1165 // formatting error.
1166 // bad() returns true if something bad happened in the buffer,
1167 // which should include file system full errors.
1172 lyxerr << "File was not closed properly." << endl;
1179 bool Buffer::makeLaTeXFile(FileName const & fname,
1180 string const & original_path,
1181 OutputParams const & runparams_in,
1182 bool output_preamble, bool output_body) const
1184 OutputParams runparams = runparams_in;
1185 if (params().useXetex)
1186 runparams.flavor = OutputParams::XETEX;
1188 string const encoding = runparams.encoding->iconvName();
1189 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1192 try { ofs.reset(encoding); }
1193 catch (iconv_codecvt_facet_exception & e) {
1194 lyxerr << "Caught iconv exception: " << e.what() << endl;
1195 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1196 "verify that the support software for your encoding (%1$s) is "
1197 "properly installed"), from_ascii(encoding)));
1200 if (!openFileWrite(ofs, fname))
1203 //TexStream ts(ofs.rdbuf(), &texrow());
1204 ErrorList & errorList = d->errorLists["Export"];
1206 bool failed_export = false;
1209 writeLaTeXSource(ofs, original_path,
1210 runparams, output_preamble, output_body);
1212 catch (EncodingException & e) {
1213 odocstringstream ods;
1214 ods.put(e.failed_char);
1216 oss << "0x" << hex << e.failed_char << dec;
1217 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1218 " (code point %2$s)"),
1219 ods.str(), from_utf8(oss.str()));
1220 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1221 "representable in the chosen encoding.\n"
1222 "Changing the document encoding to utf8 could help."),
1223 e.par_id, e.pos, e.pos + 1));
1224 failed_export = true;
1226 catch (iconv_codecvt_facet_exception & e) {
1227 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1228 _(e.what()), -1, 0, 0));
1229 failed_export = true;
1231 catch (exception const & e) {
1232 errorList.push_back(ErrorItem(_("conversion failed"),
1233 _(e.what()), -1, 0, 0));
1234 failed_export = true;
1237 lyxerr << "Caught some really weird exception..." << endl;
1243 failed_export = true;
1244 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1248 return !failed_export;
1252 void Buffer::writeLaTeXSource(odocstream & os,
1253 string const & original_path,
1254 OutputParams const & runparams_in,
1255 bool const output_preamble, bool const output_body) const
1257 // The child documents, if any, shall be already loaded at this point.
1259 OutputParams runparams = runparams_in;
1261 // Classify the unicode characters appearing in math insets
1262 Encodings::initUnicodeMath(*this);
1264 // validate the buffer.
1265 LYXERR(Debug::LATEX, " Validating buffer...");
1266 LaTeXFeatures features(*this, params(), runparams);
1268 LYXERR(Debug::LATEX, " Buffer validation done.");
1270 // The starting paragraph of the coming rows is the
1271 // first paragraph of the document. (Asger)
1272 if (output_preamble && runparams.nice) {
1273 os << "%% LyX " << lyx_version << " created this file. "
1274 "For more info, see http://www.lyx.org/.\n"
1275 "%% Do not edit unless you really know what "
1277 d->texrow.newline();
1278 d->texrow.newline();
1280 LYXERR(Debug::INFO, "lyx document header finished");
1282 // Don't move this behind the parent_buffer=0 code below,
1283 // because then the macros will not get the right "redefinition"
1284 // flag as they don't see the parent macros which are output before.
1287 // fold macros if possible, still with parent buffer as the
1288 // macros will be put in the prefix anyway.
1289 updateMacroInstances();
1291 // There are a few differences between nice LaTeX and usual files:
1292 // usual is \batchmode and has a
1293 // special input@path to allow the including of figures
1294 // with either \input or \includegraphics (what figinsets do).
1295 // input@path is set when the actual parameter
1296 // original_path is set. This is done for usual tex-file, but not
1297 // for nice-latex-file. (Matthias 250696)
1298 // Note that input@path is only needed for something the user does
1299 // in the preamble, included .tex files or ERT, files included by
1300 // LyX work without it.
1301 if (output_preamble) {
1302 if (!runparams.nice) {
1303 // code for usual, NOT nice-latex-file
1304 os << "\\batchmode\n"; // changed
1305 // from \nonstopmode
1306 d->texrow.newline();
1308 if (!original_path.empty()) {
1310 // We don't know the encoding of inputpath
1311 docstring const inputpath = from_utf8(latex_path(original_path));
1312 docstring uncodable_glyphs;
1313 Encoding const * const enc = runparams.encoding;
1315 for (size_t n = 0; n < inputpath.size(); ++n) {
1316 docstring const glyph =
1317 docstring(1, inputpath[n]);
1318 if (enc->latexChar(inputpath[n], true) != glyph) {
1319 LYXERR0("Uncodable character '"
1321 << "' in input path!");
1322 uncodable_glyphs += glyph;
1327 // warn user if we found uncodable glyphs.
1328 if (!uncodable_glyphs.empty()) {
1329 frontend::Alert::warning(_("Uncodable character in file path"),
1330 support::bformat(_("The path of your document\n"
1332 "contains glyphs that are unknown in the\n"
1333 "current document encoding (namely %2$s).\n"
1334 "This will likely result in incomplete output.\n\n"
1335 "Chose an appropriate document encoding (such as utf8)\n"
1336 "or change the file path name."), inputpath, uncodable_glyphs));
1338 os << "\\makeatletter\n"
1339 << "\\def\\input@path{{"
1340 << inputpath << "/}}\n"
1341 << "\\makeatother\n";
1342 d->texrow.newline();
1343 d->texrow.newline();
1344 d->texrow.newline();
1348 // get parent macros (if this buffer has a parent) which will be
1349 // written at the document begin further down.
1350 MacroSet parentMacros;
1351 listParentMacros(parentMacros, features);
1353 // Write the preamble
1354 runparams.use_babel = params().writeLaTeX(os, features,
1356 d->filename.onlyPath());
1358 runparams.use_japanese = features.isRequired("japanese");
1364 os << "\\begin{document}\n";
1365 d->texrow.newline();
1367 // output the parent macros
1368 MacroSet::iterator it = parentMacros.begin();
1369 MacroSet::iterator end = parentMacros.end();
1370 for (; it != end; ++it) {
1371 int num_lines = (*it)->write(os, true);
1372 d->texrow.newlines(num_lines);
1375 } // output_preamble
1377 d->texrow.start(paragraphs().begin()->id(), 0);
1379 LYXERR(Debug::INFO, "preamble finished, now the body.");
1381 // if we are doing a real file with body, even if this is the
1382 // child of some other buffer, let's cut the link here.
1383 // This happens for example if only a child document is printed.
1384 Buffer const * save_parent = 0;
1385 if (output_preamble) {
1386 save_parent = d->parent();
1391 latexParagraphs(*this, text(), os, d->texrow, runparams);
1393 // Restore the parenthood if needed
1394 if (output_preamble)
1395 d->setParent(save_parent);
1397 // add this just in case after all the paragraphs
1399 d->texrow.newline();
1401 if (output_preamble) {
1402 os << "\\end{document}\n";
1403 d->texrow.newline();
1404 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1406 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1408 runparams_in.encoding = runparams.encoding;
1410 // Just to be sure. (Asger)
1411 d->texrow.newline();
1413 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1414 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1418 bool Buffer::isLatex() const
1420 return params().documentClass().outputType() == LATEX;
1424 bool Buffer::isLiterate() const
1426 return params().documentClass().outputType() == LITERATE;
1430 bool Buffer::isDocBook() const
1432 return params().documentClass().outputType() == DOCBOOK;
1436 void Buffer::makeDocBookFile(FileName const & fname,
1437 OutputParams const & runparams,
1438 bool const body_only) const
1440 LYXERR(Debug::LATEX, "makeDocBookFile...");
1443 if (!openFileWrite(ofs, fname))
1446 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1450 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1454 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1455 OutputParams const & runparams,
1456 bool const only_body) const
1458 LaTeXFeatures features(*this, params(), runparams);
1463 DocumentClass const & tclass = params().documentClass();
1464 string const top_element = tclass.latexname();
1467 if (runparams.flavor == OutputParams::XML)
1468 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1471 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1474 if (! tclass.class_header().empty())
1475 os << from_ascii(tclass.class_header());
1476 else if (runparams.flavor == OutputParams::XML)
1477 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1478 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1480 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1482 docstring preamble = from_utf8(params().preamble);
1483 if (runparams.flavor != OutputParams::XML ) {
1484 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1485 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1486 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1487 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1490 string const name = runparams.nice
1491 ? changeExtension(absFileName(), ".sgml") : fname;
1492 preamble += features.getIncludedFiles(name);
1493 preamble += features.getLyXSGMLEntities();
1495 if (!preamble.empty()) {
1496 os << "\n [ " << preamble << " ]";
1501 string top = top_element;
1503 if (runparams.flavor == OutputParams::XML)
1504 top += params().language->code();
1506 top += params().language->code().substr(0, 2);
1509 if (!params().options.empty()) {
1511 top += params().options;
1514 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1515 << " file was created by LyX " << lyx_version
1516 << "\n See http://www.lyx.org/ for more information -->\n";
1518 params().documentClass().counters().reset();
1522 sgml::openTag(os, top);
1524 docbookParagraphs(text(), *this, os, runparams);
1525 sgml::closeTag(os, top_element);
1529 void Buffer::makeLyXHTMLFile(FileName const & fname,
1530 OutputParams const & runparams,
1531 bool const body_only) const
1533 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1536 if (!openFileWrite(ofs, fname))
1539 writeLyXHTMLSource(ofs, runparams, body_only);
1543 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1547 void Buffer::writeLyXHTMLSource(odocstream & os,
1548 OutputParams const & runparams,
1549 bool const only_body) const
1551 LaTeXFeatures features(*this, params(), runparams);
1553 updateBuffer(UpdateMaster, OutputUpdate);
1554 checkBibInfoCache();
1555 d->bibinfo_.makeCitationLabels(*this);
1557 updateMacroInstances();
1560 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1561 os << "<!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";
1562 // FIXME Language should be set properly.
1563 os << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n";
1565 // FIXME Presumably need to set this right
1566 os << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1567 os << "<title>" << features.htmlTitle() << "</title>\n";
1569 os << "\n<!-- Text Class Preamble -->\n"
1570 << features.getTClassHTMLPreamble()
1571 << "\n<!-- Premable Snippets -->\n"
1572 << from_utf8(features.getPreambleSnippets());
1574 os << "\n<!-- Layout-provided Styles -->\n";
1575 docstring const styleinfo = features.getTClassHTMLStyles();
1576 if (!styleinfo.empty()) {
1577 os << "<style type='text/css'>\n"
1581 os << "</head>\n<body>\n";
1585 params().documentClass().counters().reset();
1586 xhtmlParagraphs(text(), *this, xs, runparams);
1588 os << "</body>\n</html>\n";
1592 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1593 // Other flags: -wall -v0 -x
1594 int Buffer::runChktex()
1598 // get LaTeX-Filename
1599 FileName const path(temppath());
1600 string const name = addName(path.absFilename(), latexName());
1601 string const org_path = filePath();
1603 PathChanger p(path); // path to LaTeX file
1604 message(_("Running chktex..."));
1606 // Generate the LaTeX file if neccessary
1607 OutputParams runparams(¶ms().encoding());
1608 runparams.flavor = OutputParams::LATEX;
1609 runparams.nice = false;
1610 runparams.linelen = lyxrc.plaintext_linelen;
1611 makeLaTeXFile(FileName(name), org_path, runparams);
1614 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1615 int const res = chktex.run(terr); // run chktex
1618 Alert::error(_("chktex failure"),
1619 _("Could not run chktex successfully."));
1620 } else if (res > 0) {
1621 ErrorList & errlist = d->errorLists["ChkTeX"];
1623 bufferErrors(terr, errlist);
1634 void Buffer::validate(LaTeXFeatures & features) const
1636 params().validate(features);
1640 for_each(paragraphs().begin(), paragraphs().end(),
1641 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1643 if (lyxerr.debugging(Debug::LATEX)) {
1644 features.showStruct();
1649 void Buffer::getLabelList(vector<docstring> & list) const
1651 // If this is a child document, use the parent's list instead.
1652 Buffer const * const pbuf = d->parent();
1654 pbuf->getLabelList(list);
1659 Toc & toc = d->toc_backend.toc("label");
1660 TocIterator toc_it = toc.begin();
1661 TocIterator end = toc.end();
1662 for (; toc_it != end; ++toc_it) {
1663 if (toc_it->depth() == 0)
1664 list.push_back(toc_it->str());
1669 void Buffer::updateBibfilesCache(UpdateScope scope) const
1671 // If this is a child document, use the parent's cache instead.
1672 Buffer const * const pbuf = d->parent();
1673 if (pbuf && scope != UpdateChildOnly) {
1674 pbuf->updateBibfilesCache();
1678 d->bibfiles_cache_.clear();
1679 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1680 if (it->lyxCode() == BIBTEX_CODE) {
1681 InsetBibtex const & inset =
1682 static_cast<InsetBibtex const &>(*it);
1683 support::FileNameList const bibfiles = inset.getBibFiles();
1684 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1687 } else if (it->lyxCode() == INCLUDE_CODE) {
1688 InsetInclude & inset =
1689 static_cast<InsetInclude &>(*it);
1690 inset.updateBibfilesCache();
1691 support::FileNameList const & bibfiles =
1692 inset.getBibfilesCache();
1693 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1698 // the bibinfo cache is now invalid
1699 d->bibinfo_cache_valid_ = false;
1703 void Buffer::invalidateBibinfoCache()
1705 d->bibinfo_cache_valid_ = false;
1709 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1711 // If this is a child document, use the parent's cache instead.
1712 Buffer const * const pbuf = d->parent();
1713 if (pbuf && scope != UpdateChildOnly)
1714 return pbuf->getBibfilesCache();
1716 // We update the cache when first used instead of at loading time.
1717 if (d->bibfiles_cache_.empty())
1718 const_cast<Buffer *>(this)->updateBibfilesCache(scope);
1720 return d->bibfiles_cache_;
1724 BiblioInfo const & Buffer::masterBibInfo() const
1726 // if this is a child document and the parent is already loaded
1727 // use the parent's list instead [ale990412]
1728 Buffer const * const tmp = masterBuffer();
1731 return tmp->masterBibInfo();
1732 return localBibInfo();
1736 BiblioInfo const & Buffer::localBibInfo() const
1742 void Buffer::checkBibInfoCache() const
1744 support::FileNameList const & bibfilesCache = getBibfilesCache();
1745 // compare the cached timestamps with the actual ones.
1746 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1747 support::FileNameList::const_iterator en = bibfilesCache.end();
1748 for (; ei != en; ++ ei) {
1749 time_t lastw = ei->lastModified();
1750 time_t prevw = d->bibfile_status_[*ei];
1751 if (lastw != prevw) {
1752 d->bibinfo_cache_valid_ = false;
1753 d->bibfile_status_[*ei] = lastw;
1757 if (!d->bibinfo_cache_valid_) {
1758 d->bibinfo_.clear();
1759 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1760 it->fillWithBibKeys(d->bibinfo_, it);
1761 d->bibinfo_cache_valid_ = true;
1766 bool Buffer::isDepClean(string const & name) const
1768 DepClean::const_iterator const it = d->dep_clean.find(name);
1769 if (it == d->dep_clean.end())
1775 void Buffer::markDepClean(string const & name)
1777 d->dep_clean[name] = true;
1781 bool Buffer::isExportableFormat(string const & format) const
1783 typedef vector<Format const *> Formats;
1785 formats = exportableFormats(true);
1786 Formats::const_iterator fit = formats.begin();
1787 Formats::const_iterator end = formats.end();
1788 for (; fit != end ; ++fit) {
1789 if ((*fit)->name() == format)
1796 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1799 // FIXME? if there is an Buffer LFUN that can be dispatched even
1800 // if internal, put a switch '(cmd.action)' here.
1806 switch (cmd.action) {
1808 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1809 flag.setOnOff(isReadonly());
1812 // FIXME: There is need for a command-line import.
1813 //case LFUN_BUFFER_IMPORT:
1815 case LFUN_BUFFER_AUTO_SAVE:
1818 case LFUN_BUFFER_EXPORT_CUSTOM:
1819 // FIXME: Nothing to check here?
1822 case LFUN_BUFFER_EXPORT: {
1823 docstring const arg = cmd.argument();
1824 enable = arg == "custom" || isExportable(to_utf8(arg));
1826 flag.message(bformat(
1827 _("Don't know how to export to format: %1$s"), arg));
1831 case LFUN_BUFFER_CHKTEX:
1832 enable = isLatex() && !lyxrc.chktex_command.empty();
1835 case LFUN_BUILD_PROGRAM:
1836 enable = isExportable("program");
1839 case LFUN_BRANCH_ACTIVATE:
1840 case LFUN_BRANCH_DEACTIVATE: {
1841 BranchList const & branchList = params().branchlist();
1842 docstring const branchName = cmd.argument();
1843 enable = !branchName.empty() && branchList.find(branchName);
1847 case LFUN_BRANCH_ADD:
1848 case LFUN_BRANCHES_RENAME:
1849 case LFUN_BUFFER_PRINT:
1850 // if no Buffer is present, then of course we won't be called!
1853 case LFUN_BUFFER_LANGUAGE:
1854 enable = !isReadonly();
1860 flag.setEnabled(enable);
1865 void Buffer::dispatch(string const & command, DispatchResult & result)
1867 return dispatch(lyxaction.lookupFunc(command), result);
1871 // NOTE We can end up here even if we have no GUI, because we are called
1872 // by LyX::exec to handled command-line requests. So we may need to check
1873 // whether we have a GUI or not. The boolean use_gui holds this information.
1874 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
1877 // FIXME? if there is an Buffer LFUN that can be dispatched even
1878 // if internal, put a switch '(cmd.action)' here.
1879 dr.dispatched(false);
1882 string const argument = to_utf8(func.argument());
1883 // We'll set this back to false if need be.
1884 bool dispatched = true;
1885 undo().beginUndoGroup();
1887 switch (func.action) {
1888 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1889 if (lyxvc().inUse())
1890 lyxvc().toggleReadOnly();
1892 setReadonly(!isReadonly());
1895 case LFUN_BUFFER_EXPORT: {
1896 bool success = doExport(argument, false, false);
1897 dr.setError(!success);
1899 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
1904 case LFUN_BUILD_PROGRAM:
1905 doExport("program", true, false);
1908 case LFUN_BUFFER_CHKTEX:
1912 case LFUN_BUFFER_EXPORT_CUSTOM: {
1914 string command = split(argument, format_name, ' ');
1915 Format const * format = formats.getFormat(format_name);
1917 lyxerr << "Format \"" << format_name
1918 << "\" not recognized!"
1923 // The name of the file created by the conversion process
1926 // Output to filename
1927 if (format->name() == "lyx") {
1928 string const latexname = latexName(false);
1929 filename = changeExtension(latexname,
1930 format->extension());
1931 filename = addName(temppath(), filename);
1933 if (!writeFile(FileName(filename)))
1937 doExport(format_name, true, false, filename);
1940 // Substitute $$FName for filename
1941 if (!contains(command, "$$FName"))
1942 command = "( " + command + " ) < $$FName";
1943 command = subst(command, "$$FName", filename);
1945 // Execute the command in the background
1947 call.startscript(Systemcall::DontWait, command);
1951 // FIXME: There is need for a command-line import.
1953 case LFUN_BUFFER_IMPORT:
1958 case LFUN_BUFFER_AUTO_SAVE:
1962 case LFUN_BRANCH_ADD: {
1963 docstring const branch_name = func.argument();
1964 if (branch_name.empty()) {
1968 BranchList & branch_list = params().branchlist();
1969 Branch * branch = branch_list.find(branch_name);
1971 LYXERR0("Branch " << branch_name << " already exists.");
1973 docstring const msg =
1974 bformat(_("Branch \"%1$s\" already exists."), branch_name);
1977 branch_list.add(branch_name);
1978 branch = branch_list.find(branch_name);
1979 string const x11hexname = X11hexname(branch->color());
1980 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
1981 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
1983 dr.update(Update::Force);
1988 case LFUN_BRANCH_ACTIVATE:
1989 case LFUN_BRANCH_DEACTIVATE: {
1990 BranchList & branchList = params().branchlist();
1991 docstring const branchName = func.argument();
1992 // the case without a branch name is handled elsewhere
1993 if (branchName.empty()) {
1997 Branch * branch = branchList.find(branchName);
1999 LYXERR0("Branch " << branchName << " does not exist.");
2001 docstring const msg =
2002 bformat(_("Branch \"%1$s\" does not exist."), branchName);
2005 branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
2007 dr.update(Update::Force);
2012 case LFUN_BRANCHES_RENAME: {
2013 if (func.argument().empty())
2016 docstring const oldname = from_utf8(func.getArg(0));
2017 docstring const newname = from_utf8(func.getArg(1));
2018 InsetIterator it = inset_iterator_begin(inset());
2019 InsetIterator const end = inset_iterator_end(inset());
2020 bool success = false;
2021 for (; it != end; ++it) {
2022 if (it->lyxCode() == BRANCH_CODE) {
2023 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2024 if (ins.branch() == oldname) {
2025 undo().recordUndo(it);
2026 ins.rename(newname);
2031 if (it->lyxCode() == INCLUDE_CODE) {
2032 // get buffer of external file
2033 InsetInclude const & ins =
2034 static_cast<InsetInclude const &>(*it);
2035 Buffer * child = ins.getChildBuffer();
2038 child->dispatch(func, dr);
2043 dr.update(Update::Force);
2047 case LFUN_BUFFER_PRINT: {
2048 // we'll assume there's a problem until we succeed
2050 string target = func.getArg(0);
2051 string target_name = func.getArg(1);
2052 string command = func.getArg(2);
2055 || target_name.empty()
2056 || command.empty()) {
2057 LYXERR0("Unable to parse " << func.argument());
2058 docstring const msg =
2059 bformat(_("Unable to parse \"%1$s\""), func.argument());
2063 if (target != "printer" && target != "file") {
2064 LYXERR0("Unrecognized target \"" << target << '"');
2065 docstring const msg =
2066 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2071 bool const update_unincluded =
2072 params().maintain_unincluded_children
2073 && !params().getIncludedChildren().empty();
2074 if (!doExport("dvi", true, update_unincluded)) {
2075 showPrintError(absFileName());
2076 dr.setMessage(_("Error exporting to DVI."));
2080 // Push directory path.
2081 string const path = temppath();
2082 // Prevent the compiler from optimizing away p
2086 // there are three cases here:
2087 // 1. we print to a file
2088 // 2. we print directly to a printer
2089 // 3. we print using a spool command (print to file first)
2092 string const dviname = changeExtension(latexName(true), "dvi");
2094 if (target == "printer") {
2095 if (!lyxrc.print_spool_command.empty()) {
2096 // case 3: print using a spool
2097 string const psname = changeExtension(dviname,".ps");
2098 command += ' ' + lyxrc.print_to_file
2101 + quoteName(dviname);
2103 string command2 = lyxrc.print_spool_command + ' ';
2104 if (target_name != "default") {
2105 command2 += lyxrc.print_spool_printerprefix
2109 command2 += quoteName(psname);
2111 // If successful, then spool command
2112 res = one.startscript(Systemcall::Wait, command);
2115 // If there's no GUI, we have to wait on this command. Otherwise,
2116 // LyX deletes the temporary directory, and with it the spooled
2117 // file, before it can be printed!!
2118 Systemcall::Starttype stype = use_gui ?
2119 Systemcall::DontWait : Systemcall::Wait;
2120 res = one.startscript(stype, command2);
2123 // case 2: print directly to a printer
2124 if (target_name != "default")
2125 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2127 Systemcall::Starttype stype = use_gui ?
2128 Systemcall::DontWait : Systemcall::Wait;
2129 res = one.startscript(stype, command + quoteName(dviname));
2133 // case 1: print to a file
2134 FileName const filename(makeAbsPath(target_name, filePath()));
2135 FileName const dvifile(makeAbsPath(dviname, path));
2136 if (filename.exists()) {
2137 docstring text = bformat(
2138 _("The file %1$s already exists.\n\n"
2139 "Do you want to overwrite that file?"),
2140 makeDisplayPath(filename.absFilename()));
2141 if (Alert::prompt(_("Overwrite file?"),
2142 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2145 command += ' ' + lyxrc.print_to_file
2146 + quoteName(filename.toFilesystemEncoding())
2148 + quoteName(dvifile.toFilesystemEncoding());
2150 Systemcall::Starttype stype = use_gui ?
2151 Systemcall::DontWait : Systemcall::Wait;
2152 res = one.startscript(stype, command);
2158 dr.setMessage(_("Error running external commands."));
2159 showPrintError(absFileName());
2164 case LFUN_BUFFER_LANGUAGE: {
2165 Language const * oldL = params().language;
2166 Language const * newL = languages.getLanguage(argument);
2167 if (!newL || oldL == newL)
2169 if (oldL->rightToLeft() == newL->rightToLeft() && !isMultiLingual())
2170 changeLanguage(oldL, newL);
2178 dr.dispatched(dispatched);
2179 undo().endUndoGroup();
2183 void Buffer::changeLanguage(Language const * from, Language const * to)
2185 LASSERT(from, /**/);
2188 for_each(par_iterator_begin(),
2190 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2194 bool Buffer::isMultiLingual() const
2196 ParConstIterator end = par_iterator_end();
2197 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2198 if (it->isMultiLingual(params()))
2205 std::set<Language const *> Buffer::getLanguages() const
2207 std::set<Language const *> languages;
2208 getLanguages(languages);
2213 void Buffer::getLanguages(std::set<Language const *> & languages) const
2215 ParConstIterator end = par_iterator_end();
2216 // add the buffer language, even if it's not actively used
2217 languages.insert(language());
2218 // iterate over the paragraphs
2219 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2220 it->getLanguages(languages);
2222 std::vector<Buffer *> clist = getChildren();
2223 for (vector<Buffer *>::const_iterator cit = clist.begin();
2224 cit != clist.end(); ++cit)
2225 (*cit)->getLanguages(languages);
2229 DocIterator Buffer::getParFromID(int const id) const
2231 Buffer * buf = const_cast<Buffer *>(this);
2233 // John says this is called with id == -1 from undo
2234 lyxerr << "getParFromID(), id: " << id << endl;
2235 return doc_iterator_end(buf);
2238 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2239 if (it.paragraph().id() == id)
2242 return doc_iterator_end(buf);
2246 bool Buffer::hasParWithID(int const id) const
2248 return !getParFromID(id).atEnd();
2252 ParIterator Buffer::par_iterator_begin()
2254 return ParIterator(doc_iterator_begin(this));
2258 ParIterator Buffer::par_iterator_end()
2260 return ParIterator(doc_iterator_end(this));
2264 ParConstIterator Buffer::par_iterator_begin() const
2266 return ParConstIterator(doc_iterator_begin(this));
2270 ParConstIterator Buffer::par_iterator_end() const
2272 return ParConstIterator(doc_iterator_end(this));
2276 Language const * Buffer::language() const
2278 return params().language;
2282 docstring const Buffer::B_(string const & l10n) const
2284 return params().B_(l10n);
2288 bool Buffer::isClean() const
2290 return d->lyx_clean;
2294 bool Buffer::isExternallyModified(CheckMethod method) const
2296 LASSERT(d->filename.exists(), /**/);
2297 // if method == timestamp, check timestamp before checksum
2298 return (method == checksum_method
2299 || d->timestamp_ != d->filename.lastModified())
2300 && d->checksum_ != d->filename.checksum();
2304 void Buffer::saveCheckSum(FileName const & file) const
2306 if (file.exists()) {
2307 d->timestamp_ = file.lastModified();
2308 d->checksum_ = file.checksum();
2310 // in the case of save to a new file.
2317 void Buffer::markClean() const
2319 if (!d->lyx_clean) {
2320 d->lyx_clean = true;
2323 // if the .lyx file has been saved, we don't need an
2325 d->bak_clean = true;
2329 void Buffer::setUnnamed(bool flag)
2335 bool Buffer::isUnnamed() const
2342 /// Don't check unnamed, here: isInternal() is used in
2343 /// newBuffer(), where the unnamed flag has not been set by anyone
2344 /// yet. Also, for an internal buffer, there should be no need for
2345 /// retrieving fileName() nor for checking if it is unnamed or not.
2346 bool Buffer::isInternal() const
2348 return fileName().extension() == "internal";
2352 void Buffer::markDirty()
2355 d->lyx_clean = false;
2358 d->bak_clean = false;
2360 DepClean::iterator it = d->dep_clean.begin();
2361 DepClean::const_iterator const end = d->dep_clean.end();
2363 for (; it != end; ++it)
2368 FileName Buffer::fileName() const
2374 string Buffer::absFileName() const
2376 return d->filename.absFilename();
2380 string Buffer::filePath() const
2382 return d->filename.onlyPath().absFilename() + "/";
2386 bool Buffer::isReadonly() const
2388 return d->read_only;
2392 void Buffer::setParent(Buffer const * buffer)
2394 // Avoids recursive include.
2395 d->setParent(buffer == this ? 0 : buffer);
2400 Buffer const * Buffer::parent() const
2406 void Buffer::Impl::collectRelatives(BufferSet & bufs) const
2408 bufs.insert(owner_);
2410 parent()->d->collectRelatives(bufs);
2412 // loop over children
2413 BufferPositionMap::const_iterator it = children_positions.begin();
2414 BufferPositionMap::const_iterator end = children_positions.end();
2415 for (; it != end; ++it)
2416 bufs.insert(const_cast<Buffer *>(it->first));
2420 std::vector<Buffer const *> Buffer::allRelatives() const
2423 d->collectRelatives(bufs);
2424 BufferSet::iterator it = bufs.begin();
2425 std::vector<Buffer const *> ret;
2426 for (; it != bufs.end(); ++it)
2432 Buffer const * Buffer::masterBuffer() const
2434 Buffer const * const pbuf = d->parent();
2438 return pbuf->masterBuffer();
2442 bool Buffer::isChild(Buffer * child) const
2444 return d->children_positions.find(child) != d->children_positions.end();
2448 DocIterator Buffer::firstChildPosition(Buffer const * child)
2450 Impl::BufferPositionMap::iterator it;
2451 it = d->children_positions.find(child);
2452 if (it == d->children_positions.end())
2453 return DocIterator(this);
2458 void Buffer::getChildren(std::vector<Buffer *> & clist, bool grand_children) const
2460 // loop over children
2461 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2462 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2463 for (; it != end; ++it) {
2464 Buffer * child = const_cast<Buffer *>(it->first);
2465 clist.push_back(child);
2466 if (grand_children) {
2467 // there might be grandchildren
2468 std::vector<Buffer *> glist = child->getChildren();
2469 for (vector<Buffer *>::const_iterator git = glist.begin();
2470 git != glist.end(); ++git)
2471 clist.push_back(*git);
2477 std::vector<Buffer *> Buffer::getChildren(bool grand_children) const
2479 std::vector<Buffer *> v;
2480 getChildren(v, grand_children);
2485 template<typename M>
2486 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
2491 typename M::const_iterator it = m.lower_bound(x);
2492 if (it == m.begin())
2500 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
2501 DocIterator const & pos) const
2503 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2505 // if paragraphs have no macro context set, pos will be empty
2509 // we haven't found anything yet
2510 DocIterator bestPos = owner_->par_iterator_begin();
2511 MacroData const * bestData = 0;
2513 // find macro definitions for name
2514 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
2515 if (nameIt != macros.end()) {
2516 // find last definition in front of pos or at pos itself
2517 PositionScopeMacroMap::const_iterator it
2518 = greatest_below(nameIt->second, pos);
2519 if (it != nameIt->second.end()) {
2521 // scope ends behind pos?
2522 if (pos < it->second.first) {
2523 // Looks good, remember this. If there
2524 // is no external macro behind this,
2525 // we found the right one already.
2526 bestPos = it->first;
2527 bestData = &it->second.second;
2531 // try previous macro if there is one
2532 if (it == nameIt->second.begin())
2539 // find macros in included files
2540 PositionScopeBufferMap::const_iterator it
2541 = greatest_below(position_to_children, pos);
2542 if (it == position_to_children.end())
2543 // no children before
2547 // do we know something better (i.e. later) already?
2548 if (it->first < bestPos )
2551 // scope ends behind pos?
2552 if (pos < it->second.first) {
2553 // look for macro in external file
2555 MacroData const * data
2556 = it->second.second->getMacro(name, false);
2559 bestPos = it->first;
2565 // try previous file if there is one
2566 if (it == position_to_children.begin())
2571 // return the best macro we have found
2576 MacroData const * Buffer::getMacro(docstring const & name,
2577 DocIterator const & pos, bool global) const
2582 // query buffer macros
2583 MacroData const * data = d->getBufferMacro(name, pos);
2587 // If there is a master buffer, query that
2588 Buffer const * const pbuf = d->parent();
2590 d->macro_lock = true;
2591 MacroData const * macro = pbuf->getMacro(
2592 name, *this, false);
2593 d->macro_lock = false;
2599 data = MacroTable::globalMacros().get(name);
2608 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2610 // set scope end behind the last paragraph
2611 DocIterator scope = par_iterator_begin();
2612 scope.pit() = scope.lastpit() + 1;
2614 return getMacro(name, scope, global);
2618 MacroData const * Buffer::getMacro(docstring const & name,
2619 Buffer const & child, bool global) const
2621 // look where the child buffer is included first
2622 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2623 if (it == d->children_positions.end())
2626 // check for macros at the inclusion position
2627 return getMacro(name, it->second, global);
2631 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
2633 pit_type const lastpit = it.lastpit();
2635 // look for macros in each paragraph
2636 while (it.pit() <= lastpit) {
2637 Paragraph & par = it.paragraph();
2639 // iterate over the insets of the current paragraph
2640 InsetList const & insets = par.insetList();
2641 InsetList::const_iterator iit = insets.begin();
2642 InsetList::const_iterator end = insets.end();
2643 for (; iit != end; ++iit) {
2644 it.pos() = iit->pos;
2646 // is it a nested text inset?
2647 if (iit->inset->asInsetText()) {
2648 // Inset needs its own scope?
2649 InsetText const * itext = iit->inset->asInsetText();
2650 bool newScope = itext->isMacroScope();
2652 // scope which ends just behind the inset
2653 DocIterator insetScope = it;
2656 // collect macros in inset
2657 it.push_back(CursorSlice(*iit->inset));
2658 updateMacros(it, newScope ? insetScope : scope);
2663 // is it an external file?
2664 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2665 // get buffer of external file
2666 InsetInclude const & inset =
2667 static_cast<InsetInclude const &>(*iit->inset);
2669 Buffer * child = inset.getChildBuffer();
2674 // register its position, but only when it is
2675 // included first in the buffer
2676 if (children_positions.find(child) ==
2677 children_positions.end())
2678 children_positions[child] = it;
2680 // register child with its scope
2681 position_to_children[it] = Impl::ScopeBuffer(scope, child);
2685 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2689 MathMacroTemplate & macroTemplate =
2690 static_cast<MathMacroTemplate &>(*iit->inset);
2691 MacroContext mc(owner_, it);
2692 macroTemplate.updateToContext(mc);
2695 bool valid = macroTemplate.validMacro();
2696 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2697 // then the BufferView's cursor will be invalid in
2698 // some cases which leads to crashes.
2703 // FIXME (Abdel), I don't understandt why we pass 'it' here
2704 // instead of 'macroTemplate' defined above... is this correct?
2705 macros[macroTemplate.name()][it] =
2706 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
2716 void Buffer::updateMacros() const
2721 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2723 // start with empty table
2725 d->children_positions.clear();
2726 d->position_to_children.clear();
2728 // Iterate over buffer, starting with first paragraph
2729 // The scope must be bigger than any lookup DocIterator
2730 // later. For the global lookup, lastpit+1 is used, hence
2731 // we use lastpit+2 here.
2732 DocIterator it = par_iterator_begin();
2733 DocIterator outerScope = it;
2734 outerScope.pit() = outerScope.lastpit() + 2;
2735 d->updateMacros(it, outerScope);
2739 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
2741 InsetIterator it = inset_iterator_begin(inset());
2742 InsetIterator const end = inset_iterator_end(inset());
2743 for (; it != end; ++it) {
2744 if (it->lyxCode() == BRANCH_CODE) {
2745 InsetBranch & br = static_cast<InsetBranch &>(*it);
2746 docstring const name = br.branch();
2747 if (!from_master && !params().branchlist().find(name))
2748 result.push_back(name);
2749 else if (from_master && !masterBuffer()->params().branchlist().find(name))
2750 result.push_back(name);
2753 if (it->lyxCode() == INCLUDE_CODE) {
2754 // get buffer of external file
2755 InsetInclude const & ins =
2756 static_cast<InsetInclude const &>(*it);
2757 Buffer * child = ins.getChildBuffer();
2760 child->getUsedBranches(result, true);
2763 // remove duplicates
2768 void Buffer::updateMacroInstances() const
2770 LYXERR(Debug::MACROS, "updateMacroInstances for "
2771 << d->filename.onlyFileName());
2772 DocIterator it = doc_iterator_begin(this);
2774 DocIterator const end = doc_iterator_end(this);
2775 for (; it != end; it.forwardInset()) {
2776 // look for MathData cells in InsetMathNest insets
2777 InsetMath * minset = it.nextInset()->asInsetMath();
2781 // update macro in all cells of the InsetMathNest
2782 DocIterator::idx_type n = minset->nargs();
2783 MacroContext mc = MacroContext(this, it);
2784 for (DocIterator::idx_type i = 0; i < n; ++i) {
2785 MathData & data = minset->cell(i);
2786 data.updateMacros(0, mc);
2792 void Buffer::listMacroNames(MacroNameSet & macros) const
2797 d->macro_lock = true;
2799 // loop over macro names
2800 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2801 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2802 for (; nameIt != nameEnd; ++nameIt)
2803 macros.insert(nameIt->first);
2805 // loop over children
2806 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2807 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2808 for (; it != end; ++it)
2809 it->first->listMacroNames(macros);
2812 Buffer const * const pbuf = d->parent();
2814 pbuf->listMacroNames(macros);
2816 d->macro_lock = false;
2820 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2822 Buffer const * const pbuf = d->parent();
2827 pbuf->listMacroNames(names);
2830 MacroNameSet::iterator it = names.begin();
2831 MacroNameSet::iterator end = names.end();
2832 for (; it != end; ++it) {
2834 MacroData const * data =
2835 pbuf->getMacro(*it, *this, false);
2837 macros.insert(data);
2839 // we cannot access the original MathMacroTemplate anymore
2840 // here to calls validate method. So we do its work here manually.
2841 // FIXME: somehow make the template accessible here.
2842 if (data->optionals() > 0)
2843 features.require("xargs");
2849 Buffer::References & Buffer::references(docstring const & label)
2852 return const_cast<Buffer *>(masterBuffer())->references(label);
2854 RefCache::iterator it = d->ref_cache_.find(label);
2855 if (it != d->ref_cache_.end())
2856 return it->second.second;
2858 static InsetLabel const * dummy_il = 0;
2859 static References const dummy_refs;
2860 it = d->ref_cache_.insert(
2861 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2862 return it->second.second;
2866 Buffer::References const & Buffer::references(docstring const & label) const
2868 return const_cast<Buffer *>(this)->references(label);
2872 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2874 masterBuffer()->d->ref_cache_[label].first = il;
2878 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2880 return masterBuffer()->d->ref_cache_[label].first;
2884 void Buffer::clearReferenceCache() const
2887 d->ref_cache_.clear();
2891 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2894 //FIXME: This does not work for child documents yet.
2895 LASSERT(code == CITE_CODE, /**/);
2896 // Check if the label 'from' appears more than once
2897 vector<docstring> labels;
2899 checkBibInfoCache();
2900 BiblioInfo const & keys = masterBibInfo();
2901 BiblioInfo::const_iterator bit = keys.begin();
2902 BiblioInfo::const_iterator bend = keys.end();
2904 for (; bit != bend; ++bit)
2906 labels.push_back(bit->first);
2909 if (count(labels.begin(), labels.end(), from) > 1)
2912 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2913 if (it->lyxCode() == code) {
2914 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2915 docstring const oldValue = inset.getParam(paramName);
2916 if (oldValue == from)
2917 inset.setParam(paramName, to);
2923 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2924 pit_type par_end, bool full_source) const
2926 OutputParams runparams(¶ms().encoding());
2927 runparams.nice = true;
2928 runparams.flavor = params().useXetex ?
2929 OutputParams::XETEX : OutputParams::LATEX;
2930 runparams.linelen = lyxrc.plaintext_linelen;
2931 // No side effect of file copying and image conversion
2932 runparams.dryrun = true;
2935 os << "% " << _("Preview source code") << "\n\n";
2937 d->texrow.newline();
2938 d->texrow.newline();
2940 writeDocBookSource(os, absFileName(), runparams, false);
2942 // latex or literate
2943 writeLaTeXSource(os, string(), runparams, true, true);
2945 runparams.par_begin = par_begin;
2946 runparams.par_end = par_end;
2947 if (par_begin + 1 == par_end) {
2949 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2953 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2954 convert<docstring>(par_begin),
2955 convert<docstring>(par_end - 1))
2962 // output paragraphs
2964 docbookParagraphs(text(), *this, os, runparams);
2966 // latex or literate
2967 latexParagraphs(*this, text(), os, texrow, runparams);
2972 ErrorList & Buffer::errorList(string const & type) const
2974 static ErrorList emptyErrorList;
2975 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2976 if (I == d->errorLists.end())
2977 return emptyErrorList;
2983 void Buffer::updateTocItem(std::string const & type,
2984 DocIterator const & dit) const
2987 d->gui_->updateTocItem(type, dit);
2991 void Buffer::structureChanged() const
2994 d->gui_->structureChanged();
2998 void Buffer::errors(string const & err, bool from_master) const
3001 d->gui_->errors(err, from_master);
3005 void Buffer::message(docstring const & msg) const
3008 d->gui_->message(msg);
3012 void Buffer::setBusy(bool on) const
3015 d->gui_->setBusy(on);
3019 void Buffer::updateTitles() const
3022 d->wa_->updateTitles();
3026 void Buffer::resetAutosaveTimers() const
3029 d->gui_->resetAutosaveTimers();
3033 bool Buffer::hasGuiDelegate() const
3039 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3048 class AutoSaveBuffer : public ForkedProcess {
3051 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3052 : buffer_(buffer), fname_(fname) {}
3054 virtual boost::shared_ptr<ForkedProcess> clone() const
3056 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3061 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3062 from_utf8(fname_.absFilename())));
3063 return run(DontWait);
3067 virtual int generateChild();
3069 Buffer const & buffer_;
3074 int AutoSaveBuffer::generateChild()
3076 #if defined(__APPLE__)
3077 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3078 * We should use something else like threads.
3080 * Since I do not know how to determine at run time what is the OS X
3081 * version, I just disable forking altogether for now (JMarc)
3083 pid_t const pid = -1;
3085 // tmp_ret will be located (usually) in /tmp
3086 // will that be a problem?
3087 // Note that this calls ForkedCalls::fork(), so it's
3088 // ok cross-platform.
3089 pid_t const pid = fork();
3090 // If you want to debug the autosave
3091 // you should set pid to -1, and comment out the fork.
3092 if (pid != 0 && pid != -1)
3096 // pid = -1 signifies that lyx was unable
3097 // to fork. But we will do the save
3099 bool failed = false;
3100 FileName const tmp_ret = FileName::tempName("lyxauto");
3101 if (!tmp_ret.empty()) {
3102 buffer_.writeFile(tmp_ret);
3103 // assume successful write of tmp_ret
3104 if (!tmp_ret.moveTo(fname_))
3110 // failed to write/rename tmp_ret so try writing direct
3111 if (!buffer_.writeFile(fname_)) {
3112 // It is dangerous to do this in the child,
3113 // but safe in the parent, so...
3114 if (pid == -1) // emit message signal.
3115 buffer_.message(_("Autosave failed!"));
3119 if (pid == 0) // we are the child so...
3128 FileName Buffer::getAutosaveFilename() const
3130 // if the document is unnamed try to save in the backup dir, else
3131 // in the default document path, and as a last try in the filePath,
3132 // which will most often be the temporary directory
3135 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3136 : lyxrc.backupdir_path;
3137 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3140 string const fname = "#" + d->filename.onlyFileName() + "#";
3141 return makeAbsPath(fname, fpath);
3145 void Buffer::removeAutosaveFile() const
3147 FileName const f = getAutosaveFilename();
3153 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3155 FileName const newauto = getAutosaveFilename();
3157 if (newauto != oldauto && oldauto.exists())
3158 if (!oldauto.moveTo(newauto))
3159 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3163 // Perfect target for a thread...
3164 void Buffer::autoSave() const
3166 if (d->bak_clean || isReadonly()) {
3167 // We don't save now, but we'll try again later
3168 resetAutosaveTimers();
3172 // emit message signal.
3173 message(_("Autosaving current document..."));
3174 AutoSaveBuffer autosave(*this, getAutosaveFilename());
3177 d->bak_clean = true;
3179 resetAutosaveTimers();
3183 string Buffer::bufferFormat() const
3185 string format = params().documentClass().outputFormat();
3186 if (format == "latex") {
3187 if (params().useXetex)
3189 if (params().encoding().package() == Encoding::japanese)
3196 string Buffer::getDefaultOutputFormat() const
3198 if (!params().defaultOutputFormat.empty()
3199 && params().defaultOutputFormat != "default")
3200 return params().defaultOutputFormat;
3201 typedef vector<Format const *> Formats;
3202 Formats formats = exportableFormats(true);
3205 || params().useXetex
3206 || params().encoding().package() == Encoding::japanese) {
3207 if (formats.empty())
3209 // return the first we find
3210 return formats.front()->name();
3212 return lyxrc.default_view_format;
3217 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3218 bool includeall, string & result_file) const
3220 string backend_format;
3221 OutputParams runparams(¶ms().encoding());
3222 runparams.flavor = OutputParams::LATEX;
3223 runparams.linelen = lyxrc.plaintext_linelen;
3224 runparams.includeall = includeall;
3225 vector<string> backs = backends();
3226 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3227 // Get shortest path to format
3228 Graph::EdgePath path;
3229 for (vector<string>::const_iterator it = backs.begin();
3230 it != backs.end(); ++it) {
3231 Graph::EdgePath p = theConverters().getPath(*it, format);
3232 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3233 backend_format = *it;
3238 if (!put_in_tempdir) {
3239 // Only show this alert if this is an export to a non-temporary
3240 // file (not for previewing).
3241 Alert::error(_("Couldn't export file"), bformat(
3242 _("No information for exporting the format %1$s."),
3243 formats.prettyName(format)));
3247 runparams.flavor = theConverters().getFlavor(path);
3250 backend_format = format;
3251 // FIXME: Don't hardcode format names here, but use a flag
3252 if (backend_format == "pdflatex")
3253 runparams.flavor = OutputParams::PDFLATEX;
3256 string filename = latexName(false);
3257 filename = addName(temppath(), filename);
3258 filename = changeExtension(filename,
3259 formats.extension(backend_format));
3262 updateMacroInstances();
3264 // Plain text backend
3265 if (backend_format == "text") {
3266 runparams.flavor = OutputParams::TEXT;
3267 writePlaintextFile(*this, FileName(filename), runparams);
3270 else if (backend_format == "xhtml") {
3271 runparams.flavor = OutputParams::HTML;
3272 makeLyXHTMLFile(FileName(filename), runparams);
3273 } else if (backend_format == "lyx")
3274 writeFile(FileName(filename));
3276 else if (isDocBook()) {
3277 runparams.nice = !put_in_tempdir;
3278 makeDocBookFile(FileName(filename), runparams);
3281 else if (backend_format == format) {
3282 runparams.nice = true;
3283 if (!makeLaTeXFile(FileName(filename), string(), runparams))
3285 } else if (!lyxrc.tex_allows_spaces
3286 && contains(filePath(), ' ')) {
3287 Alert::error(_("File name error"),
3288 _("The directory path to the document cannot contain spaces."));
3291 runparams.nice = false;
3292 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
3296 string const error_type = (format == "program")
3297 ? "Build" : bufferFormat();
3298 ErrorList & error_list = d->errorLists[error_type];
3299 string const ext = formats.extension(format);
3300 FileName const tmp_result_file(changeExtension(filename, ext));
3301 bool const success = theConverters().convert(this, FileName(filename),
3302 tmp_result_file, FileName(absFileName()), backend_format, format,
3304 // Emit the signal to show the error list.
3305 if (format != backend_format) {
3307 // also to the children, in case of master-buffer-view
3308 std::vector<Buffer *> clist = getChildren();
3309 for (vector<Buffer *>::const_iterator cit = clist.begin();
3310 cit != clist.end(); ++cit)
3311 (*cit)->errors(error_type, true);
3316 if (d->cloned_buffer_) {
3317 // Enable reverse dvi or pdf to work by copying back the texrow
3318 // object to the cloned buffer.
3319 // FIXME: There is a possibility of concurrent access to texrow
3320 // here from the main GUI thread that should be securized.
3321 d->cloned_buffer_->d->texrow = d->texrow;
3324 if (put_in_tempdir) {
3325 result_file = tmp_result_file.absFilename();
3329 result_file = changeExtension(d->exportFileName().absFilename(), ext);
3330 // We need to copy referenced files (e. g. included graphics
3331 // if format == "dvi") to the result dir.
3332 vector<ExportedFile> const files =
3333 runparams.exportdata->externalFiles(format);
3334 string const dest = onlyPath(result_file);
3335 CopyStatus status = SUCCESS;
3337 vector<ExportedFile>::const_iterator it = files.begin();
3338 vector<ExportedFile>::const_iterator const en = files.end();
3339 for (; it != en && status != CANCEL; ++it) {
3340 string const fmt = formats.getFormatFromFile(it->sourceName);
3341 status = copyFile(fmt, it->sourceName,
3342 makeAbsPath(it->exportName, dest),
3343 it->exportName, status == FORCE);
3346 if (status == CANCEL) {
3347 message(_("Document export cancelled."));
3348 } else if (tmp_result_file.exists()) {
3349 // Finally copy the main file
3350 status = copyFile(format, tmp_result_file,
3351 FileName(result_file), result_file,
3353 message(bformat(_("Document exported as %1$s "
3355 formats.prettyName(format),
3356 makeDisplayPath(result_file)));
3358 // This must be a dummy converter like fax (bug 1888)
3359 message(bformat(_("Document exported as %1$s"),
3360 formats.prettyName(format)));
3367 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3368 bool includeall) const
3371 // (1) export with all included children (omit \includeonly)
3372 if (includeall && !doExport(format, put_in_tempdir, true, result_file))
3374 // (2) export with included children only
3375 return doExport(format, put_in_tempdir, false, result_file);
3379 bool Buffer::preview(string const & format, bool includeall) const
3382 // (1) export with all included children (omit \includeonly)
3383 if (includeall && !doExport(format, true, true))
3385 // (2) export with included children only
3386 if (!doExport(format, true, false, result_file))
3388 return formats.view(*this, FileName(result_file), format);
3392 bool Buffer::isExportable(string const & format) const
3394 vector<string> backs = backends();
3395 for (vector<string>::const_iterator it = backs.begin();
3396 it != backs.end(); ++it)
3397 if (theConverters().isReachable(*it, format))
3403 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
3405 vector<string> const backs = backends();
3406 vector<Format const *> result =
3407 theConverters().getReachable(backs[0], only_viewable, true);
3408 for (vector<string>::const_iterator it = backs.begin() + 1;
3409 it != backs.end(); ++it) {
3410 vector<Format const *> r =
3411 theConverters().getReachable(*it, only_viewable, false);
3412 result.insert(result.end(), r.begin(), r.end());
3418 vector<string> Buffer::backends() const
3421 v.push_back(bufferFormat());
3422 // FIXME: Don't hardcode format names here, but use a flag
3423 if (v.back() == "latex")
3424 v.push_back("pdflatex");
3425 v.push_back("xhtml");
3426 v.push_back("text");
3432 bool Buffer::readFileHelper(FileName const & s)
3434 // File information about normal file
3436 docstring const file = makeDisplayPath(s.absFilename(), 50);
3437 docstring text = bformat(_("The specified document\n%1$s"
3438 "\ncould not be read."), file);
3439 Alert::error(_("Could not read document"), text);
3443 // Check if emergency save file exists and is newer.
3444 FileName const e(s.absFilename() + ".emergency");
3446 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
3447 docstring const file = makeDisplayPath(s.absFilename(), 20);
3448 docstring const text =
3449 bformat(_("An emergency save of the document "
3451 "Recover emergency save?"), file);
3452 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
3453 _("&Recover"), _("&Load Original"),
3457 // the file is not saved if we load the emergency file.
3462 if ((res = readFile(e)) == success)
3463 str = _("Document was successfully recovered.");
3465 str = _("Document was NOT successfully recovered.");
3466 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3467 from_utf8(e.absFilename()));
3469 if (!Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3470 _("&Remove"), _("&Keep it"))) {
3473 Alert::warning(_("Emergency file deleted"),
3474 _("Do not forget to save your file now!"), true);
3479 if (!Alert::prompt(_("Delete emergency file?"),
3480 _("Remove emergency file now?"), 1, 1,
3481 _("&Remove"), _("&Keep it")))
3489 // Now check if autosave file is newer.
3490 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
3492 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
3493 docstring const file = makeDisplayPath(s.absFilename(), 20);
3494 docstring const text =
3495 bformat(_("The backup of the document "
3496 "%1$s is newer.\n\nLoad the "
3497 "backup instead?"), file);
3498 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
3499 _("&Load backup"), _("Load &original"),
3503 // the file is not saved if we load the autosave file.
3507 // Here we delete the autosave
3518 bool Buffer::loadLyXFile(FileName const & s)
3520 // If the file is not readable, we try to
3521 // retrieve the file from version control.
3522 if (!s.isReadableFile()
3523 && !LyXVC::file_not_found_hook(s))
3526 if (s.isReadableFile()){
3527 // InsetInfo needs to know if file is under VCS
3528 lyxvc().file_found_hook(s);
3529 if (readFileHelper(s)) {
3530 d->read_only = !s.isWritable();
3538 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3540 TeXErrors::Errors::const_iterator cit = terr.begin();
3541 TeXErrors::Errors::const_iterator end = terr.end();
3543 for (; cit != end; ++cit) {
3546 int errorRow = cit->error_in_line;
3547 bool found = d->texrow.getIdFromRow(errorRow, id_start,
3553 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
3554 } while (found && id_start == id_end && pos_start == pos_end);
3556 errorList.push_back(ErrorItem(cit->error_desc,
3557 cit->error_text, id_start, pos_start, pos_end));
3562 void Buffer::setBuffersForInsets() const
3564 inset().setBuffer(const_cast<Buffer &>(*this));
3568 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
3570 // Use the master text class also for child documents
3571 Buffer const * const master = masterBuffer();
3572 DocumentClass const & textclass = master->params().documentClass();
3574 // do this only if we are the top-level Buffer
3575 if (scope != UpdateMaster || master == this)
3576 checkBibInfoCache();
3578 // keep the buffers to be children in this set. If the call from the
3579 // master comes back we can see which of them were actually seen (i.e.
3580 // via an InsetInclude). The remaining ones in the set need still be updated.
3581 static std::set<Buffer const *> bufToUpdate;
3582 if (scope == UpdateMaster) {
3583 // If this is a child document start with the master
3584 if (master != this) {
3585 bufToUpdate.insert(this);
3586 master->updateBuffer(UpdateMaster, utype);
3587 // Do this here in case the master has no gui associated with it. Then,
3588 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3589 if (!master->d->gui_)
3592 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3593 if (bufToUpdate.find(this) == bufToUpdate.end())
3597 // start over the counters in the master
3598 textclass.counters().reset();
3601 // update will be done below for this buffer
3602 bufToUpdate.erase(this);
3604 // update all caches
3605 clearReferenceCache();
3608 Buffer & cbuf = const_cast<Buffer &>(*this);
3610 LASSERT(!text().paragraphs().empty(), /**/);
3613 ParIterator parit = cbuf.par_iterator_begin();
3614 updateBuffer(parit, utype);
3617 // TocBackend update will be done later.
3620 cbuf.tocBackend().update();
3621 if (scope == UpdateMaster)
3622 cbuf.structureChanged();
3626 static depth_type getDepth(DocIterator const & it)
3628 depth_type depth = 0;
3629 for (size_t i = 0 ; i < it.depth() ; ++i)
3630 if (!it[i].inset().inMathed())
3631 depth += it[i].paragraph().getDepth() + 1;
3632 // remove 1 since the outer inset does not count
3636 static depth_type getItemDepth(ParIterator const & it)
3638 Paragraph const & par = *it;
3639 LabelType const labeltype = par.layout().labeltype;
3641 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3644 // this will hold the lowest depth encountered up to now.
3645 depth_type min_depth = getDepth(it);
3646 ParIterator prev_it = it;
3649 --prev_it.top().pit();
3651 // start of nested inset: go to outer par
3653 if (prev_it.empty()) {
3654 // start of document: nothing to do
3659 // We search for the first paragraph with same label
3660 // that is not more deeply nested.
3661 Paragraph & prev_par = *prev_it;
3662 depth_type const prev_depth = getDepth(prev_it);
3663 if (labeltype == prev_par.layout().labeltype) {
3664 if (prev_depth < min_depth)
3665 return prev_par.itemdepth + 1;
3666 if (prev_depth == min_depth)
3667 return prev_par.itemdepth;
3669 min_depth = min(min_depth, prev_depth);
3670 // small optimization: if we are at depth 0, we won't
3671 // find anything else
3672 if (prev_depth == 0)
3678 static bool needEnumCounterReset(ParIterator const & it)
3680 Paragraph const & par = *it;
3681 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3682 depth_type const cur_depth = par.getDepth();
3683 ParIterator prev_it = it;
3684 while (prev_it.pit()) {
3685 --prev_it.top().pit();
3686 Paragraph const & prev_par = *prev_it;
3687 if (prev_par.getDepth() <= cur_depth)
3688 return prev_par.layout().labeltype != LABEL_ENUMERATE;
3690 // start of nested inset: reset
3695 // set the label of a paragraph. This includes the counters.
3696 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
3698 BufferParams const & bp = owner_->masterBuffer()->params();
3699 DocumentClass const & textclass = bp.documentClass();
3700 Paragraph & par = it.paragraph();
3701 Layout const & layout = par.layout();
3702 Counters & counters = textclass.counters();
3704 if (par.params().startOfAppendix()) {
3705 // FIXME: only the counter corresponding to toplevel
3706 // sectioning should be reset
3708 counters.appendix(true);
3710 par.params().appendix(counters.appendix());
3712 // Compute the item depth of the paragraph
3713 par.itemdepth = getItemDepth(it);
3715 if (layout.margintype == MARGIN_MANUAL
3716 || layout.latextype == LATEX_BIB_ENVIRONMENT) {
3717 if (par.params().labelWidthString().empty())
3718 par.params().labelWidthString(par.expandLabel(layout, bp));
3720 par.params().labelWidthString(docstring());
3723 switch(layout.labeltype) {
3725 if (layout.toclevel <= bp.secnumdepth
3726 && (layout.latextype != LATEX_ENVIRONMENT
3727 || it.text()->isFirstInSequence(it.pit()))) {
3728 counters.step(layout.counter, utype);
3729 par.params().labelString(
3730 par.expandLabel(layout, bp));
3732 par.params().labelString(docstring());
3735 case LABEL_ITEMIZE: {
3736 // At some point of time we should do something more
3737 // clever here, like:
3738 // par.params().labelString(
3739 // bp.user_defined_bullet(par.itemdepth).getText());
3740 // for now, use a simple hardcoded label
3741 docstring itemlabel;
3742 switch (par.itemdepth) {
3744 itemlabel = char_type(0x2022);
3747 itemlabel = char_type(0x2013);
3750 itemlabel = char_type(0x2217);
3753 itemlabel = char_type(0x2219); // or 0x00b7
3756 par.params().labelString(itemlabel);
3760 case LABEL_ENUMERATE: {
3761 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
3763 switch (par.itemdepth) {
3772 enumcounter += "iv";
3775 // not a valid enumdepth...
3779 // Maybe we have to reset the enumeration counter.
3780 if (needEnumCounterReset(it))
3781 counters.reset(enumcounter);
3782 counters.step(enumcounter, utype);
3784 string const & lang = par.getParLanguage(bp)->code();
3785 par.params().labelString(counters.theCounter(enumcounter, lang));
3790 case LABEL_SENSITIVE: {
3791 string const & type = counters.current_float();
3792 docstring full_label;
3794 full_label = owner_->B_("Senseless!!! ");
3796 docstring name = owner_->B_(textclass.floats().getType(type).name());
3797 if (counters.hasCounter(from_utf8(type))) {
3798 string const & lang = par.getParLanguage(bp)->code();
3799 counters.step(from_utf8(type), utype);
3800 full_label = bformat(from_ascii("%1$s %2$s:"),
3802 counters.theCounter(from_utf8(type), lang));
3804 full_label = bformat(from_ascii("%1$s #:"), name);
3806 par.params().labelString(full_label);
3810 case LABEL_NO_LABEL:
3811 par.params().labelString(docstring());
3815 case LABEL_TOP_ENVIRONMENT:
3816 case LABEL_CENTERED_TOP_ENVIRONMENT:
3819 par.params().labelString(par.expandLabel(layout, bp));
3825 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
3827 LASSERT(parit.pit() == 0, /**/);
3829 // set the position of the text in the buffer to be able
3830 // to resolve macros in it. This has nothing to do with
3831 // labels, but by putting it here we avoid implementing
3832 // a whole bunch of traversal routines just for this call.
3833 parit.text()->setMacrocontextPosition(parit);
3835 depth_type maxdepth = 0;
3836 pit_type const lastpit = parit.lastpit();
3837 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
3838 // reduce depth if necessary
3839 parit->params().depth(min(parit->params().depth(), maxdepth));
3840 maxdepth = parit->getMaxDepthAfter();
3842 if (utype == OutputUpdate) {
3843 // track the active counters
3844 // we have to do this for the master buffer, since the local
3845 // buffer isn't tracking anything.
3846 masterBuffer()->params().documentClass().counters().
3847 setActiveLayout(parit->layout());
3850 // set the counter for this paragraph
3851 d->setLabel(parit, utype);
3854 InsetList::const_iterator iit = parit->insetList().begin();
3855 InsetList::const_iterator end = parit->insetList().end();
3856 for (; iit != end; ++iit) {
3857 parit.pos() = iit->pos;
3858 iit->inset->updateBuffer(parit, utype);
3864 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
3865 WordLangTuple & word_lang, docstring_list & suggestions) const
3869 suggestions.clear();
3870 word_lang = WordLangTuple();
3871 // OK, we start from here.
3872 DocIterator const end = doc_iterator_end(this);
3873 for (; from != end; from.forwardPos()) {
3874 // We are only interested in text so remove the math CursorSlice.
3875 while (from.inMathed()) {
3879 // If from is at the end of the document (which is possible
3880 // when leaving the mathed) LyX will crash later.
3884 if (from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions)) {
3889 // Do not increase progress when from == to, otherwise the word
3890 // count will be wrong.
3900 bool Buffer::reload()
3903 // e.g., read-only status could have changed due to version control
3904 d->filename.refresh();
3905 docstring const disp_fn = makeDisplayPath(d->filename.absFilename());
3907 bool const success = loadLyXFile(d->filename);
3912 message(bformat(_("Document %1$s reloaded."), disp_fn));
3914 message(bformat(_("Could not reload document %1$s."), disp_fn));