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 = 382; // uwestoehr: support to change font color for greyed-out notes
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) {
282 && parent_buffer && pb && parent_buffer != pb)
283 LYXERR0("Warning: a buffer should not have two parents!");
287 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
288 /// This one is useful for preview detached in a thread.
289 Buffer const * cloned_buffer_;
292 /// So we can force access via the accessors.
293 mutable Buffer const * parent_buffer;
298 /// Creates the per buffer temporary directory
299 static FileName createBufferTmpDir()
302 // We are in our own directory. Why bother to mangle name?
303 // In fact I wrote this code to circumvent a problematic behaviour
304 // (bug?) of EMX mkstemp().
305 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
306 convert<string>(count++));
308 if (!tmpfl.createDirectory(0777)) {
309 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
310 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
311 from_utf8(tmpfl.absFilename())));
317 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
318 Buffer const * cloned_buffer)
319 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
320 read_only(readonly_), filename(file), file_fully_loaded(false),
321 toc_backend(owner), macro_lock(false), timestamp_(0),
322 checksum_(0), wa_(0), gui_(0), undo_(*owner), bibinfo_cache_valid_(false),
323 cloned_buffer_(cloned_buffer), parent_buffer(0)
325 if (!cloned_buffer_) {
326 temppath = createBufferTmpDir();
327 lyxvc.setBuffer(owner_);
329 wa_ = new frontend::WorkAreaManager;
332 temppath = cloned_buffer_->d->temppath;
333 file_fully_loaded = true;
334 params = cloned_buffer_->d->params;
335 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
336 bibinfo_ = cloned_buffer_->d->bibinfo_;
337 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
338 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
342 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
343 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
345 LYXERR(Debug::INFO, "Buffer::Buffer()");
347 d->inset = new InsetText(*cloned_buffer->d->inset);
348 d->inset->setBuffer(*this);
349 // FIXME: optimize this loop somewhat, maybe by creating a new
350 // general recursive Inset::setId().
351 DocIterator it = doc_iterator_begin(this);
352 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
353 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
354 it.paragraph().setId(cloned_it.paragraph().id());
356 d->inset = new InsetText(this);
357 d->inset->setAutoBreakRows(true);
358 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
364 LYXERR(Debug::INFO, "Buffer::~Buffer()");
365 // here the buffer should take care that it is
366 // saved properly, before it goes into the void.
368 // GuiView already destroyed
372 // No need to do additional cleanups for internal buffer.
377 // loop over children
378 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
379 Impl::BufferPositionMap::iterator end = d->children_positions.end();
380 for (; it != end; ++it) {
381 Buffer * child = const_cast<Buffer *>(it->first);
382 if (d->cloned_buffer_)
384 // The child buffer might have been closed already.
385 else if (theBufferList().isLoaded(child))
386 theBufferList().releaseChild(this, child);
390 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
391 msg += emergencyWrite();
392 Alert::warning(_("Attempting to close changed document!"), msg);
395 // clear references to children in macro tables
396 d->children_positions.clear();
397 d->position_to_children.clear();
399 if (!d->cloned_buffer_ && !d->temppath.destroyDirectory()) {
400 Alert::warning(_("Could not remove temporary directory"),
401 bformat(_("Could not remove the temporary directory %1$s"),
402 from_utf8(d->temppath.absFilename())));
405 // Remove any previewed LaTeX snippets associated with this buffer.
406 thePreviews().removeLoader(*this);
412 Buffer * Buffer::clone() const
414 Buffer * buffer_clone = new Buffer(fileName().absFilename(), false, this);
415 buffer_clone->d->macro_lock = true;
416 buffer_clone->d->children_positions.clear();
417 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
418 // math macro caches need to be rethought and simplified.
419 // I am not sure wether we should handle Buffer cloning here or in BufferList.
420 // Right now BufferList knows nothing about buffer clones.
421 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
422 Impl::BufferPositionMap::iterator end = d->children_positions.end();
423 for (; it != end; ++it) {
424 DocIterator dit = it->second.clone(buffer_clone);
425 dit.setBuffer(buffer_clone);
426 Buffer * child = const_cast<Buffer *>(it->first);
427 Buffer * child_clone = child->clone();
428 Inset * inset = dit.nextInset();
429 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
430 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
431 inset_inc->setChildBuffer(child_clone);
432 child_clone->d->setParent(buffer_clone);
433 buffer_clone->setChild(dit, child_clone);
435 buffer_clone->d->macro_lock = false;
440 bool Buffer::isClone() const
442 return d->cloned_buffer_;
446 void Buffer::changed(bool update_metrics) const
449 d->wa_->redrawAll(update_metrics);
453 frontend::WorkAreaManager & Buffer::workAreaManager() const
455 LASSERT(d->wa_, /**/);
460 Text & Buffer::text() const
462 return d->inset->text();
466 Inset & Buffer::inset() const
472 BufferParams & Buffer::params()
478 BufferParams const & Buffer::params() const
484 ParagraphList & Buffer::paragraphs()
486 return text().paragraphs();
490 ParagraphList const & Buffer::paragraphs() const
492 return text().paragraphs();
496 LyXVC & Buffer::lyxvc()
502 LyXVC const & Buffer::lyxvc() const
508 string const Buffer::temppath() const
510 return d->temppath.absFilename();
514 TexRow & Buffer::texrow()
520 TexRow const & Buffer::texrow() const
526 TocBackend & Buffer::tocBackend() const
528 return d->toc_backend;
532 Undo & Buffer::undo()
538 void Buffer::setChild(DocIterator const & dit, Buffer * child)
540 d->children_positions[child] = dit;
544 string Buffer::latexName(bool const no_path) const
546 FileName latex_name =
547 makeLatexName(d->exportFileName());
548 return no_path ? latex_name.onlyFileName()
549 : latex_name.absFilename();
553 FileName Buffer::Impl::exportFileName() const
555 docstring const branch_suffix =
556 params.branchlist().getFilenameSuffix();
557 if (branch_suffix.empty())
560 string const name = filename.onlyFileNameWithoutExt()
561 + to_utf8(branch_suffix);
562 FileName res(filename.onlyPath().absFilename() + "/" + name);
563 res.changeExtension(filename.extension());
569 string Buffer::logName(LogType * type) const
571 string const filename = latexName(false);
573 if (filename.empty()) {
579 string const path = temppath();
581 FileName const fname(addName(temppath(),
582 onlyFilename(changeExtension(filename,
585 // FIXME: how do we know this is the name of the build log?
586 FileName const bname(
587 addName(path, onlyFilename(
588 changeExtension(filename,
589 formats.extension(bufferFormat()) + ".out"))));
591 // Also consider the master buffer log file
592 FileName masterfname = fname;
594 if (masterBuffer() != this) {
595 string const mlogfile = masterBuffer()->logName(&mtype);
596 masterfname = FileName(mlogfile);
599 // If no Latex log or Build log is newer, show Build log
600 if (bname.exists() &&
601 ((!fname.exists() && !masterfname.exists())
602 || (fname.lastModified() < bname.lastModified()
603 && masterfname.lastModified() < bname.lastModified()))) {
604 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
607 return bname.absFilename();
608 // If we have a newer master file log or only a master log, show this
609 } else if (fname != masterfname
610 && (!fname.exists() && (masterfname.exists()
611 || fname.lastModified() < masterfname.lastModified()))) {
612 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
615 return masterfname.absFilename();
617 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
620 return fname.absFilename();
624 void Buffer::setReadonly(bool const flag)
626 if (d->read_only != flag) {
633 void Buffer::setFileName(string const & newfile)
635 d->filename = makeAbsPath(newfile);
636 setReadonly(d->filename.isReadOnly());
641 int Buffer::readHeader(Lexer & lex)
643 int unknown_tokens = 0;
645 int begin_header_line = -1;
647 // Initialize parameters that may be/go lacking in header:
648 params().branchlist().clear();
649 params().preamble.erase();
650 params().options.erase();
651 params().master.erase();
652 params().float_placement.erase();
653 params().paperwidth.erase();
654 params().paperheight.erase();
655 params().leftmargin.erase();
656 params().rightmargin.erase();
657 params().topmargin.erase();
658 params().bottommargin.erase();
659 params().headheight.erase();
660 params().headsep.erase();
661 params().footskip.erase();
662 params().columnsep.erase();
663 params().fontsCJK.erase();
664 params().listings_params.clear();
665 params().clearLayoutModules();
666 params().clearRemovedModules();
667 params().clearIncludedChildren();
668 params().pdfoptions().clear();
669 params().indiceslist().clear();
670 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
671 params().notefontcolor = lyx::rgbFromHexName("#cccccc");
673 for (int i = 0; i < 4; ++i) {
674 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
675 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
678 ErrorList & errorList = d->errorLists["Parse"];
687 if (token == "\\end_header")
691 if (token == "\\begin_header") {
692 begin_header_line = line;
696 LYXERR(Debug::PARSER, "Handling document header token: `"
699 string unknown = params().readToken(lex, token, d->filename.onlyPath());
700 if (!unknown.empty()) {
701 if (unknown[0] != '\\' && token == "\\textclass") {
702 Alert::warning(_("Unknown document class"),
703 bformat(_("Using the default document class, because the "
704 "class %1$s is unknown."), from_utf8(unknown)));
707 docstring const s = bformat(_("Unknown token: "
711 errorList.push_back(ErrorItem(_("Document header error"),
716 if (begin_header_line) {
717 docstring const s = _("\\begin_header is missing");
718 errorList.push_back(ErrorItem(_("Document header error"),
722 params().makeDocumentClass();
724 return unknown_tokens;
729 // changed to be public and have one parameter
730 // Returns true if "\end_document" is not read (Asger)
731 bool Buffer::readDocument(Lexer & lex)
733 ErrorList & errorList = d->errorLists["Parse"];
736 if (!lex.checkFor("\\begin_document")) {
737 docstring const s = _("\\begin_document is missing");
738 errorList.push_back(ErrorItem(_("Document header error"),
742 // we are reading in a brand new document
743 LASSERT(paragraphs().empty(), /**/);
747 if (params().outputChanges) {
748 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
749 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
750 LaTeXFeatures::isAvailable("xcolor");
752 if (!dvipost && !xcolorulem) {
753 Alert::warning(_("Changes not shown in LaTeX output"),
754 _("Changes will not be highlighted in LaTeX output, "
755 "because neither dvipost nor xcolor/ulem are installed.\n"
756 "Please install these packages or redefine "
757 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
758 } else if (!xcolorulem) {
759 Alert::warning(_("Changes not shown in LaTeX output"),
760 _("Changes will not be highlighted in LaTeX output "
761 "when using pdflatex, because xcolor and ulem are not installed.\n"
762 "Please install both packages or redefine "
763 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
767 if (!params().master.empty()) {
768 FileName const master_file = makeAbsPath(params().master,
769 onlyPath(absFileName()));
770 if (isLyXFilename(master_file.absFilename())) {
772 checkAndLoadLyXFile(master_file, true);
774 // necessary e.g. after a reload
775 // to re-register the child (bug 5873)
776 // FIXME: clean up updateMacros (here, only
777 // child registering is needed).
778 master->updateMacros();
779 // set master as master buffer, but only
780 // if we are a real child
781 if (master->isChild(this))
783 // if the master is not fully loaded
784 // it is probably just loading this
785 // child. No warning needed then.
786 else if (master->isFullyLoaded())
787 LYXERR0("The master '"
789 << "' assigned to this document ("
791 << ") does not include "
792 "this document. Ignoring the master assignment.");
797 // assure we have a default index
798 params().indiceslist().addDefault(B_("Index"));
801 bool const res = text().read(lex, errorList, d->inset);
805 updateMacroInstances();
810 bool Buffer::readString(string const & s)
812 params().compressed = false;
814 // remove dummy empty par
815 paragraphs().clear();
819 FileName const name = FileName::tempName("Buffer_readString");
820 switch (readFile(lex, name, true)) {
824 // We need to call lyx2lyx, so write the input to a file
825 ofstream os(name.toFilesystemEncoding().c_str());
828 return readFile(name);
838 bool Buffer::readFile(FileName const & filename)
840 FileName fname(filename);
842 params().compressed = fname.isZippedFile();
844 // remove dummy empty par
845 paragraphs().clear();
848 if (readFile(lex, fname) != success)
855 bool Buffer::isFullyLoaded() const
857 return d->file_fully_loaded;
861 void Buffer::setFullyLoaded(bool value)
863 d->file_fully_loaded = value;
867 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
870 LASSERT(!filename.empty(), /**/);
872 // the first (non-comment) token _must_ be...
873 if (!lex.checkFor("\\lyxformat")) {
874 Alert::error(_("Document format failure"),
875 bformat(_("%1$s is not a readable LyX document."),
876 from_utf8(filename.absFilename())));
882 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
883 // if present remove ".," from string.
884 size_t dot = tmp_format.find_first_of(".,");
885 //lyxerr << " dot found at " << dot << endl;
886 if (dot != string::npos)
887 tmp_format.erase(dot, 1);
888 int const file_format = convert<int>(tmp_format);
889 //lyxerr << "format: " << file_format << endl;
891 // save timestamp and checksum of the original disk file, making sure
892 // to not overwrite them with those of the file created in the tempdir
893 // when it has to be converted to the current format.
895 // Save the timestamp and checksum of disk file. If filename is an
896 // emergency file, save the timestamp and checksum of the original lyx file
897 // because isExternallyModified will check for this file. (BUG4193)
898 string diskfile = filename.absFilename();
899 if (suffixIs(diskfile, ".emergency"))
900 diskfile = diskfile.substr(0, diskfile.size() - 10);
901 saveCheckSum(FileName(diskfile));
904 if (file_format != LYX_FORMAT) {
907 // lyx2lyx would fail
910 FileName const tmpfile = FileName::tempName("Buffer_readFile");
911 if (tmpfile.empty()) {
912 Alert::error(_("Conversion failed"),
913 bformat(_("%1$s is from a different"
914 " version of LyX, but a temporary"
915 " file for converting it could"
917 from_utf8(filename.absFilename())));
920 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
921 if (lyx2lyx.empty()) {
922 Alert::error(_("Conversion script not found"),
923 bformat(_("%1$s is from a different"
924 " version of LyX, but the"
925 " conversion script lyx2lyx"
926 " could not be found."),
927 from_utf8(filename.absFilename())));
930 ostringstream command;
931 command << os::python()
932 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
933 << " -t " << convert<string>(LYX_FORMAT)
934 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
935 << ' ' << quoteName(filename.toSafeFilesystemEncoding());
936 string const command_str = command.str();
938 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
940 cmd_ret const ret = runCommand(command_str);
941 if (ret.first != 0) {
942 if (file_format < LYX_FORMAT)
943 Alert::error(_("Conversion script failed"),
944 bformat(_("%1$s is from an older version"
945 " of LyX, but the lyx2lyx script"
946 " failed to convert it."),
947 from_utf8(filename.absFilename())));
949 Alert::error(_("Conversion script failed"),
950 bformat(_("%1$s is from a newer version"
951 " of LyX and cannot be converted by the"
953 from_utf8(filename.absFilename())));
956 bool const ret = readFile(tmpfile);
957 // Do stuff with tmpfile name and buffer name here.
958 return ret ? success : failure;
963 if (readDocument(lex)) {
964 Alert::error(_("Document format failure"),
965 bformat(_("%1$s ended unexpectedly, which means"
966 " that it is probably corrupted."),
967 from_utf8(filename.absFilename())));
971 d->file_fully_loaded = true;
976 // Should probably be moved to somewhere else: BufferView? GuiView?
977 bool Buffer::save() const
979 // ask if the disk file has been externally modified (use checksum method)
980 if (fileName().exists() && isExternallyModified(checksum_method)) {
981 docstring const file = makeDisplayPath(absFileName(), 20);
982 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
983 "you want to overwrite this file?"), file);
984 int const ret = Alert::prompt(_("Overwrite modified file?"),
985 text, 1, 1, _("&Overwrite"), _("&Cancel"));
990 // We don't need autosaves in the immediate future. (Asger)
991 resetAutosaveTimers();
994 bool madeBackup = false;
996 // make a backup if the file already exists
997 if (lyxrc.make_backup && fileName().exists()) {
998 backupName = FileName(absFileName() + '~');
999 if (!lyxrc.backupdir_path.empty()) {
1000 string const mangledName =
1001 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
1002 backupName = FileName(addName(lyxrc.backupdir_path,
1005 if (fileName().moveTo(backupName)) {
1008 Alert::error(_("Backup failure"),
1009 bformat(_("Cannot create backup file %1$s.\n"
1010 "Please check whether the directory exists and is writeable."),
1011 from_utf8(backupName.absFilename())));
1012 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1016 if (writeFile(d->filename)) {
1020 // Saving failed, so backup is not backup
1022 backupName.moveTo(d->filename);
1028 bool Buffer::writeFile(FileName const & fname) const
1030 if (d->read_only && fname == d->filename)
1033 bool retval = false;
1035 docstring const str = bformat(_("Saving document %1$s..."),
1036 makeDisplayPath(fname.absFilename()));
1039 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1041 if (params().compressed) {
1042 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1043 retval = ofs && write(ofs);
1045 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1046 retval = ofs && write(ofs);
1050 message(str + _(" could not write file!"));
1055 // removeAutosaveFile();
1057 saveCheckSum(d->filename);
1058 message(str + _(" done."));
1064 docstring Buffer::emergencyWrite()
1066 // No need to save if the buffer has not changed.
1070 string const doc = isUnnamed() ? onlyFilename(absFileName()) : absFileName();
1072 docstring user_message = bformat(
1073 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1075 // We try to save three places:
1076 // 1) Same place as document. Unless it is an unnamed doc.
1078 string s = absFileName();
1081 if (writeFile(FileName(s))) {
1083 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1084 return user_message;
1086 user_message += _(" Save failed! Trying again...\n");
1090 // 2) In HOME directory.
1091 string s = addName(package().home_dir().absFilename(), absFileName());
1093 lyxerr << ' ' << s << endl;
1094 if (writeFile(FileName(s))) {
1096 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1097 return user_message;
1100 user_message += _(" Save failed! Trying yet again...\n");
1102 // 3) In "/tmp" directory.
1103 // MakeAbsPath to prepend the current
1104 // drive letter on OS/2
1105 s = addName(package().temp_dir().absFilename(), absFileName());
1107 lyxerr << ' ' << s << endl;
1108 if (writeFile(FileName(s))) {
1110 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1111 return user_message;
1114 user_message += _(" Save failed! Bummer. Document is lost.");
1117 return user_message;
1121 bool Buffer::write(ostream & ofs) const
1124 // Use the standard "C" locale for file output.
1125 ofs.imbue(locale::classic());
1128 // The top of the file should not be written by params().
1130 // write out a comment in the top of the file
1131 ofs << "#LyX " << lyx_version
1132 << " created this file. For more info see http://www.lyx.org/\n"
1133 << "\\lyxformat " << LYX_FORMAT << "\n"
1134 << "\\begin_document\n";
1136 /// For each author, set 'used' to true if there is a change
1137 /// by this author in the document; otherwise set it to 'false'.
1138 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1139 AuthorList::Authors::const_iterator a_end = params().authors().end();
1140 for (; a_it != a_end; ++a_it)
1141 a_it->setUsed(false);
1143 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1144 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1145 for ( ; it != end; ++it)
1146 it->checkAuthors(params().authors());
1148 // now write out the buffer parameters.
1149 ofs << "\\begin_header\n";
1150 params().writeFile(ofs);
1151 ofs << "\\end_header\n";
1154 ofs << "\n\\begin_body\n";
1156 ofs << "\n\\end_body\n";
1158 // Write marker that shows file is complete
1159 ofs << "\\end_document" << endl;
1161 // Shouldn't really be needed....
1164 // how to check if close went ok?
1165 // Following is an attempt... (BE 20001011)
1167 // good() returns false if any error occured, including some
1168 // formatting error.
1169 // bad() returns true if something bad happened in the buffer,
1170 // which should include file system full errors.
1175 lyxerr << "File was not closed properly." << endl;
1182 bool Buffer::makeLaTeXFile(FileName const & fname,
1183 string const & original_path,
1184 OutputParams const & runparams_in,
1185 bool output_preamble, bool output_body) const
1187 OutputParams runparams = runparams_in;
1188 if (params().useXetex)
1189 runparams.flavor = OutputParams::XETEX;
1191 string const encoding = runparams.encoding->iconvName();
1192 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1195 try { ofs.reset(encoding); }
1196 catch (iconv_codecvt_facet_exception & e) {
1197 lyxerr << "Caught iconv exception: " << e.what() << endl;
1198 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1199 "verify that the support software for your encoding (%1$s) is "
1200 "properly installed"), from_ascii(encoding)));
1203 if (!openFileWrite(ofs, fname))
1206 //TexStream ts(ofs.rdbuf(), &texrow());
1207 ErrorList & errorList = d->errorLists["Export"];
1209 bool failed_export = false;
1212 writeLaTeXSource(ofs, original_path,
1213 runparams, output_preamble, output_body);
1215 catch (EncodingException & e) {
1216 odocstringstream ods;
1217 ods.put(e.failed_char);
1219 oss << "0x" << hex << e.failed_char << dec;
1220 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1221 " (code point %2$s)"),
1222 ods.str(), from_utf8(oss.str()));
1223 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1224 "representable in the chosen encoding.\n"
1225 "Changing the document encoding to utf8 could help."),
1226 e.par_id, e.pos, e.pos + 1));
1227 failed_export = true;
1229 catch (iconv_codecvt_facet_exception & e) {
1230 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1231 _(e.what()), -1, 0, 0));
1232 failed_export = true;
1234 catch (exception const & e) {
1235 errorList.push_back(ErrorItem(_("conversion failed"),
1236 _(e.what()), -1, 0, 0));
1237 failed_export = true;
1240 lyxerr << "Caught some really weird exception..." << endl;
1246 failed_export = true;
1247 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1251 return !failed_export;
1255 void Buffer::writeLaTeXSource(odocstream & os,
1256 string const & original_path,
1257 OutputParams const & runparams_in,
1258 bool const output_preamble, bool const output_body) const
1260 // The child documents, if any, shall be already loaded at this point.
1262 OutputParams runparams = runparams_in;
1264 // Classify the unicode characters appearing in math insets
1265 Encodings::initUnicodeMath(*this);
1267 // validate the buffer.
1268 LYXERR(Debug::LATEX, " Validating buffer...");
1269 LaTeXFeatures features(*this, params(), runparams);
1271 LYXERR(Debug::LATEX, " Buffer validation done.");
1273 // The starting paragraph of the coming rows is the
1274 // first paragraph of the document. (Asger)
1275 if (output_preamble && runparams.nice) {
1276 os << "%% LyX " << lyx_version << " created this file. "
1277 "For more info, see http://www.lyx.org/.\n"
1278 "%% Do not edit unless you really know what "
1280 d->texrow.newline();
1281 d->texrow.newline();
1283 LYXERR(Debug::INFO, "lyx document header finished");
1285 // Don't move this behind the parent_buffer=0 code below,
1286 // because then the macros will not get the right "redefinition"
1287 // flag as they don't see the parent macros which are output before.
1290 // fold macros if possible, still with parent buffer as the
1291 // macros will be put in the prefix anyway.
1292 updateMacroInstances();
1294 // There are a few differences between nice LaTeX and usual files:
1295 // usual is \batchmode and has a
1296 // special input@path to allow the including of figures
1297 // with either \input or \includegraphics (what figinsets do).
1298 // input@path is set when the actual parameter
1299 // original_path is set. This is done for usual tex-file, but not
1300 // for nice-latex-file. (Matthias 250696)
1301 // Note that input@path is only needed for something the user does
1302 // in the preamble, included .tex files or ERT, files included by
1303 // LyX work without it.
1304 if (output_preamble) {
1305 if (!runparams.nice) {
1306 // code for usual, NOT nice-latex-file
1307 os << "\\batchmode\n"; // changed
1308 // from \nonstopmode
1309 d->texrow.newline();
1311 if (!original_path.empty()) {
1313 // We don't know the encoding of inputpath
1314 docstring const inputpath = from_utf8(support::latex_path(original_path));
1315 docstring uncodable_glyphs;
1316 Encoding const * const enc = runparams.encoding;
1318 for (size_t n = 0; n < inputpath.size(); ++n) {
1319 docstring const glyph =
1320 docstring(1, inputpath[n]);
1321 if (enc->latexChar(inputpath[n], true) != glyph) {
1322 LYXERR0("Uncodable character '"
1324 << "' in input path!");
1325 uncodable_glyphs += glyph;
1330 // warn user if we found uncodable glyphs.
1331 if (!uncodable_glyphs.empty()) {
1332 frontend::Alert::warning(_("Uncodable character in file path"),
1333 support::bformat(_("The path of your document\n"
1335 "contains glyphs that are unknown in the\n"
1336 "current document encoding (namely %2$s).\n"
1337 "This will likely result in incomplete output.\n\n"
1338 "Choose an appropriate document encoding (such as utf8)\n"
1339 "or change the file path name."), inputpath, uncodable_glyphs));
1341 os << "\\makeatletter\n"
1342 << "\\def\\input@path{{"
1343 << inputpath << "/}}\n"
1344 << "\\makeatother\n";
1345 d->texrow.newline();
1346 d->texrow.newline();
1347 d->texrow.newline();
1351 // get parent macros (if this buffer has a parent) which will be
1352 // written at the document begin further down.
1353 MacroSet parentMacros;
1354 listParentMacros(parentMacros, features);
1356 // Write the preamble
1357 runparams.use_babel = params().writeLaTeX(os, features,
1359 d->filename.onlyPath());
1361 runparams.use_japanese = features.isRequired("japanese");
1367 os << "\\begin{document}\n";
1368 d->texrow.newline();
1370 // output the parent macros
1371 MacroSet::iterator it = parentMacros.begin();
1372 MacroSet::iterator end = parentMacros.end();
1373 for (; it != end; ++it) {
1374 int num_lines = (*it)->write(os, true);
1375 d->texrow.newlines(num_lines);
1378 } // output_preamble
1380 d->texrow.start(paragraphs().begin()->id(), 0);
1382 LYXERR(Debug::INFO, "preamble finished, now the body.");
1384 // if we are doing a real file with body, even if this is the
1385 // child of some other buffer, let's cut the link here.
1386 // This happens for example if only a child document is printed.
1387 Buffer const * save_parent = 0;
1388 if (output_preamble) {
1389 save_parent = d->parent();
1394 latexParagraphs(*this, text(), os, d->texrow, runparams);
1396 // Restore the parenthood if needed
1397 if (output_preamble)
1398 d->setParent(save_parent);
1400 // add this just in case after all the paragraphs
1402 d->texrow.newline();
1404 if (output_preamble) {
1405 os << "\\end{document}\n";
1406 d->texrow.newline();
1407 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1409 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1411 runparams_in.encoding = runparams.encoding;
1413 // Just to be sure. (Asger)
1414 d->texrow.newline();
1416 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1417 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1421 bool Buffer::isLatex() const
1423 return params().documentClass().outputType() == LATEX;
1427 bool Buffer::isLiterate() const
1429 return params().documentClass().outputType() == LITERATE;
1433 bool Buffer::isDocBook() const
1435 return params().documentClass().outputType() == DOCBOOK;
1439 void Buffer::makeDocBookFile(FileName const & fname,
1440 OutputParams const & runparams,
1441 bool const body_only) const
1443 LYXERR(Debug::LATEX, "makeDocBookFile...");
1446 if (!openFileWrite(ofs, fname))
1449 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1453 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1457 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1458 OutputParams const & runparams,
1459 bool const only_body) const
1461 LaTeXFeatures features(*this, params(), runparams);
1466 DocumentClass const & tclass = params().documentClass();
1467 string const top_element = tclass.latexname();
1470 if (runparams.flavor == OutputParams::XML)
1471 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1474 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1477 if (! tclass.class_header().empty())
1478 os << from_ascii(tclass.class_header());
1479 else if (runparams.flavor == OutputParams::XML)
1480 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1481 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1483 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1485 docstring preamble = from_utf8(params().preamble);
1486 if (runparams.flavor != OutputParams::XML ) {
1487 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1488 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1489 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1490 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1493 string const name = runparams.nice
1494 ? changeExtension(absFileName(), ".sgml") : fname;
1495 preamble += features.getIncludedFiles(name);
1496 preamble += features.getLyXSGMLEntities();
1498 if (!preamble.empty()) {
1499 os << "\n [ " << preamble << " ]";
1504 string top = top_element;
1506 if (runparams.flavor == OutputParams::XML)
1507 top += params().language->code();
1509 top += params().language->code().substr(0, 2);
1512 if (!params().options.empty()) {
1514 top += params().options;
1517 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1518 << " file was created by LyX " << lyx_version
1519 << "\n See http://www.lyx.org/ for more information -->\n";
1521 params().documentClass().counters().reset();
1525 sgml::openTag(os, top);
1527 docbookParagraphs(text(), *this, os, runparams);
1528 sgml::closeTag(os, top_element);
1532 void Buffer::makeLyXHTMLFile(FileName const & fname,
1533 OutputParams const & runparams,
1534 bool const body_only) const
1536 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1539 if (!openFileWrite(ofs, fname))
1542 writeLyXHTMLSource(ofs, runparams, body_only);
1546 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1550 void Buffer::writeLyXHTMLSource(odocstream & os,
1551 OutputParams const & runparams,
1552 bool const only_body) const
1554 LaTeXFeatures features(*this, params(), runparams);
1556 updateBuffer(UpdateMaster, OutputUpdate);
1557 checkBibInfoCache();
1558 d->bibinfo_.makeCitationLabels(*this);
1560 updateMacroInstances();
1563 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1564 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";
1565 // FIXME Language should be set properly.
1566 os << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n";
1568 // FIXME Presumably need to set this right
1569 os << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1570 os << "<title>" << features.htmlTitle() << "</title>\n";
1572 os << "\n<!-- Text Class Preamble -->\n"
1573 << features.getTClassHTMLPreamble()
1574 << "\n<!-- Premable Snippets -->\n"
1575 << from_utf8(features.getPreambleSnippets());
1577 os << "\n<!-- Layout-provided Styles -->\n";
1578 docstring const styleinfo = features.getTClassHTMLStyles();
1579 if (!styleinfo.empty()) {
1580 os << "<style type='text/css'>\n"
1584 os << "</head>\n<body>\n";
1588 params().documentClass().counters().reset();
1589 xhtmlParagraphs(text(), *this, xs, runparams);
1591 os << "</body>\n</html>\n";
1595 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1596 // Other flags: -wall -v0 -x
1597 int Buffer::runChktex()
1601 // get LaTeX-Filename
1602 FileName const path(temppath());
1603 string const name = addName(path.absFilename(), latexName());
1604 string const org_path = filePath();
1606 PathChanger p(path); // path to LaTeX file
1607 message(_("Running chktex..."));
1609 // Generate the LaTeX file if neccessary
1610 OutputParams runparams(¶ms().encoding());
1611 runparams.flavor = OutputParams::LATEX;
1612 runparams.nice = false;
1613 runparams.linelen = lyxrc.plaintext_linelen;
1614 makeLaTeXFile(FileName(name), org_path, runparams);
1617 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1618 int const res = chktex.run(terr); // run chktex
1621 Alert::error(_("chktex failure"),
1622 _("Could not run chktex successfully."));
1623 } else if (res > 0) {
1624 ErrorList & errlist = d->errorLists["ChkTeX"];
1626 bufferErrors(terr, errlist);
1637 void Buffer::validate(LaTeXFeatures & features) const
1639 params().validate(features);
1643 for_each(paragraphs().begin(), paragraphs().end(),
1644 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1646 if (lyxerr.debugging(Debug::LATEX)) {
1647 features.showStruct();
1652 void Buffer::getLabelList(vector<docstring> & list) const
1654 // If this is a child document, use the parent's list instead.
1655 Buffer const * const pbuf = d->parent();
1657 pbuf->getLabelList(list);
1662 Toc & toc = d->toc_backend.toc("label");
1663 TocIterator toc_it = toc.begin();
1664 TocIterator end = toc.end();
1665 for (; toc_it != end; ++toc_it) {
1666 if (toc_it->depth() == 0)
1667 list.push_back(toc_it->str());
1672 void Buffer::updateBibfilesCache(UpdateScope scope) const
1674 // If this is a child document, use the parent's cache instead.
1675 Buffer const * const pbuf = d->parent();
1676 if (pbuf && scope != UpdateChildOnly) {
1677 pbuf->updateBibfilesCache();
1681 d->bibfiles_cache_.clear();
1682 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1683 if (it->lyxCode() == BIBTEX_CODE) {
1684 InsetBibtex const & inset =
1685 static_cast<InsetBibtex const &>(*it);
1686 support::FileNameList const bibfiles = inset.getBibFiles();
1687 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1690 } else if (it->lyxCode() == INCLUDE_CODE) {
1691 InsetInclude & inset =
1692 static_cast<InsetInclude &>(*it);
1693 inset.updateBibfilesCache();
1694 support::FileNameList const & bibfiles =
1695 inset.getBibfilesCache();
1696 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1701 // the bibinfo cache is now invalid
1702 d->bibinfo_cache_valid_ = false;
1706 void Buffer::invalidateBibinfoCache()
1708 d->bibinfo_cache_valid_ = false;
1712 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1714 // If this is a child document, use the parent's cache instead.
1715 Buffer const * const pbuf = d->parent();
1716 if (pbuf && scope != UpdateChildOnly)
1717 return pbuf->getBibfilesCache();
1719 // We update the cache when first used instead of at loading time.
1720 if (d->bibfiles_cache_.empty())
1721 const_cast<Buffer *>(this)->updateBibfilesCache(scope);
1723 return d->bibfiles_cache_;
1727 BiblioInfo const & Buffer::masterBibInfo() const
1729 // if this is a child document and the parent is already loaded
1730 // use the parent's list instead [ale990412]
1731 Buffer const * const tmp = masterBuffer();
1734 return tmp->masterBibInfo();
1735 return localBibInfo();
1739 BiblioInfo const & Buffer::localBibInfo() const
1745 void Buffer::checkBibInfoCache() const
1747 support::FileNameList const & bibfilesCache = getBibfilesCache();
1748 // compare the cached timestamps with the actual ones.
1749 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1750 support::FileNameList::const_iterator en = bibfilesCache.end();
1751 for (; ei != en; ++ ei) {
1752 time_t lastw = ei->lastModified();
1753 time_t prevw = d->bibfile_status_[*ei];
1754 if (lastw != prevw) {
1755 d->bibinfo_cache_valid_ = false;
1756 d->bibfile_status_[*ei] = lastw;
1760 if (!d->bibinfo_cache_valid_) {
1761 d->bibinfo_.clear();
1762 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1763 it->fillWithBibKeys(d->bibinfo_, it);
1764 d->bibinfo_cache_valid_ = true;
1769 bool Buffer::isDepClean(string const & name) const
1771 DepClean::const_iterator const it = d->dep_clean.find(name);
1772 if (it == d->dep_clean.end())
1778 void Buffer::markDepClean(string const & name)
1780 d->dep_clean[name] = true;
1784 bool Buffer::isExportableFormat(string const & format) const
1786 typedef vector<Format const *> Formats;
1788 formats = exportableFormats(true);
1789 Formats::const_iterator fit = formats.begin();
1790 Formats::const_iterator end = formats.end();
1791 for (; fit != end ; ++fit) {
1792 if ((*fit)->name() == format)
1799 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1802 // FIXME? if there is an Buffer LFUN that can be dispatched even
1803 // if internal, put a switch '(cmd.action)' here.
1809 switch (cmd.action) {
1811 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1812 flag.setOnOff(isReadonly());
1815 // FIXME: There is need for a command-line import.
1816 //case LFUN_BUFFER_IMPORT:
1818 case LFUN_BUFFER_AUTO_SAVE:
1821 case LFUN_BUFFER_EXPORT_CUSTOM:
1822 // FIXME: Nothing to check here?
1825 case LFUN_BUFFER_EXPORT: {
1826 docstring const arg = cmd.argument();
1827 enable = arg == "custom" || isExportable(to_utf8(arg));
1829 flag.message(bformat(
1830 _("Don't know how to export to format: %1$s"), arg));
1834 case LFUN_BUFFER_CHKTEX:
1835 enable = isLatex() && !lyxrc.chktex_command.empty();
1838 case LFUN_BUILD_PROGRAM:
1839 enable = isExportable("program");
1842 case LFUN_BRANCH_ACTIVATE:
1843 case LFUN_BRANCH_DEACTIVATE: {
1844 BranchList const & branchList = params().branchlist();
1845 docstring const branchName = cmd.argument();
1846 enable = !branchName.empty() && branchList.find(branchName);
1850 case LFUN_BRANCH_ADD:
1851 case LFUN_BRANCHES_RENAME:
1852 case LFUN_BUFFER_PRINT:
1853 // if no Buffer is present, then of course we won't be called!
1856 case LFUN_BUFFER_LANGUAGE:
1857 enable = !isReadonly();
1863 flag.setEnabled(enable);
1868 void Buffer::dispatch(string const & command, DispatchResult & result)
1870 return dispatch(lyxaction.lookupFunc(command), result);
1874 // NOTE We can end up here even if we have no GUI, because we are called
1875 // by LyX::exec to handled command-line requests. So we may need to check
1876 // whether we have a GUI or not. The boolean use_gui holds this information.
1877 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
1880 // FIXME? if there is an Buffer LFUN that can be dispatched even
1881 // if internal, put a switch '(cmd.action)' here.
1882 dr.dispatched(false);
1885 string const argument = to_utf8(func.argument());
1886 // We'll set this back to false if need be.
1887 bool dispatched = true;
1888 undo().beginUndoGroup();
1890 switch (func.action) {
1891 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1892 if (lyxvc().inUse())
1893 lyxvc().toggleReadOnly();
1895 setReadonly(!isReadonly());
1898 case LFUN_BUFFER_EXPORT: {
1899 bool success = doExport(argument, false, false);
1900 dr.setError(!success);
1902 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
1907 case LFUN_BUILD_PROGRAM:
1908 doExport("program", true, false);
1911 case LFUN_BUFFER_CHKTEX:
1915 case LFUN_BUFFER_EXPORT_CUSTOM: {
1917 string command = split(argument, format_name, ' ');
1918 Format const * format = formats.getFormat(format_name);
1920 lyxerr << "Format \"" << format_name
1921 << "\" not recognized!"
1926 // The name of the file created by the conversion process
1929 // Output to filename
1930 if (format->name() == "lyx") {
1931 string const latexname = latexName(false);
1932 filename = changeExtension(latexname,
1933 format->extension());
1934 filename = addName(temppath(), filename);
1936 if (!writeFile(FileName(filename)))
1940 doExport(format_name, true, false, filename);
1943 // Substitute $$FName for filename
1944 if (!contains(command, "$$FName"))
1945 command = "( " + command + " ) < $$FName";
1946 command = subst(command, "$$FName", filename);
1948 // Execute the command in the background
1950 call.startscript(Systemcall::DontWait, command);
1954 // FIXME: There is need for a command-line import.
1956 case LFUN_BUFFER_IMPORT:
1961 case LFUN_BUFFER_AUTO_SAVE:
1965 case LFUN_BRANCH_ADD: {
1966 docstring const branch_name = func.argument();
1967 if (branch_name.empty()) {
1971 BranchList & branch_list = params().branchlist();
1972 Branch * branch = branch_list.find(branch_name);
1974 LYXERR0("Branch " << branch_name << " already exists.");
1976 docstring const msg =
1977 bformat(_("Branch \"%1$s\" already exists."), branch_name);
1980 branch_list.add(branch_name);
1981 branch = branch_list.find(branch_name);
1982 string const x11hexname = X11hexname(branch->color());
1983 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
1984 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
1986 dr.update(Update::Force);
1991 case LFUN_BRANCH_ACTIVATE:
1992 case LFUN_BRANCH_DEACTIVATE: {
1993 BranchList & branchList = params().branchlist();
1994 docstring const branchName = func.argument();
1995 // the case without a branch name is handled elsewhere
1996 if (branchName.empty()) {
2000 Branch * branch = branchList.find(branchName);
2002 LYXERR0("Branch " << branchName << " does not exist.");
2004 docstring const msg =
2005 bformat(_("Branch \"%1$s\" does not exist."), branchName);
2008 branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
2010 dr.update(Update::Force);
2015 case LFUN_BRANCHES_RENAME: {
2016 if (func.argument().empty())
2019 docstring const oldname = from_utf8(func.getArg(0));
2020 docstring const newname = from_utf8(func.getArg(1));
2021 InsetIterator it = inset_iterator_begin(inset());
2022 InsetIterator const end = inset_iterator_end(inset());
2023 bool success = false;
2024 for (; it != end; ++it) {
2025 if (it->lyxCode() == BRANCH_CODE) {
2026 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2027 if (ins.branch() == oldname) {
2028 undo().recordUndo(it);
2029 ins.rename(newname);
2034 if (it->lyxCode() == INCLUDE_CODE) {
2035 // get buffer of external file
2036 InsetInclude const & ins =
2037 static_cast<InsetInclude const &>(*it);
2038 Buffer * child = ins.getChildBuffer();
2041 child->dispatch(func, dr);
2046 dr.update(Update::Force);
2050 case LFUN_BUFFER_PRINT: {
2051 // we'll assume there's a problem until we succeed
2053 string target = func.getArg(0);
2054 string target_name = func.getArg(1);
2055 string command = func.getArg(2);
2058 || target_name.empty()
2059 || command.empty()) {
2060 LYXERR0("Unable to parse " << func.argument());
2061 docstring const msg =
2062 bformat(_("Unable to parse \"%1$s\""), func.argument());
2066 if (target != "printer" && target != "file") {
2067 LYXERR0("Unrecognized target \"" << target << '"');
2068 docstring const msg =
2069 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2074 bool const update_unincluded =
2075 params().maintain_unincluded_children
2076 && !params().getIncludedChildren().empty();
2077 if (!doExport("dvi", true, update_unincluded)) {
2078 showPrintError(absFileName());
2079 dr.setMessage(_("Error exporting to DVI."));
2083 // Push directory path.
2084 string const path = temppath();
2085 // Prevent the compiler from optimizing away p
2089 // there are three cases here:
2090 // 1. we print to a file
2091 // 2. we print directly to a printer
2092 // 3. we print using a spool command (print to file first)
2095 string const dviname = changeExtension(latexName(true), "dvi");
2097 if (target == "printer") {
2098 if (!lyxrc.print_spool_command.empty()) {
2099 // case 3: print using a spool
2100 string const psname = changeExtension(dviname,".ps");
2101 command += ' ' + lyxrc.print_to_file
2104 + quoteName(dviname);
2106 string command2 = lyxrc.print_spool_command + ' ';
2107 if (target_name != "default") {
2108 command2 += lyxrc.print_spool_printerprefix
2112 command2 += quoteName(psname);
2114 // If successful, then spool command
2115 res = one.startscript(Systemcall::Wait, command);
2118 // If there's no GUI, we have to wait on this command. Otherwise,
2119 // LyX deletes the temporary directory, and with it the spooled
2120 // file, before it can be printed!!
2121 Systemcall::Starttype stype = use_gui ?
2122 Systemcall::DontWait : Systemcall::Wait;
2123 res = one.startscript(stype, command2);
2126 // case 2: print directly to a printer
2127 if (target_name != "default")
2128 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2130 Systemcall::Starttype stype = use_gui ?
2131 Systemcall::DontWait : Systemcall::Wait;
2132 res = one.startscript(stype, command + quoteName(dviname));
2136 // case 1: print to a file
2137 FileName const filename(makeAbsPath(target_name, filePath()));
2138 FileName const dvifile(makeAbsPath(dviname, path));
2139 if (filename.exists()) {
2140 docstring text = bformat(
2141 _("The file %1$s already exists.\n\n"
2142 "Do you want to overwrite that file?"),
2143 makeDisplayPath(filename.absFilename()));
2144 if (Alert::prompt(_("Overwrite file?"),
2145 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2148 command += ' ' + lyxrc.print_to_file
2149 + quoteName(filename.toFilesystemEncoding())
2151 + quoteName(dvifile.toFilesystemEncoding());
2153 Systemcall::Starttype stype = use_gui ?
2154 Systemcall::DontWait : Systemcall::Wait;
2155 res = one.startscript(stype, command);
2161 dr.setMessage(_("Error running external commands."));
2162 showPrintError(absFileName());
2167 case LFUN_BUFFER_LANGUAGE: {
2168 Language const * oldL = params().language;
2169 Language const * newL = languages.getLanguage(argument);
2170 if (!newL || oldL == newL)
2172 if (oldL->rightToLeft() == newL->rightToLeft() && !isMultiLingual())
2173 changeLanguage(oldL, newL);
2181 dr.dispatched(dispatched);
2182 undo().endUndoGroup();
2186 void Buffer::changeLanguage(Language const * from, Language const * to)
2188 LASSERT(from, /**/);
2191 for_each(par_iterator_begin(),
2193 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2197 bool Buffer::isMultiLingual() const
2199 ParConstIterator end = par_iterator_end();
2200 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2201 if (it->isMultiLingual(params()))
2208 std::set<Language const *> Buffer::getLanguages() const
2210 std::set<Language const *> languages;
2211 getLanguages(languages);
2216 void Buffer::getLanguages(std::set<Language const *> & languages) const
2218 ParConstIterator end = par_iterator_end();
2219 // add the buffer language, even if it's not actively used
2220 languages.insert(language());
2221 // iterate over the paragraphs
2222 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2223 it->getLanguages(languages);
2225 std::vector<Buffer *> clist = getChildren();
2226 for (vector<Buffer *>::const_iterator cit = clist.begin();
2227 cit != clist.end(); ++cit)
2228 (*cit)->getLanguages(languages);
2232 DocIterator Buffer::getParFromID(int const id) const
2234 Buffer * buf = const_cast<Buffer *>(this);
2236 // John says this is called with id == -1 from undo
2237 lyxerr << "getParFromID(), id: " << id << endl;
2238 return doc_iterator_end(buf);
2241 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2242 if (it.paragraph().id() == id)
2245 return doc_iterator_end(buf);
2249 bool Buffer::hasParWithID(int const id) const
2251 return !getParFromID(id).atEnd();
2255 ParIterator Buffer::par_iterator_begin()
2257 return ParIterator(doc_iterator_begin(this));
2261 ParIterator Buffer::par_iterator_end()
2263 return ParIterator(doc_iterator_end(this));
2267 ParConstIterator Buffer::par_iterator_begin() const
2269 return ParConstIterator(doc_iterator_begin(this));
2273 ParConstIterator Buffer::par_iterator_end() const
2275 return ParConstIterator(doc_iterator_end(this));
2279 Language const * Buffer::language() const
2281 return params().language;
2285 docstring const Buffer::B_(string const & l10n) const
2287 return params().B_(l10n);
2291 bool Buffer::isClean() const
2293 return d->lyx_clean;
2297 bool Buffer::isExternallyModified(CheckMethod method) const
2299 LASSERT(d->filename.exists(), /**/);
2300 // if method == timestamp, check timestamp before checksum
2301 return (method == checksum_method
2302 || d->timestamp_ != d->filename.lastModified())
2303 && d->checksum_ != d->filename.checksum();
2307 void Buffer::saveCheckSum(FileName const & file) const
2309 if (file.exists()) {
2310 d->timestamp_ = file.lastModified();
2311 d->checksum_ = file.checksum();
2313 // in the case of save to a new file.
2320 void Buffer::markClean() const
2322 if (!d->lyx_clean) {
2323 d->lyx_clean = true;
2326 // if the .lyx file has been saved, we don't need an
2328 d->bak_clean = true;
2332 void Buffer::setUnnamed(bool flag)
2338 bool Buffer::isUnnamed() const
2345 /// Don't check unnamed, here: isInternal() is used in
2346 /// newBuffer(), where the unnamed flag has not been set by anyone
2347 /// yet. Also, for an internal buffer, there should be no need for
2348 /// retrieving fileName() nor for checking if it is unnamed or not.
2349 bool Buffer::isInternal() const
2351 return fileName().extension() == "internal";
2355 void Buffer::markDirty()
2358 d->lyx_clean = false;
2361 d->bak_clean = false;
2363 DepClean::iterator it = d->dep_clean.begin();
2364 DepClean::const_iterator const end = d->dep_clean.end();
2366 for (; it != end; ++it)
2371 FileName Buffer::fileName() const
2377 string Buffer::absFileName() const
2379 return d->filename.absFilename();
2383 string Buffer::filePath() const
2385 return d->filename.onlyPath().absFilename() + "/";
2389 bool Buffer::isReadonly() const
2391 return d->read_only;
2395 void Buffer::setParent(Buffer const * buffer)
2397 // Avoids recursive include.
2398 d->setParent(buffer == this ? 0 : buffer);
2403 Buffer const * Buffer::parent() const
2409 void Buffer::Impl::collectRelatives(BufferSet & bufs) const
2411 bufs.insert(owner_);
2413 parent()->d->collectRelatives(bufs);
2415 // loop over children
2416 BufferPositionMap::const_iterator it = children_positions.begin();
2417 BufferPositionMap::const_iterator end = children_positions.end();
2418 for (; it != end; ++it)
2419 bufs.insert(const_cast<Buffer *>(it->first));
2423 std::vector<Buffer const *> Buffer::allRelatives() const
2426 d->collectRelatives(bufs);
2427 BufferSet::iterator it = bufs.begin();
2428 std::vector<Buffer const *> ret;
2429 for (; it != bufs.end(); ++it)
2435 Buffer const * Buffer::masterBuffer() const
2437 Buffer const * const pbuf = d->parent();
2441 return pbuf->masterBuffer();
2445 bool Buffer::isChild(Buffer * child) const
2447 return d->children_positions.find(child) != d->children_positions.end();
2451 DocIterator Buffer::firstChildPosition(Buffer const * child)
2453 Impl::BufferPositionMap::iterator it;
2454 it = d->children_positions.find(child);
2455 if (it == d->children_positions.end())
2456 return DocIterator(this);
2461 void Buffer::getChildren(std::vector<Buffer *> & clist, bool grand_children) const
2463 // loop over children
2464 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2465 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2466 for (; it != end; ++it) {
2467 Buffer * child = const_cast<Buffer *>(it->first);
2468 clist.push_back(child);
2469 if (grand_children) {
2470 // there might be grandchildren
2471 vector<Buffer *> glist = child->getChildren();
2472 clist.insert(clist.end(), glist.begin(), glist.end());
2478 vector<Buffer *> Buffer::getChildren(bool grand_children) const
2481 getChildren(v, grand_children);
2486 template<typename M>
2487 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
2492 typename M::const_iterator it = m.lower_bound(x);
2493 if (it == m.begin())
2501 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
2502 DocIterator const & pos) const
2504 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2506 // if paragraphs have no macro context set, pos will be empty
2510 // we haven't found anything yet
2511 DocIterator bestPos = owner_->par_iterator_begin();
2512 MacroData const * bestData = 0;
2514 // find macro definitions for name
2515 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
2516 if (nameIt != macros.end()) {
2517 // find last definition in front of pos or at pos itself
2518 PositionScopeMacroMap::const_iterator it
2519 = greatest_below(nameIt->second, pos);
2520 if (it != nameIt->second.end()) {
2522 // scope ends behind pos?
2523 if (pos < it->second.first) {
2524 // Looks good, remember this. If there
2525 // is no external macro behind this,
2526 // we found the right one already.
2527 bestPos = it->first;
2528 bestData = &it->second.second;
2532 // try previous macro if there is one
2533 if (it == nameIt->second.begin())
2540 // find macros in included files
2541 PositionScopeBufferMap::const_iterator it
2542 = greatest_below(position_to_children, pos);
2543 if (it == position_to_children.end())
2544 // no children before
2548 // do we know something better (i.e. later) already?
2549 if (it->first < bestPos )
2552 // scope ends behind pos?
2553 if (pos < it->second.first) {
2554 // look for macro in external file
2556 MacroData const * data
2557 = it->second.second->getMacro(name, false);
2560 bestPos = it->first;
2566 // try previous file if there is one
2567 if (it == position_to_children.begin())
2572 // return the best macro we have found
2577 MacroData const * Buffer::getMacro(docstring const & name,
2578 DocIterator const & pos, bool global) const
2583 // query buffer macros
2584 MacroData const * data = d->getBufferMacro(name, pos);
2588 // If there is a master buffer, query that
2589 Buffer const * const pbuf = d->parent();
2591 d->macro_lock = true;
2592 MacroData const * macro = pbuf->getMacro(
2593 name, *this, false);
2594 d->macro_lock = false;
2600 data = MacroTable::globalMacros().get(name);
2609 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2611 // set scope end behind the last paragraph
2612 DocIterator scope = par_iterator_begin();
2613 scope.pit() = scope.lastpit() + 1;
2615 return getMacro(name, scope, global);
2619 MacroData const * Buffer::getMacro(docstring const & name,
2620 Buffer const & child, bool global) const
2622 // look where the child buffer is included first
2623 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2624 if (it == d->children_positions.end())
2627 // check for macros at the inclusion position
2628 return getMacro(name, it->second, global);
2632 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
2634 pit_type const lastpit = it.lastpit();
2636 // look for macros in each paragraph
2637 while (it.pit() <= lastpit) {
2638 Paragraph & par = it.paragraph();
2640 // iterate over the insets of the current paragraph
2641 InsetList const & insets = par.insetList();
2642 InsetList::const_iterator iit = insets.begin();
2643 InsetList::const_iterator end = insets.end();
2644 for (; iit != end; ++iit) {
2645 it.pos() = iit->pos;
2647 // is it a nested text inset?
2648 if (iit->inset->asInsetText()) {
2649 // Inset needs its own scope?
2650 InsetText const * itext = iit->inset->asInsetText();
2651 bool newScope = itext->isMacroScope();
2653 // scope which ends just behind the inset
2654 DocIterator insetScope = it;
2657 // collect macros in inset
2658 it.push_back(CursorSlice(*iit->inset));
2659 updateMacros(it, newScope ? insetScope : scope);
2664 // is it an external file?
2665 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2666 // get buffer of external file
2667 InsetInclude const & inset =
2668 static_cast<InsetInclude const &>(*iit->inset);
2670 Buffer * child = inset.getChildBuffer();
2675 // register its position, but only when it is
2676 // included first in the buffer
2677 if (children_positions.find(child) ==
2678 children_positions.end())
2679 children_positions[child] = it;
2681 // register child with its scope
2682 position_to_children[it] = Impl::ScopeBuffer(scope, child);
2686 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2690 MathMacroTemplate & macroTemplate =
2691 static_cast<MathMacroTemplate &>(*iit->inset);
2692 MacroContext mc(owner_, it);
2693 macroTemplate.updateToContext(mc);
2696 bool valid = macroTemplate.validMacro();
2697 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2698 // then the BufferView's cursor will be invalid in
2699 // some cases which leads to crashes.
2704 // FIXME (Abdel), I don't understandt why we pass 'it' here
2705 // instead of 'macroTemplate' defined above... is this correct?
2706 macros[macroTemplate.name()][it] =
2707 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
2717 void Buffer::updateMacros() const
2722 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2724 // start with empty table
2726 d->children_positions.clear();
2727 d->position_to_children.clear();
2729 // Iterate over buffer, starting with first paragraph
2730 // The scope must be bigger than any lookup DocIterator
2731 // later. For the global lookup, lastpit+1 is used, hence
2732 // we use lastpit+2 here.
2733 DocIterator it = par_iterator_begin();
2734 DocIterator outerScope = it;
2735 outerScope.pit() = outerScope.lastpit() + 2;
2736 d->updateMacros(it, outerScope);
2740 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
2742 InsetIterator it = inset_iterator_begin(inset());
2743 InsetIterator const end = inset_iterator_end(inset());
2744 for (; it != end; ++it) {
2745 if (it->lyxCode() == BRANCH_CODE) {
2746 InsetBranch & br = static_cast<InsetBranch &>(*it);
2747 docstring const name = br.branch();
2748 if (!from_master && !params().branchlist().find(name))
2749 result.push_back(name);
2750 else if (from_master && !masterBuffer()->params().branchlist().find(name))
2751 result.push_back(name);
2754 if (it->lyxCode() == INCLUDE_CODE) {
2755 // get buffer of external file
2756 InsetInclude const & ins =
2757 static_cast<InsetInclude const &>(*it);
2758 Buffer * child = ins.getChildBuffer();
2761 child->getUsedBranches(result, true);
2764 // remove duplicates
2769 void Buffer::updateMacroInstances() const
2771 LYXERR(Debug::MACROS, "updateMacroInstances for "
2772 << d->filename.onlyFileName());
2773 DocIterator it = doc_iterator_begin(this);
2775 DocIterator const end = doc_iterator_end(this);
2776 for (; it != end; it.forwardInset()) {
2777 // look for MathData cells in InsetMathNest insets
2778 InsetMath * minset = it.nextInset()->asInsetMath();
2782 // update macro in all cells of the InsetMathNest
2783 DocIterator::idx_type n = minset->nargs();
2784 MacroContext mc = MacroContext(this, it);
2785 for (DocIterator::idx_type i = 0; i < n; ++i) {
2786 MathData & data = minset->cell(i);
2787 data.updateMacros(0, mc);
2793 void Buffer::listMacroNames(MacroNameSet & macros) const
2798 d->macro_lock = true;
2800 // loop over macro names
2801 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2802 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2803 for (; nameIt != nameEnd; ++nameIt)
2804 macros.insert(nameIt->first);
2806 // loop over children
2807 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2808 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2809 for (; it != end; ++it)
2810 it->first->listMacroNames(macros);
2813 Buffer const * const pbuf = d->parent();
2815 pbuf->listMacroNames(macros);
2817 d->macro_lock = false;
2821 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2823 Buffer const * const pbuf = d->parent();
2828 pbuf->listMacroNames(names);
2831 MacroNameSet::iterator it = names.begin();
2832 MacroNameSet::iterator end = names.end();
2833 for (; it != end; ++it) {
2835 MacroData const * data =
2836 pbuf->getMacro(*it, *this, false);
2838 macros.insert(data);
2840 // we cannot access the original MathMacroTemplate anymore
2841 // here to calls validate method. So we do its work here manually.
2842 // FIXME: somehow make the template accessible here.
2843 if (data->optionals() > 0)
2844 features.require("xargs");
2850 Buffer::References & Buffer::references(docstring const & label)
2853 return const_cast<Buffer *>(masterBuffer())->references(label);
2855 RefCache::iterator it = d->ref_cache_.find(label);
2856 if (it != d->ref_cache_.end())
2857 return it->second.second;
2859 static InsetLabel const * dummy_il = 0;
2860 static References const dummy_refs;
2861 it = d->ref_cache_.insert(
2862 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2863 return it->second.second;
2867 Buffer::References const & Buffer::references(docstring const & label) const
2869 return const_cast<Buffer *>(this)->references(label);
2873 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2875 masterBuffer()->d->ref_cache_[label].first = il;
2879 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2881 return masterBuffer()->d->ref_cache_[label].first;
2885 void Buffer::clearReferenceCache() const
2888 d->ref_cache_.clear();
2892 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2895 //FIXME: This does not work for child documents yet.
2896 LASSERT(code == CITE_CODE, /**/);
2897 // Check if the label 'from' appears more than once
2898 vector<docstring> labels;
2900 checkBibInfoCache();
2901 BiblioInfo const & keys = masterBibInfo();
2902 BiblioInfo::const_iterator bit = keys.begin();
2903 BiblioInfo::const_iterator bend = keys.end();
2905 for (; bit != bend; ++bit)
2907 labels.push_back(bit->first);
2910 if (count(labels.begin(), labels.end(), from) > 1)
2913 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2914 if (it->lyxCode() == code) {
2915 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2916 docstring const oldValue = inset.getParam(paramName);
2917 if (oldValue == from)
2918 inset.setParam(paramName, to);
2924 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2925 pit_type par_end, bool full_source) const
2927 OutputParams runparams(¶ms().encoding());
2928 runparams.nice = true;
2929 runparams.flavor = params().useXetex ?
2930 OutputParams::XETEX : OutputParams::LATEX;
2931 runparams.linelen = lyxrc.plaintext_linelen;
2932 // No side effect of file copying and image conversion
2933 runparams.dryrun = true;
2936 os << "% " << _("Preview source code") << "\n\n";
2938 d->texrow.newline();
2939 d->texrow.newline();
2941 writeDocBookSource(os, absFileName(), runparams, false);
2943 // latex or literate
2944 writeLaTeXSource(os, string(), runparams, true, true);
2946 runparams.par_begin = par_begin;
2947 runparams.par_end = par_end;
2948 if (par_begin + 1 == par_end) {
2950 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2954 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2955 convert<docstring>(par_begin),
2956 convert<docstring>(par_end - 1))
2963 // output paragraphs
2965 docbookParagraphs(text(), *this, os, runparams);
2967 // latex or literate
2968 latexParagraphs(*this, text(), os, texrow, runparams);
2973 ErrorList & Buffer::errorList(string const & type) const
2975 static ErrorList emptyErrorList;
2976 map<string, ErrorList>::iterator it = d->errorLists.find(type);
2977 if (it == d->errorLists.end())
2978 return emptyErrorList;
2984 void Buffer::updateTocItem(std::string const & type,
2985 DocIterator const & dit) const
2988 d->gui_->updateTocItem(type, dit);
2992 void Buffer::structureChanged() const
2995 d->gui_->structureChanged();
2999 void Buffer::errors(string const & err, bool from_master) const
3002 d->gui_->errors(err, from_master);
3006 void Buffer::message(docstring const & msg) const
3009 d->gui_->message(msg);
3013 void Buffer::setBusy(bool on) const
3016 d->gui_->setBusy(on);
3020 void Buffer::updateTitles() const
3023 d->wa_->updateTitles();
3027 void Buffer::resetAutosaveTimers() const
3030 d->gui_->resetAutosaveTimers();
3034 bool Buffer::hasGuiDelegate() const
3040 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3049 class AutoSaveBuffer : public ForkedProcess {
3052 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3053 : buffer_(buffer), fname_(fname) {}
3055 virtual boost::shared_ptr<ForkedProcess> clone() const
3057 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3062 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3063 from_utf8(fname_.absFilename())));
3064 return run(DontWait);
3068 virtual int generateChild();
3070 Buffer const & buffer_;
3075 int AutoSaveBuffer::generateChild()
3077 #if defined(__APPLE__)
3078 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3079 * We should use something else like threads.
3081 * Since I do not know how to determine at run time what is the OS X
3082 * version, I just disable forking altogether for now (JMarc)
3084 pid_t const pid = -1;
3086 // tmp_ret will be located (usually) in /tmp
3087 // will that be a problem?
3088 // Note that this calls ForkedCalls::fork(), so it's
3089 // ok cross-platform.
3090 pid_t const pid = fork();
3091 // If you want to debug the autosave
3092 // you should set pid to -1, and comment out the fork.
3093 if (pid != 0 && pid != -1)
3097 // pid = -1 signifies that lyx was unable
3098 // to fork. But we will do the save
3100 bool failed = false;
3101 FileName const tmp_ret = FileName::tempName("lyxauto");
3102 if (!tmp_ret.empty()) {
3103 buffer_.writeFile(tmp_ret);
3104 // assume successful write of tmp_ret
3105 if (!tmp_ret.moveTo(fname_))
3111 // failed to write/rename tmp_ret so try writing direct
3112 if (!buffer_.writeFile(fname_)) {
3113 // It is dangerous to do this in the child,
3114 // but safe in the parent, so...
3115 if (pid == -1) // emit message signal.
3116 buffer_.message(_("Autosave failed!"));
3120 if (pid == 0) // we are the child so...
3129 FileName Buffer::getAutosaveFilename() const
3131 // if the document is unnamed try to save in the backup dir, else
3132 // in the default document path, and as a last try in the filePath,
3133 // which will most often be the temporary directory
3136 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3137 : lyxrc.backupdir_path;
3138 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3141 string const fname = "#" + d->filename.onlyFileName() + "#";
3142 return makeAbsPath(fname, fpath);
3146 void Buffer::removeAutosaveFile() const
3148 FileName const f = getAutosaveFilename();
3154 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3156 FileName const newauto = getAutosaveFilename();
3158 if (newauto != oldauto && oldauto.exists())
3159 if (!oldauto.moveTo(newauto))
3160 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3164 // Perfect target for a thread...
3165 void Buffer::autoSave() const
3167 if (d->bak_clean || isReadonly()) {
3168 // We don't save now, but we'll try again later
3169 resetAutosaveTimers();
3173 // emit message signal.
3174 message(_("Autosaving current document..."));
3175 AutoSaveBuffer autosave(*this, getAutosaveFilename());
3178 d->bak_clean = true;
3180 resetAutosaveTimers();
3184 string Buffer::bufferFormat() const
3186 string format = params().documentClass().outputFormat();
3187 if (format == "latex") {
3188 if (params().useXetex)
3190 if (params().encoding().package() == Encoding::japanese)
3197 string Buffer::getDefaultOutputFormat() const
3199 if (!params().defaultOutputFormat.empty()
3200 && params().defaultOutputFormat != "default")
3201 return params().defaultOutputFormat;
3202 typedef vector<Format const *> Formats;
3203 Formats formats = exportableFormats(true);
3206 || params().useXetex
3207 || params().encoding().package() == Encoding::japanese) {
3208 if (formats.empty())
3210 // return the first we find
3211 return formats.front()->name();
3213 return lyxrc.default_view_format;
3218 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3219 bool includeall, string & result_file) const
3221 string backend_format;
3222 OutputParams runparams(¶ms().encoding());
3223 runparams.flavor = OutputParams::LATEX;
3224 runparams.linelen = lyxrc.plaintext_linelen;
3225 runparams.includeall = includeall;
3226 vector<string> backs = backends();
3227 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3228 // Get shortest path to format
3229 Graph::EdgePath path;
3230 for (vector<string>::const_iterator it = backs.begin();
3231 it != backs.end(); ++it) {
3232 Graph::EdgePath p = theConverters().getPath(*it, format);
3233 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3234 backend_format = *it;
3239 if (!put_in_tempdir) {
3240 // Only show this alert if this is an export to a non-temporary
3241 // file (not for previewing).
3242 Alert::error(_("Couldn't export file"), bformat(
3243 _("No information for exporting the format %1$s."),
3244 formats.prettyName(format)));
3248 runparams.flavor = theConverters().getFlavor(path);
3251 backend_format = format;
3252 // FIXME: Don't hardcode format names here, but use a flag
3253 if (backend_format == "pdflatex")
3254 runparams.flavor = OutputParams::PDFLATEX;
3257 string filename = latexName(false);
3258 filename = addName(temppath(), filename);
3259 filename = changeExtension(filename,
3260 formats.extension(backend_format));
3263 updateMacroInstances();
3265 // Plain text backend
3266 if (backend_format == "text") {
3267 runparams.flavor = OutputParams::TEXT;
3268 writePlaintextFile(*this, FileName(filename), runparams);
3271 else if (backend_format == "xhtml") {
3272 runparams.flavor = OutputParams::HTML;
3273 switch (params().html_math_output) {
3274 case BufferParams::MathML:
3275 runparams.math_flavor = OutputParams::MathAsMathML;
3277 case BufferParams::HTML:
3278 runparams.math_flavor = OutputParams::MathAsHTML;
3280 case BufferParams::Images:
3281 runparams.math_flavor = OutputParams::MathAsImages;
3283 case BufferParams::LaTeX:
3284 runparams.math_flavor = OutputParams::MathAsLaTeX;
3288 makeLyXHTMLFile(FileName(filename), runparams);
3289 } else if (backend_format == "lyx")
3290 writeFile(FileName(filename));
3292 else if (isDocBook()) {
3293 runparams.nice = !put_in_tempdir;
3294 makeDocBookFile(FileName(filename), runparams);
3297 else if (backend_format == format) {
3298 runparams.nice = true;
3299 if (!makeLaTeXFile(FileName(filename), string(), runparams))
3301 } else if (!lyxrc.tex_allows_spaces
3302 && contains(filePath(), ' ')) {
3303 Alert::error(_("File name error"),
3304 _("The directory path to the document cannot contain spaces."));
3307 runparams.nice = false;
3308 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
3312 string const error_type = (format == "program")
3313 ? "Build" : bufferFormat();
3314 ErrorList & error_list = d->errorLists[error_type];
3315 string const ext = formats.extension(format);
3316 FileName const tmp_result_file(changeExtension(filename, ext));
3317 bool const success = theConverters().convert(this, FileName(filename),
3318 tmp_result_file, FileName(absFileName()), backend_format, format,
3321 // Emit the signal to show the error list or copy it back to the
3322 // cloned Buffer so that it cab be emitted afterwards.
3323 if (format != backend_format) {
3324 if (d->cloned_buffer_) {
3325 d->cloned_buffer_->d->errorLists[error_type] =
3326 d->errorLists[error_type];
3329 // also to the children, in case of master-buffer-view
3330 std::vector<Buffer *> clist = getChildren();
3331 for (vector<Buffer *>::const_iterator cit = clist.begin();
3332 cit != clist.end(); ++cit) {
3333 if (d->cloned_buffer_) {
3334 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
3335 (*cit)->d->errorLists[error_type];
3337 (*cit)->errors(error_type, true);
3341 if (d->cloned_buffer_) {
3342 // Enable reverse dvi or pdf to work by copying back the texrow
3343 // object to the cloned buffer.
3344 // FIXME: There is a possibility of concurrent access to texrow
3345 // here from the main GUI thread that should be securized.
3346 d->cloned_buffer_->d->texrow = d->texrow;
3347 string const error_type = bufferFormat();
3348 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
3354 if (put_in_tempdir) {
3355 result_file = tmp_result_file.absFilename();
3359 result_file = changeExtension(d->exportFileName().absFilename(), ext);
3360 // We need to copy referenced files (e. g. included graphics
3361 // if format == "dvi") to the result dir.
3362 vector<ExportedFile> const files =
3363 runparams.exportdata->externalFiles(format);
3364 string const dest = onlyPath(result_file);
3365 CopyStatus status = SUCCESS;
3367 vector<ExportedFile>::const_iterator it = files.begin();
3368 vector<ExportedFile>::const_iterator const en = files.end();
3369 for (; it != en && status != CANCEL; ++it) {
3370 string const fmt = formats.getFormatFromFile(it->sourceName);
3371 status = copyFile(fmt, it->sourceName,
3372 makeAbsPath(it->exportName, dest),
3373 it->exportName, status == FORCE);
3376 if (status == CANCEL) {
3377 message(_("Document export cancelled."));
3378 } else if (tmp_result_file.exists()) {
3379 // Finally copy the main file
3380 status = copyFile(format, tmp_result_file,
3381 FileName(result_file), result_file,
3383 message(bformat(_("Document exported as %1$s "
3385 formats.prettyName(format),
3386 makeDisplayPath(result_file)));
3388 // This must be a dummy converter like fax (bug 1888)
3389 message(bformat(_("Document exported as %1$s"),
3390 formats.prettyName(format)));
3397 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3398 bool includeall) const
3401 // (1) export with all included children (omit \includeonly)
3402 if (includeall && !doExport(format, put_in_tempdir, true, result_file))
3404 // (2) export with included children only
3405 return doExport(format, put_in_tempdir, false, result_file);
3409 bool Buffer::preview(string const & format, bool includeall) const
3412 // (1) export with all included children (omit \includeonly)
3413 if (includeall && !doExport(format, true, true))
3415 // (2) export with included children only
3416 if (!doExport(format, true, false, result_file))
3418 return formats.view(*this, FileName(result_file), format);
3422 bool Buffer::isExportable(string const & format) const
3424 vector<string> backs = backends();
3425 for (vector<string>::const_iterator it = backs.begin();
3426 it != backs.end(); ++it)
3427 if (theConverters().isReachable(*it, format))
3433 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
3435 vector<string> const backs = backends();
3436 vector<Format const *> result =
3437 theConverters().getReachable(backs[0], only_viewable, true);
3438 for (vector<string>::const_iterator it = backs.begin() + 1;
3439 it != backs.end(); ++it) {
3440 vector<Format const *> r =
3441 theConverters().getReachable(*it, only_viewable, false);
3442 result.insert(result.end(), r.begin(), r.end());
3448 vector<string> Buffer::backends() const
3451 v.push_back(bufferFormat());
3452 // FIXME: Don't hardcode format names here, but use a flag
3453 if (v.back() == "latex")
3454 v.push_back("pdflatex");
3455 v.push_back("xhtml");
3456 v.push_back("text");
3462 bool Buffer::readFileHelper(FileName const & s)
3464 // File information about normal file
3466 docstring const file = makeDisplayPath(s.absFilename(), 50);
3467 docstring text = bformat(_("The specified document\n%1$s"
3468 "\ncould not be read."), file);
3469 Alert::error(_("Could not read document"), text);
3473 // Check if emergency save file exists and is newer.
3474 FileName const e(s.absFilename() + ".emergency");
3476 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
3477 docstring const file = makeDisplayPath(s.absFilename(), 20);
3478 docstring const text =
3479 bformat(_("An emergency save of the document "
3481 "Recover emergency save?"), file);
3482 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
3483 _("&Recover"), _("&Load Original"),
3487 // the file is not saved if we load the emergency file.
3492 if ((res = readFile(e)) == success)
3493 str = _("Document was successfully recovered.");
3495 str = _("Document was NOT successfully recovered.");
3496 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3497 from_utf8(e.absFilename()));
3499 if (!Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3500 _("&Remove"), _("&Keep it"))) {
3503 Alert::warning(_("Emergency file deleted"),
3504 _("Do not forget to save your file now!"), true);
3509 if (!Alert::prompt(_("Delete emergency file?"),
3510 _("Remove emergency file now?"), 1, 1,
3511 _("&Remove"), _("&Keep it")))
3519 // Now check if autosave file is newer.
3520 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
3522 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
3523 docstring const file = makeDisplayPath(s.absFilename(), 20);
3524 docstring const text =
3525 bformat(_("The backup of the document "
3526 "%1$s is newer.\n\nLoad the "
3527 "backup instead?"), file);
3528 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
3529 _("&Load backup"), _("Load &original"),
3533 // the file is not saved if we load the autosave file.
3537 // Here we delete the autosave
3548 bool Buffer::loadLyXFile(FileName const & s)
3550 // If the file is not readable, we try to
3551 // retrieve the file from version control.
3552 if (!s.isReadableFile()
3553 && !LyXVC::file_not_found_hook(s))
3556 if (s.isReadableFile()){
3557 // InsetInfo needs to know if file is under VCS
3558 lyxvc().file_found_hook(s);
3559 if (readFileHelper(s)) {
3560 d->read_only = !s.isWritable();
3568 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3570 TeXErrors::Errors::const_iterator cit = terr.begin();
3571 TeXErrors::Errors::const_iterator end = terr.end();
3573 for (; cit != end; ++cit) {
3576 int errorRow = cit->error_in_line;
3577 bool found = d->texrow.getIdFromRow(errorRow, id_start,
3583 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
3584 } while (found && id_start == id_end && pos_start == pos_end);
3586 errorList.push_back(ErrorItem(cit->error_desc,
3587 cit->error_text, id_start, pos_start, pos_end));
3592 void Buffer::setBuffersForInsets() const
3594 inset().setBuffer(const_cast<Buffer &>(*this));
3598 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
3600 // Use the master text class also for child documents
3601 Buffer const * const master = masterBuffer();
3602 DocumentClass const & textclass = master->params().documentClass();
3604 // do this only if we are the top-level Buffer
3605 if (scope != UpdateMaster || master == this)
3606 checkBibInfoCache();
3608 // keep the buffers to be children in this set. If the call from the
3609 // master comes back we can see which of them were actually seen (i.e.
3610 // via an InsetInclude). The remaining ones in the set need still be updated.
3611 static std::set<Buffer const *> bufToUpdate;
3612 if (scope == UpdateMaster) {
3613 // If this is a child document start with the master
3614 if (master != this) {
3615 bufToUpdate.insert(this);
3616 master->updateBuffer(UpdateMaster, utype);
3617 // Do this here in case the master has no gui associated with it. Then,
3618 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3619 if (!master->d->gui_)
3622 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3623 if (bufToUpdate.find(this) == bufToUpdate.end())
3627 // start over the counters in the master
3628 textclass.counters().reset();
3631 // update will be done below for this buffer
3632 bufToUpdate.erase(this);
3634 // update all caches
3635 clearReferenceCache();
3638 Buffer & cbuf = const_cast<Buffer &>(*this);
3640 LASSERT(!text().paragraphs().empty(), /**/);
3643 ParIterator parit = cbuf.par_iterator_begin();
3644 updateBuffer(parit, utype);
3647 // TocBackend update will be done later.
3650 cbuf.tocBackend().update();
3651 if (scope == UpdateMaster)
3652 cbuf.structureChanged();
3656 static depth_type getDepth(DocIterator const & it)
3658 depth_type depth = 0;
3659 for (size_t i = 0 ; i < it.depth() ; ++i)
3660 if (!it[i].inset().inMathed())
3661 depth += it[i].paragraph().getDepth() + 1;
3662 // remove 1 since the outer inset does not count
3666 static depth_type getItemDepth(ParIterator const & it)
3668 Paragraph const & par = *it;
3669 LabelType const labeltype = par.layout().labeltype;
3671 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3674 // this will hold the lowest depth encountered up to now.
3675 depth_type min_depth = getDepth(it);
3676 ParIterator prev_it = it;
3679 --prev_it.top().pit();
3681 // start of nested inset: go to outer par
3683 if (prev_it.empty()) {
3684 // start of document: nothing to do
3689 // We search for the first paragraph with same label
3690 // that is not more deeply nested.
3691 Paragraph & prev_par = *prev_it;
3692 depth_type const prev_depth = getDepth(prev_it);
3693 if (labeltype == prev_par.layout().labeltype) {
3694 if (prev_depth < min_depth)
3695 return prev_par.itemdepth + 1;
3696 if (prev_depth == min_depth)
3697 return prev_par.itemdepth;
3699 min_depth = min(min_depth, prev_depth);
3700 // small optimization: if we are at depth 0, we won't
3701 // find anything else
3702 if (prev_depth == 0)
3708 static bool needEnumCounterReset(ParIterator const & it)
3710 Paragraph const & par = *it;
3711 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3712 depth_type const cur_depth = par.getDepth();
3713 ParIterator prev_it = it;
3714 while (prev_it.pit()) {
3715 --prev_it.top().pit();
3716 Paragraph const & prev_par = *prev_it;
3717 if (prev_par.getDepth() <= cur_depth)
3718 return prev_par.layout().labeltype != LABEL_ENUMERATE;
3720 // start of nested inset: reset
3725 // set the label of a paragraph. This includes the counters.
3726 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
3728 BufferParams const & bp = owner_->masterBuffer()->params();
3729 DocumentClass const & textclass = bp.documentClass();
3730 Paragraph & par = it.paragraph();
3731 Layout const & layout = par.layout();
3732 Counters & counters = textclass.counters();
3734 if (par.params().startOfAppendix()) {
3735 // FIXME: only the counter corresponding to toplevel
3736 // sectioning should be reset
3738 counters.appendix(true);
3740 par.params().appendix(counters.appendix());
3742 // Compute the item depth of the paragraph
3743 par.itemdepth = getItemDepth(it);
3745 if (layout.margintype == MARGIN_MANUAL
3746 || layout.latextype == LATEX_BIB_ENVIRONMENT) {
3747 if (par.params().labelWidthString().empty())
3748 par.params().labelWidthString(par.expandLabel(layout, bp));
3750 par.params().labelWidthString(docstring());
3753 switch(layout.labeltype) {
3755 if (layout.toclevel <= bp.secnumdepth
3756 && (layout.latextype != LATEX_ENVIRONMENT
3757 || it.text()->isFirstInSequence(it.pit()))) {
3758 counters.step(layout.counter, utype);
3759 par.params().labelString(
3760 par.expandLabel(layout, bp));
3762 par.params().labelString(docstring());
3765 case LABEL_ITEMIZE: {
3766 // At some point of time we should do something more
3767 // clever here, like:
3768 // par.params().labelString(
3769 // bp.user_defined_bullet(par.itemdepth).getText());
3770 // for now, use a simple hardcoded label
3771 docstring itemlabel;
3772 switch (par.itemdepth) {
3774 itemlabel = char_type(0x2022);
3777 itemlabel = char_type(0x2013);
3780 itemlabel = char_type(0x2217);
3783 itemlabel = char_type(0x2219); // or 0x00b7
3786 par.params().labelString(itemlabel);
3790 case LABEL_ENUMERATE: {
3791 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
3793 switch (par.itemdepth) {
3802 enumcounter += "iv";
3805 // not a valid enumdepth...
3809 // Maybe we have to reset the enumeration counter.
3810 if (needEnumCounterReset(it))
3811 counters.reset(enumcounter);
3812 counters.step(enumcounter, utype);
3814 string const & lang = par.getParLanguage(bp)->code();
3815 par.params().labelString(counters.theCounter(enumcounter, lang));
3820 case LABEL_SENSITIVE: {
3821 string const & type = counters.current_float();
3822 docstring full_label;
3824 full_label = owner_->B_("Senseless!!! ");
3826 docstring name = owner_->B_(textclass.floats().getType(type).name());
3827 if (counters.hasCounter(from_utf8(type))) {
3828 string const & lang = par.getParLanguage(bp)->code();
3829 counters.step(from_utf8(type), utype);
3830 full_label = bformat(from_ascii("%1$s %2$s:"),
3832 counters.theCounter(from_utf8(type), lang));
3834 full_label = bformat(from_ascii("%1$s #:"), name);
3836 par.params().labelString(full_label);
3840 case LABEL_NO_LABEL:
3841 par.params().labelString(docstring());
3845 case LABEL_TOP_ENVIRONMENT:
3846 case LABEL_CENTERED_TOP_ENVIRONMENT:
3849 par.params().labelString(par.expandLabel(layout, bp));
3855 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
3857 LASSERT(parit.pit() == 0, /**/);
3859 // set the position of the text in the buffer to be able
3860 // to resolve macros in it. This has nothing to do with
3861 // labels, but by putting it here we avoid implementing
3862 // a whole bunch of traversal routines just for this call.
3863 parit.text()->setMacrocontextPosition(parit);
3865 depth_type maxdepth = 0;
3866 pit_type const lastpit = parit.lastpit();
3867 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
3868 // reduce depth if necessary
3869 parit->params().depth(min(parit->params().depth(), maxdepth));
3870 maxdepth = parit->getMaxDepthAfter();
3872 if (utype == OutputUpdate) {
3873 // track the active counters
3874 // we have to do this for the master buffer, since the local
3875 // buffer isn't tracking anything.
3876 masterBuffer()->params().documentClass().counters().
3877 setActiveLayout(parit->layout());
3880 // set the counter for this paragraph
3881 d->setLabel(parit, utype);
3884 InsetList::const_iterator iit = parit->insetList().begin();
3885 InsetList::const_iterator end = parit->insetList().end();
3886 for (; iit != end; ++iit) {
3887 parit.pos() = iit->pos;
3888 iit->inset->updateBuffer(parit, utype);
3894 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
3895 WordLangTuple & word_lang, docstring_list & suggestions) const
3899 suggestions.clear();
3900 word_lang = WordLangTuple();
3901 // OK, we start from here.
3902 DocIterator const end = doc_iterator_end(this);
3903 for (; from != end; from.forwardPos()) {
3904 // We are only interested in text so remove the math CursorSlice.
3905 while (from.inMathed()) {
3909 // If from is at the end of the document (which is possible
3910 // when leaving the mathed) LyX will crash later.
3914 if (from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions)) {
3919 // Do not increase progress when from == to, otherwise the word
3920 // count will be wrong.
3930 bool Buffer::reload()
3933 // e.g., read-only status could have changed due to version control
3934 d->filename.refresh();
3935 docstring const disp_fn = makeDisplayPath(d->filename.absFilename());
3937 bool const success = loadLyXFile(d->filename);
3942 message(bformat(_("Document %1$s reloaded."), disp_fn));
3944 message(bformat(_("Could not reload document %1$s."), disp_fn));
3947 thePreviews().removeLoader(*this);
3948 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
3949 thePreviews().generateBufferPreviews(*this);
3955 // FIXME We could do better here, but it is complicated. What would be
3956 // nice is to offer either (a) to save the child buffer to an appropriate
3957 // location, so that it would "move with the master", or else (b) to update
3958 // the InsetInclude so that it pointed to the same file. But (a) is a bit
3959 // complicated, because the code for this lives in GuiView.
3960 void Buffer::checkChildBuffers()
3962 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3963 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
3964 for (; it != en; ++it) {
3965 DocIterator dit = it->second;
3966 Buffer * cbuf = const_cast<Buffer *>(it->first);
3967 if (!cbuf || !theBufferList().isLoaded(cbuf))
3969 Inset * inset = dit.nextInset();
3970 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
3971 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
3972 docstring const & incfile = inset_inc->getParam("filename");
3973 string oldloc = cbuf->absFileName();
3974 string newloc = makeAbsPath(to_utf8(incfile),
3975 onlyPath(absFileName())).absFilename();
3976 if (oldloc == newloc)
3978 // the location of the child file is incorrect.
3979 Alert::warning(_("Included File Invalid"),
3980 bformat(_("Saving this document to a new location has made the file:\n"
3982 "inaccessible. You will need to update the included filename."),
3983 from_utf8(oldloc)));
3985 inset_inc->setChildBuffer(0);
3987 // invalidate cache of children
3988 d->children_positions.clear();
3989 d->position_to_children.clear();