3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
7 * \author Stefan Schimanski
9 * Full author contact details are available in file CREDITS.
17 #include "LayoutFile.h"
18 #include "BiblioInfo.h"
19 #include "BranchList.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
25 #include "Converter.h"
27 #include "DispatchResult.h"
28 #include "DocIterator.h"
30 #include "ErrorList.h"
33 #include "FuncRequest.h"
34 #include "FuncStatus.h"
35 #include "IndicesList.h"
36 #include "InsetIterator.h"
37 #include "InsetList.h"
39 #include "LaTeXFeatures.h"
43 #include "LyXAction.h"
47 #include "output_docbook.h"
49 #include "output_latex.h"
50 #include "output_xhtml.h"
51 #include "output_plaintext.h"
52 #include "Paragraph.h"
53 #include "ParagraphParameters.h"
54 #include "ParIterator.h"
55 #include "PDFOptions.h"
56 #include "SpellChecker.h"
59 #include "TexStream.h"
61 #include "TextClass.h"
62 #include "TocBackend.h"
64 #include "VCBackend.h"
66 #include "WordLangTuple.h"
69 #include "insets/InsetBibitem.h"
70 #include "insets/InsetBibtex.h"
71 #include "insets/InsetBranch.h"
72 #include "insets/InsetInclude.h"
73 #include "insets/InsetText.h"
75 #include "mathed/InsetMathHull.h"
76 #include "mathed/MacroTable.h"
77 #include "mathed/MathMacroTemplate.h"
78 #include "mathed/MathSupport.h"
80 #include "frontends/alert.h"
81 #include "frontends/Delegates.h"
82 #include "frontends/WorkAreaManager.h"
84 #include "graphics/Previews.h"
86 #include "support/lassert.h"
87 #include "support/convert.h"
88 #include "support/debug.h"
89 #include "support/docstring_list.h"
90 #include "support/ExceptionMessage.h"
91 #include "support/FileName.h"
92 #include "support/FileNameList.h"
93 #include "support/filetools.h"
94 #include "support/ForkedCalls.h"
95 #include "support/gettext.h"
96 #include "support/gzstream.h"
97 #include "support/lstrings.h"
98 #include "support/lyxalgo.h"
99 #include "support/os.h"
100 #include "support/Package.h"
101 #include "support/Path.h"
102 #include "support/Systemcall.h"
103 #include "support/textutils.h"
104 #include "support/types.h"
106 #include "support/bind.h"
107 #include "support/shared_ptr.h"
119 using namespace lyx::support;
123 namespace Alert = frontend::Alert;
124 namespace os = support::os;
128 // Do not remove the comment below, so we get merge conflict in
129 // independent branches. Instead add your own.
130 int const LYX_FORMAT = 401; // Ronen: support for \Diagram
132 typedef map<string, bool> DepClean;
133 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
135 void showPrintError(string const & name)
137 docstring str = bformat(_("Could not print the document %1$s.\n"
138 "Check that your printer is set up correctly."),
139 makeDisplayPath(name, 50));
140 Alert::error(_("Print document failed"), str);
146 typedef std::set<Buffer *> BufferSet;
152 Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
163 /// search for macro in local (buffer) table or in children
164 MacroData const * getBufferMacro(docstring const & name,
165 DocIterator const & pos) const;
167 /// Update macro table starting with position of it \param it in some
169 void updateMacros(DocIterator & it, DocIterator & scope);
171 void setLabel(ParIterator & it, UpdateType utype) const;
173 void collectRelatives(BufferSet & bufs) const;
175 /** If we have branches that use the file suffix
176 feature, return the file name with suffix appended.
178 support::FileName exportFileName() const;
185 mutable TexRow texrow;
187 /// need to regenerate .tex?
191 mutable bool lyx_clean;
193 /// is autosave needed?
194 mutable bool bak_clean;
196 /// is this a unnamed file (New...)?
202 /// name of the file the buffer is associated with.
205 /** Set to true only when the file is fully loaded.
206 * Used to prevent the premature generation of previews
207 * and by the citation inset.
209 bool file_fully_loaded;
212 mutable TocBackend toc_backend;
215 typedef pair<DocIterator, MacroData> ScopeMacro;
216 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
217 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
218 /// map from the macro name to the position map,
219 /// which maps the macro definition position to the scope and the MacroData.
220 NamePositionScopeMacroMap macros;
221 /// This seem to change the way Buffer::getMacro() works
222 mutable bool macro_lock;
224 /// positions of child buffers in the buffer
225 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
226 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
227 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
228 /// position of children buffers in this buffer
229 BufferPositionMap children_positions;
230 /// map from children inclusion positions to their scope and their buffer
231 PositionScopeBufferMap position_to_children;
233 /// Container for all sort of Buffer dependant errors.
234 map<string, ErrorList> errorLists;
236 /// timestamp and checksum used to test if the file has been externally
237 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
239 unsigned long checksum_;
242 frontend::WorkAreaManager * wa_;
244 frontend::GuiBufferDelegate * gui_;
249 /// A cache for the bibfiles (including bibfiles of loaded child
250 /// documents), needed for appropriate update of natbib labels.
251 mutable support::FileNameList bibfiles_cache_;
253 // FIXME The caching mechanism could be improved. At present, we have a
254 // cache for each Buffer, that caches all the bibliography info for that
255 // Buffer. A more efficient solution would be to have a global cache per
256 // file, and then to construct the Buffer's bibinfo from that.
257 /// A cache for bibliography info
258 mutable BiblioInfo bibinfo_;
259 /// whether the bibinfo cache is valid
260 mutable bool bibinfo_cache_valid_;
261 /// whether the bibfile cache is valid
262 mutable bool bibfile_cache_valid_;
263 /// Cache of timestamps of .bib files
264 map<FileName, time_t> bibfile_status_;
266 mutable RefCache ref_cache_;
268 /// our Text that should be wrapped in an InsetText
271 /// This is here to force the test to be done whenever parent_buffer
273 Buffer const * parent() const {
274 // if parent_buffer is not loaded, then it has been unloaded,
275 // which means that parent_buffer is an invalid pointer. So we
276 // set it to null in that case.
277 // however, the BufferList doesn't know about cloned buffers, so
278 // they will always be regarded as unloaded. in that case, we hope
280 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
282 return parent_buffer;
286 void setParent(Buffer const * pb) {
287 if (parent_buffer == pb)
290 if (!cloned_buffer_ && parent_buffer && pb)
291 LYXERR0("Warning: a buffer should not have two parents!");
293 if (!cloned_buffer_ && parent_buffer) {
294 parent_buffer->invalidateBibfileCache();
295 parent_buffer->invalidateBibinfoCache();
299 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
300 /// This one is useful for preview detached in a thread.
301 Buffer const * cloned_buffer_;
302 /// are we in the process of exporting this buffer?
303 mutable bool doing_export;
306 /// So we can force access via the accessors.
307 mutable Buffer const * parent_buffer;
312 /// Creates the per buffer temporary directory
313 static FileName createBufferTmpDir()
316 // We are in our own directory. Why bother to mangle name?
317 // In fact I wrote this code to circumvent a problematic behaviour
318 // (bug?) of EMX mkstemp().
319 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
320 convert<string>(count++));
322 if (!tmpfl.createDirectory(0777)) {
323 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
324 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
325 from_utf8(tmpfl.absFileName())));
331 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
332 Buffer const * cloned_buffer)
333 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
334 read_only(readonly_), filename(file), file_fully_loaded(false),
335 toc_backend(owner), macro_lock(false), timestamp_(0),
336 checksum_(0), wa_(0), gui_(0), undo_(*owner), bibinfo_cache_valid_(false),
337 bibfile_cache_valid_(false), cloned_buffer_(cloned_buffer),
338 doing_export(false), parent_buffer(0)
340 if (!cloned_buffer_) {
341 temppath = createBufferTmpDir();
342 lyxvc.setBuffer(owner_);
344 wa_ = new frontend::WorkAreaManager;
347 temppath = cloned_buffer_->d->temppath;
348 file_fully_loaded = true;
349 params = cloned_buffer_->d->params;
350 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
351 bibinfo_ = cloned_buffer_->d->bibinfo_;
352 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
353 bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
354 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
358 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
359 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
361 LYXERR(Debug::INFO, "Buffer::Buffer()");
363 d->inset = new InsetText(*cloned_buffer->d->inset);
364 d->inset->setBuffer(*this);
365 // FIXME: optimize this loop somewhat, maybe by creating a new
366 // general recursive Inset::setId().
367 DocIterator it = doc_iterator_begin(this);
368 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
369 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
370 it.paragraph().setId(cloned_it.paragraph().id());
372 d->inset = new InsetText(this);
373 d->inset->setAutoBreakRows(true);
374 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
380 LYXERR(Debug::INFO, "Buffer::~Buffer()");
381 // here the buffer should take care that it is
382 // saved properly, before it goes into the void.
384 // GuiView already destroyed
388 // No need to do additional cleanups for internal buffer.
393 // loop over children
394 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
395 Impl::BufferPositionMap::iterator end = d->children_positions.end();
396 for (; it != end; ++it) {
397 Buffer * child = const_cast<Buffer *>(it->first);
398 if (d->cloned_buffer_)
400 // The child buffer might have been closed already.
401 else if (theBufferList().isLoaded(child))
402 theBufferList().releaseChild(this, child);
406 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
407 msg += emergencyWrite();
408 Alert::warning(_("Attempting to close changed document!"), msg);
411 // clear references to children in macro tables
412 d->children_positions.clear();
413 d->position_to_children.clear();
415 if (!d->cloned_buffer_ && !d->temppath.destroyDirectory()) {
416 Alert::warning(_("Could not remove temporary directory"),
417 bformat(_("Could not remove the temporary directory %1$s"),
418 from_utf8(d->temppath.absFileName())));
421 // Remove any previewed LaTeX snippets associated with this buffer.
423 thePreviews().removeLoader(*this);
429 Buffer * Buffer::clone() const
431 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
432 buffer_clone->d->macro_lock = true;
433 buffer_clone->d->children_positions.clear();
434 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
435 // math macro caches need to be rethought and simplified.
436 // I am not sure wether we should handle Buffer cloning here or in BufferList.
437 // Right now BufferList knows nothing about buffer clones.
438 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
439 Impl::BufferPositionMap::iterator end = d->children_positions.end();
440 for (; it != end; ++it) {
441 DocIterator dit = it->second.clone(buffer_clone);
442 dit.setBuffer(buffer_clone);
443 Buffer * child = const_cast<Buffer *>(it->first);
444 Buffer * child_clone = child->clone();
445 Inset * inset = dit.nextInset();
446 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
447 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
448 inset_inc->setChildBuffer(child_clone);
449 child_clone->d->setParent(buffer_clone);
450 buffer_clone->setChild(dit, child_clone);
452 buffer_clone->d->macro_lock = false;
457 bool Buffer::isClone() const
459 return d->cloned_buffer_;
463 void Buffer::changed(bool update_metrics) const
466 d->wa_->redrawAll(update_metrics);
470 frontend::WorkAreaManager & Buffer::workAreaManager() const
472 LASSERT(d->wa_, /**/);
477 Text & Buffer::text() const
479 return d->inset->text();
483 Inset & Buffer::inset() const
489 BufferParams & Buffer::params()
495 BufferParams const & Buffer::params() const
501 ParagraphList & Buffer::paragraphs()
503 return text().paragraphs();
507 ParagraphList const & Buffer::paragraphs() const
509 return text().paragraphs();
513 LyXVC & Buffer::lyxvc()
519 LyXVC const & Buffer::lyxvc() const
525 string const Buffer::temppath() const
527 return d->temppath.absFileName();
531 TexRow & Buffer::texrow()
537 TexRow const & Buffer::texrow() const
543 TocBackend & Buffer::tocBackend() const
545 return d->toc_backend;
549 Undo & Buffer::undo()
555 void Buffer::setChild(DocIterator const & dit, Buffer * child)
557 d->children_positions[child] = dit;
561 string Buffer::latexName(bool const no_path) const
563 FileName latex_name =
564 makeLatexName(d->exportFileName());
565 return no_path ? latex_name.onlyFileName()
566 : latex_name.absFileName();
570 FileName Buffer::Impl::exportFileName() const
572 docstring const branch_suffix =
573 params.branchlist().getFileNameSuffix();
574 if (branch_suffix.empty())
577 string const name = filename.onlyFileNameWithoutExt()
578 + to_utf8(branch_suffix);
579 FileName res(filename.onlyPath().absFileName() + "/" + name);
580 res.changeExtension(filename.extension());
586 string Buffer::logName(LogType * type) const
588 string const filename = latexName(false);
590 if (filename.empty()) {
596 string const path = temppath();
598 FileName const fname(addName(temppath(),
599 onlyFileName(changeExtension(filename,
602 // FIXME: how do we know this is the name of the build log?
603 FileName const bname(
604 addName(path, onlyFileName(
605 changeExtension(filename,
606 formats.extension(bufferFormat()) + ".out"))));
608 // Also consider the master buffer log file
609 FileName masterfname = fname;
611 if (masterBuffer() != this) {
612 string const mlogfile = masterBuffer()->logName(&mtype);
613 masterfname = FileName(mlogfile);
616 // If no Latex log or Build log is newer, show Build log
617 if (bname.exists() &&
618 ((!fname.exists() && !masterfname.exists())
619 || (fname.lastModified() < bname.lastModified()
620 && masterfname.lastModified() < bname.lastModified()))) {
621 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
624 return bname.absFileName();
625 // If we have a newer master file log or only a master log, show this
626 } else if (fname != masterfname
627 && (!fname.exists() && (masterfname.exists()
628 || fname.lastModified() < masterfname.lastModified()))) {
629 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
632 return masterfname.absFileName();
634 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
637 return fname.absFileName();
641 void Buffer::setReadonly(bool const flag)
643 if (d->read_only != flag) {
650 void Buffer::setFileName(string const & newfile)
652 d->filename = makeAbsPath(newfile);
653 setReadonly(d->filename.isReadOnly());
658 int Buffer::readHeader(Lexer & lex)
660 int unknown_tokens = 0;
662 int begin_header_line = -1;
664 // Initialize parameters that may be/go lacking in header:
665 params().branchlist().clear();
666 params().preamble.erase();
667 params().options.erase();
668 params().master.erase();
669 params().float_placement.erase();
670 params().paperwidth.erase();
671 params().paperheight.erase();
672 params().leftmargin.erase();
673 params().rightmargin.erase();
674 params().topmargin.erase();
675 params().bottommargin.erase();
676 params().headheight.erase();
677 params().headsep.erase();
678 params().footskip.erase();
679 params().columnsep.erase();
680 params().fontsCJK.erase();
681 params().listings_params.clear();
682 params().clearLayoutModules();
683 params().clearRemovedModules();
684 params().clearIncludedChildren();
685 params().pdfoptions().clear();
686 params().indiceslist().clear();
687 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
688 params().isbackgroundcolor = false;
689 params().fontcolor = lyx::rgbFromHexName("#000000");
690 params().isfontcolor = false;
691 params().notefontcolor = lyx::rgbFromHexName("#cccccc");
692 params().boxbgcolor = lyx::rgbFromHexName("#ff0000");
693 params().html_latex_start.clear();
694 params().html_latex_end.clear();
695 params().html_math_img_scale = 1.0;
696 params().output_sync_macro.erase();
698 for (int i = 0; i < 4; ++i) {
699 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
700 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
703 ErrorList & errorList = d->errorLists["Parse"];
712 if (token == "\\end_header")
716 if (token == "\\begin_header") {
717 begin_header_line = line;
721 LYXERR(Debug::PARSER, "Handling document header token: `"
724 string unknown = params().readToken(lex, token, d->filename.onlyPath());
725 if (!unknown.empty()) {
726 if (unknown[0] != '\\' && token == "\\textclass") {
727 Alert::warning(_("Unknown document class"),
728 bformat(_("Using the default document class, because the "
729 "class %1$s is unknown."), from_utf8(unknown)));
732 docstring const s = bformat(_("Unknown token: "
736 errorList.push_back(ErrorItem(_("Document header error"),
741 if (begin_header_line) {
742 docstring const s = _("\\begin_header is missing");
743 errorList.push_back(ErrorItem(_("Document header error"),
747 params().makeDocumentClass();
749 return unknown_tokens;
754 // changed to be public and have one parameter
755 // Returns true if "\end_document" is not read (Asger)
756 bool Buffer::readDocument(Lexer & lex)
758 ErrorList & errorList = d->errorLists["Parse"];
761 if (!lex.checkFor("\\begin_document")) {
762 docstring const s = _("\\begin_document is missing");
763 errorList.push_back(ErrorItem(_("Document header error"),
767 // we are reading in a brand new document
768 LASSERT(paragraphs().empty(), /**/);
772 if (params().outputChanges) {
773 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
774 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
775 LaTeXFeatures::isAvailable("xcolor");
777 if (!dvipost && !xcolorulem) {
778 Alert::warning(_("Changes not shown in LaTeX output"),
779 _("Changes will not be highlighted in LaTeX output, "
780 "because neither dvipost nor xcolor/ulem are installed.\n"
781 "Please install these packages or redefine "
782 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
783 } else if (!xcolorulem) {
784 Alert::warning(_("Changes not shown in LaTeX output"),
785 _("Changes will not be highlighted in LaTeX output "
786 "when using pdflatex, because xcolor and ulem are not installed.\n"
787 "Please install both packages or redefine "
788 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
792 if (!params().master.empty()) {
793 FileName const master_file = makeAbsPath(params().master,
794 onlyPath(absFileName()));
795 if (isLyXFileName(master_file.absFileName())) {
797 checkAndLoadLyXFile(master_file, true);
799 // necessary e.g. after a reload
800 // to re-register the child (bug 5873)
801 // FIXME: clean up updateMacros (here, only
802 // child registering is needed).
803 master->updateMacros();
804 // set master as master buffer, but only
805 // if we are a real child
806 if (master->isChild(this))
808 // if the master is not fully loaded
809 // it is probably just loading this
810 // child. No warning needed then.
811 else if (master->isFullyLoaded())
812 LYXERR0("The master '"
814 << "' assigned to this document ("
816 << ") does not include "
817 "this document. Ignoring the master assignment.");
822 // assure we have a default index
823 params().indiceslist().addDefault(B_("Index"));
826 bool const res = text().read(lex, errorList, d->inset);
830 updateMacroInstances();
835 bool Buffer::readString(string const & s)
837 params().compressed = false;
839 // remove dummy empty par
840 paragraphs().clear();
844 FileName const name = FileName::tempName("Buffer_readString");
845 switch (readFile(lex, name, true)) {
849 // We need to call lyx2lyx, so write the input to a file
850 ofstream os(name.toFilesystemEncoding().c_str());
853 return readFile(name);
863 bool Buffer::readFile(FileName const & filename)
865 FileName fname(filename);
867 params().compressed = fname.isZippedFile();
869 // remove dummy empty par
870 paragraphs().clear();
873 if (readFile(lex, fname) != success)
880 bool Buffer::isFullyLoaded() const
882 return d->file_fully_loaded;
886 void Buffer::setFullyLoaded(bool value)
888 d->file_fully_loaded = value;
892 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
895 LASSERT(!filename.empty(), /**/);
897 // the first (non-comment) token _must_ be...
898 if (!lex.checkFor("\\lyxformat")) {
899 Alert::error(_("Document format failure"),
900 bformat(_("%1$s is not a readable LyX document."),
901 from_utf8(filename.absFileName())));
907 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
908 // if present remove ".," from string.
909 size_t dot = tmp_format.find_first_of(".,");
910 //lyxerr << " dot found at " << dot << endl;
911 if (dot != string::npos)
912 tmp_format.erase(dot, 1);
913 int const file_format = convert<int>(tmp_format);
914 //lyxerr << "format: " << file_format << endl;
916 // save timestamp and checksum of the original disk file, making sure
917 // to not overwrite them with those of the file created in the tempdir
918 // when it has to be converted to the current format.
920 // Save the timestamp and checksum of disk file. If filename is an
921 // emergency file, save the timestamp and checksum of the original lyx file
922 // because isExternallyModified will check for this file. (BUG4193)
923 string diskfile = filename.absFileName();
924 if (suffixIs(diskfile, ".emergency"))
925 diskfile = diskfile.substr(0, diskfile.size() - 10);
926 saveCheckSum(FileName(diskfile));
929 if (file_format != LYX_FORMAT) {
932 // lyx2lyx would fail
935 FileName const tmpfile = FileName::tempName("Buffer_readFile");
936 if (tmpfile.empty()) {
937 Alert::error(_("Conversion failed"),
938 bformat(_("%1$s is from a different"
939 " version of LyX, but a temporary"
940 " file for converting it could"
942 from_utf8(filename.absFileName())));
945 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
946 if (lyx2lyx.empty()) {
947 Alert::error(_("Conversion script not found"),
948 bformat(_("%1$s is from a different"
949 " version of LyX, but the"
950 " conversion script lyx2lyx"
951 " could not be found."),
952 from_utf8(filename.absFileName())));
955 ostringstream command;
956 command << os::python()
957 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
958 << " -t " << convert<string>(LYX_FORMAT)
959 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
960 << ' ' << quoteName(filename.toSafeFilesystemEncoding());
961 string const command_str = command.str();
963 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
965 cmd_ret const ret = runCommand(command_str);
966 if (ret.first != 0) {
967 if (file_format < LYX_FORMAT)
968 Alert::error(_("Conversion script failed"),
969 bformat(_("%1$s is from an older version"
970 " of LyX, but the lyx2lyx script"
971 " failed to convert it."),
972 from_utf8(filename.absFileName())));
974 Alert::error(_("Conversion script failed"),
975 bformat(_("%1$s is from a newer version"
976 " of LyX and cannot be converted by the"
978 from_utf8(filename.absFileName())));
981 bool const ret = readFile(tmpfile);
982 // Do stuff with tmpfile name and buffer name here.
983 return ret ? success : failure;
988 if (readDocument(lex)) {
989 Alert::error(_("Document format failure"),
990 bformat(_("%1$s ended unexpectedly, which means"
991 " that it is probably corrupted."),
992 from_utf8(filename.absFileName())));
996 d->file_fully_loaded = true;
1001 // Should probably be moved to somewhere else: BufferView? GuiView?
1002 bool Buffer::save() const
1004 // ask if the disk file has been externally modified (use checksum method)
1005 if (fileName().exists() && isExternallyModified(checksum_method)) {
1006 docstring const file = makeDisplayPath(absFileName(), 20);
1007 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
1008 "you want to overwrite this file?"), file);
1009 int const ret = Alert::prompt(_("Overwrite modified file?"),
1010 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1015 // We don't need autosaves in the immediate future. (Asger)
1016 resetAutosaveTimers();
1018 FileName backupName;
1019 bool madeBackup = false;
1021 // make a backup if the file already exists
1022 if (lyxrc.make_backup && fileName().exists()) {
1023 backupName = FileName(absFileName() + '~');
1024 if (!lyxrc.backupdir_path.empty()) {
1025 string const mangledName =
1026 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1027 backupName = FileName(addName(lyxrc.backupdir_path,
1030 // do not copy because of #6587
1031 if (fileName().moveTo(backupName)) {
1034 Alert::error(_("Backup failure"),
1035 bformat(_("Cannot create backup file %1$s.\n"
1036 "Please check whether the directory exists and is writeable."),
1037 from_utf8(backupName.absFileName())));
1038 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1042 if (writeFile(d->filename)) {
1046 // Saving failed, so backup is not backup
1048 backupName.moveTo(d->filename);
1054 bool Buffer::writeFile(FileName const & fname) const
1056 if (d->read_only && fname == d->filename)
1059 bool retval = false;
1061 docstring const str = bformat(_("Saving document %1$s..."),
1062 makeDisplayPath(fname.absFileName()));
1065 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1067 if (params().compressed) {
1068 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1069 retval = ofs && write(ofs);
1071 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1072 retval = ofs && write(ofs);
1076 message(str + _(" could not write file!"));
1081 // removeAutosaveFile();
1083 saveCheckSum(d->filename);
1084 message(str + _(" done."));
1090 docstring Buffer::emergencyWrite()
1092 // No need to save if the buffer has not changed.
1096 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1098 docstring user_message = bformat(
1099 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1101 // We try to save three places:
1102 // 1) Same place as document. Unless it is an unnamed doc.
1104 string s = absFileName();
1107 if (writeFile(FileName(s))) {
1109 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1110 return user_message;
1112 user_message += _(" Save failed! Trying again...\n");
1116 // 2) In HOME directory.
1117 string s = addName(package().home_dir().absFileName(), absFileName());
1119 lyxerr << ' ' << s << endl;
1120 if (writeFile(FileName(s))) {
1122 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1123 return user_message;
1126 user_message += _(" Save failed! Trying yet again...\n");
1128 // 3) In "/tmp" directory.
1129 // MakeAbsPath to prepend the current
1130 // drive letter on OS/2
1131 s = addName(package().temp_dir().absFileName(), absFileName());
1133 lyxerr << ' ' << s << endl;
1134 if (writeFile(FileName(s))) {
1136 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1137 return user_message;
1140 user_message += _(" Save failed! Bummer. Document is lost.");
1143 return user_message;
1147 bool Buffer::write(ostream & ofs) const
1150 // Use the standard "C" locale for file output.
1151 ofs.imbue(locale::classic());
1154 // The top of the file should not be written by params().
1156 // write out a comment in the top of the file
1157 ofs << "#LyX " << lyx_version
1158 << " created this file. For more info see http://www.lyx.org/\n"
1159 << "\\lyxformat " << LYX_FORMAT << "\n"
1160 << "\\begin_document\n";
1162 /// For each author, set 'used' to true if there is a change
1163 /// by this author in the document; otherwise set it to 'false'.
1164 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1165 AuthorList::Authors::const_iterator a_end = params().authors().end();
1166 for (; a_it != a_end; ++a_it)
1167 a_it->setUsed(false);
1169 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1170 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1171 for ( ; it != end; ++it)
1172 it->checkAuthors(params().authors());
1174 // now write out the buffer parameters.
1175 ofs << "\\begin_header\n";
1176 params().writeFile(ofs);
1177 ofs << "\\end_header\n";
1180 ofs << "\n\\begin_body\n";
1182 ofs << "\n\\end_body\n";
1184 // Write marker that shows file is complete
1185 ofs << "\\end_document" << endl;
1187 // Shouldn't really be needed....
1190 // how to check if close went ok?
1191 // Following is an attempt... (BE 20001011)
1193 // good() returns false if any error occured, including some
1194 // formatting error.
1195 // bad() returns true if something bad happened in the buffer,
1196 // which should include file system full errors.
1201 lyxerr << "File was not closed properly." << endl;
1208 bool Buffer::makeLaTeXFile(FileName const & fname,
1209 string const & original_path,
1210 OutputParams const & runparams_in,
1211 bool output_preamble, bool output_body) const
1213 OutputParams runparams = runparams_in;
1214 if (params().useXetex)
1215 runparams.flavor = OutputParams::XETEX;
1217 string const encoding = runparams.encoding->iconvName();
1218 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1221 try { ofs.reset(encoding); }
1222 catch (iconv_codecvt_facet_exception & e) {
1223 lyxerr << "Caught iconv exception: " << e.what() << endl;
1224 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1225 "verify that the support software for your encoding (%1$s) is "
1226 "properly installed"), from_ascii(encoding)));
1229 if (!openFileWrite(ofs, fname))
1232 //TexStream ts(ofs.rdbuf(), &texrow());
1233 ErrorList & errorList = d->errorLists["Export"];
1235 bool failed_export = false;
1238 writeLaTeXSource(ofs, original_path,
1239 runparams, output_preamble, output_body);
1241 catch (EncodingException & e) {
1242 odocstringstream ods;
1243 ods.put(e.failed_char);
1245 oss << "0x" << hex << e.failed_char << dec;
1246 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1247 " (code point %2$s)"),
1248 ods.str(), from_utf8(oss.str()));
1249 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1250 "representable in the chosen encoding.\n"
1251 "Changing the document encoding to utf8 could help."),
1252 e.par_id, e.pos, e.pos + 1));
1253 failed_export = true;
1255 catch (iconv_codecvt_facet_exception & e) {
1256 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1257 _(e.what()), -1, 0, 0));
1258 failed_export = true;
1260 catch (exception const & e) {
1261 errorList.push_back(ErrorItem(_("conversion failed"),
1262 _(e.what()), -1, 0, 0));
1263 failed_export = true;
1266 lyxerr << "Caught some really weird exception..." << endl;
1272 failed_export = true;
1273 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1277 return !failed_export;
1281 void Buffer::writeLaTeXSource(odocstream & os,
1282 string const & original_path,
1283 OutputParams const & runparams_in,
1284 bool const output_preamble, bool const output_body) const
1286 // The child documents, if any, shall be already loaded at this point.
1288 OutputParams runparams = runparams_in;
1290 // Classify the unicode characters appearing in math insets
1291 Encodings::initUnicodeMath(*this);
1293 // validate the buffer.
1294 LYXERR(Debug::LATEX, " Validating buffer...");
1295 LaTeXFeatures features(*this, params(), runparams);
1297 LYXERR(Debug::LATEX, " Buffer validation done.");
1299 // The starting paragraph of the coming rows is the
1300 // first paragraph of the document. (Asger)
1301 if (output_preamble && runparams.nice) {
1302 os << "%% LyX " << lyx_version << " created this file. "
1303 "For more info, see http://www.lyx.org/.\n"
1304 "%% Do not edit unless you really know what "
1306 d->texrow.newline();
1307 d->texrow.newline();
1309 LYXERR(Debug::INFO, "lyx document header finished");
1311 // Don't move this behind the parent_buffer=0 code below,
1312 // because then the macros will not get the right "redefinition"
1313 // flag as they don't see the parent macros which are output before.
1316 // fold macros if possible, still with parent buffer as the
1317 // macros will be put in the prefix anyway.
1318 updateMacroInstances();
1320 // There are a few differences between nice LaTeX and usual files:
1321 // usual is \batchmode and has a
1322 // special input@path to allow the including of figures
1323 // with either \input or \includegraphics (what figinsets do).
1324 // input@path is set when the actual parameter
1325 // original_path is set. This is done for usual tex-file, but not
1326 // for nice-latex-file. (Matthias 250696)
1327 // Note that input@path is only needed for something the user does
1328 // in the preamble, included .tex files or ERT, files included by
1329 // LyX work without it.
1330 if (output_preamble) {
1331 if (!runparams.nice) {
1332 // code for usual, NOT nice-latex-file
1333 os << "\\batchmode\n"; // changed
1334 // from \nonstopmode
1335 d->texrow.newline();
1337 if (!original_path.empty()) {
1339 // We don't know the encoding of inputpath
1340 docstring const inputpath = from_utf8(support::latex_path(original_path));
1341 docstring uncodable_glyphs;
1342 Encoding const * const enc = runparams.encoding;
1344 for (size_t n = 0; n < inputpath.size(); ++n) {
1345 docstring const glyph =
1346 docstring(1, inputpath[n]);
1347 if (enc->latexChar(inputpath[n], true) != glyph) {
1348 LYXERR0("Uncodable character '"
1350 << "' in input path!");
1351 uncodable_glyphs += glyph;
1356 // warn user if we found uncodable glyphs.
1357 if (!uncodable_glyphs.empty()) {
1358 frontend::Alert::warning(_("Uncodable character in file path"),
1359 support::bformat(_("The path of your document\n"
1361 "contains glyphs that are unknown in the\n"
1362 "current document encoding (namely %2$s).\n"
1363 "This will likely result in incomplete output.\n\n"
1364 "Choose an appropriate document encoding (such as utf8)\n"
1365 "or change the file path name."), inputpath, uncodable_glyphs));
1367 os << "\\makeatletter\n"
1368 << "\\def\\input@path{{"
1369 << inputpath << "/}}\n"
1370 << "\\makeatother\n";
1371 d->texrow.newline();
1372 d->texrow.newline();
1373 d->texrow.newline();
1377 // get parent macros (if this buffer has a parent) which will be
1378 // written at the document begin further down.
1379 MacroSet parentMacros;
1380 listParentMacros(parentMacros, features);
1382 // Write the preamble
1383 runparams.use_babel = params().writeLaTeX(os, features,
1385 d->filename.onlyPath());
1387 runparams.use_japanese = features.isRequired("japanese");
1393 os << "\\begin{document}\n";
1394 d->texrow.newline();
1396 // output the parent macros
1397 MacroSet::iterator it = parentMacros.begin();
1398 MacroSet::iterator end = parentMacros.end();
1399 for (; it != end; ++it) {
1400 int num_lines = (*it)->write(os, true);
1401 d->texrow.newlines(num_lines);
1404 } // output_preamble
1406 d->texrow.start(paragraphs().begin()->id(), 0);
1408 LYXERR(Debug::INFO, "preamble finished, now the body.");
1410 // if we are doing a real file with body, even if this is the
1411 // child of some other buffer, let's cut the link here.
1412 // This happens for example if only a child document is printed.
1413 Buffer const * save_parent = 0;
1414 if (output_preamble) {
1415 save_parent = d->parent();
1420 latexParagraphs(*this, text(), os, d->texrow, runparams);
1422 // Restore the parenthood if needed
1423 if (output_preamble)
1424 d->setParent(save_parent);
1426 // add this just in case after all the paragraphs
1428 d->texrow.newline();
1430 if (output_preamble) {
1431 os << "\\end{document}\n";
1432 d->texrow.newline();
1433 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1435 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1437 runparams_in.encoding = runparams.encoding;
1439 // Just to be sure. (Asger)
1440 d->texrow.newline();
1442 //for (int i = 0; i<d->texrow.rows(); i++) {
1444 // if (d->texrow.getIdFromRow(i+1,id,pos) && id>0)
1445 // lyxerr << i+1 << ":" << id << ":" << getParFromID(id).paragraph().asString()<<"\n";
1448 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1449 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1453 bool Buffer::isLatex() const
1455 return params().documentClass().outputType() == LATEX;
1459 bool Buffer::isLiterate() const
1461 return params().documentClass().outputType() == LITERATE;
1465 bool Buffer::isDocBook() const
1467 return params().documentClass().outputType() == DOCBOOK;
1471 void Buffer::makeDocBookFile(FileName const & fname,
1472 OutputParams const & runparams,
1473 bool const body_only) const
1475 LYXERR(Debug::LATEX, "makeDocBookFile...");
1478 if (!openFileWrite(ofs, fname))
1481 writeDocBookSource(ofs, fname.absFileName(), runparams, body_only);
1485 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1489 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1490 OutputParams const & runparams,
1491 bool const only_body) const
1493 LaTeXFeatures features(*this, params(), runparams);
1498 DocumentClass const & tclass = params().documentClass();
1499 string const top_element = tclass.latexname();
1502 if (runparams.flavor == OutputParams::XML)
1503 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1506 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1509 if (! tclass.class_header().empty())
1510 os << from_ascii(tclass.class_header());
1511 else if (runparams.flavor == OutputParams::XML)
1512 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1513 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1515 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1517 docstring preamble = from_utf8(params().preamble);
1518 if (runparams.flavor != OutputParams::XML ) {
1519 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1520 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1521 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1522 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1525 string const name = runparams.nice
1526 ? changeExtension(absFileName(), ".sgml") : fname;
1527 preamble += features.getIncludedFiles(name);
1528 preamble += features.getLyXSGMLEntities();
1530 if (!preamble.empty()) {
1531 os << "\n [ " << preamble << " ]";
1536 string top = top_element;
1538 if (runparams.flavor == OutputParams::XML)
1539 top += params().language->code();
1541 top += params().language->code().substr(0, 2);
1544 if (!params().options.empty()) {
1546 top += params().options;
1549 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1550 << " file was created by LyX " << lyx_version
1551 << "\n See http://www.lyx.org/ for more information -->\n";
1553 params().documentClass().counters().reset();
1557 sgml::openTag(os, top);
1559 docbookParagraphs(text(), *this, os, runparams);
1560 sgml::closeTag(os, top_element);
1564 void Buffer::makeLyXHTMLFile(FileName const & fname,
1565 OutputParams const & runparams,
1566 bool const body_only) const
1568 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1571 if (!openFileWrite(ofs, fname))
1574 writeLyXHTMLSource(ofs, runparams, body_only);
1578 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1582 void Buffer::writeLyXHTMLSource(odocstream & os,
1583 OutputParams const & runparams,
1584 bool const only_body) const
1586 LaTeXFeatures features(*this, params(), runparams);
1588 updateBuffer(UpdateMaster, OutputUpdate);
1589 d->bibinfo_.makeCitationLabels(*this);
1591 updateMacroInstances();
1594 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1595 << "<!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"
1596 // FIXME Language should be set properly.
1597 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
1599 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
1600 // FIXME Presumably need to set this right
1601 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1603 docstring const & doctitle = features.htmlTitle();
1605 << (doctitle.empty() ? from_ascii("LyX Document") : doctitle)
1608 os << "\n<!-- Text Class Preamble -->\n"
1609 << features.getTClassHTMLPreamble()
1610 << "\n<!-- Premable Snippets -->\n"
1611 << from_utf8(features.getPreambleSnippets());
1613 os << "\n<!-- Layout-provided Styles -->\n";
1614 docstring const styleinfo = features.getTClassHTMLStyles();
1615 if (!styleinfo.empty()) {
1616 os << "<style type='text/css'>\n"
1620 os << "</head>\n<body>\n";
1624 params().documentClass().counters().reset();
1625 xhtmlParagraphs(text(), *this, xs, runparams);
1627 os << "</body>\n</html>\n";
1631 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1632 // Other flags: -wall -v0 -x
1633 int Buffer::runChktex()
1637 // get LaTeX-Filename
1638 FileName const path(temppath());
1639 string const name = addName(path.absFileName(), latexName());
1640 string const org_path = filePath();
1642 PathChanger p(path); // path to LaTeX file
1643 message(_("Running chktex..."));
1645 // Generate the LaTeX file if neccessary
1646 OutputParams runparams(¶ms().encoding());
1647 runparams.flavor = OutputParams::LATEX;
1648 runparams.nice = false;
1649 runparams.linelen = lyxrc.plaintext_linelen;
1650 makeLaTeXFile(FileName(name), org_path, runparams);
1653 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
1654 int const res = chktex.run(terr); // run chktex
1657 Alert::error(_("chktex failure"),
1658 _("Could not run chktex successfully."));
1659 } else if (res > 0) {
1660 ErrorList & errlist = d->errorLists["ChkTeX"];
1662 bufferErrors(terr, errlist);
1673 void Buffer::validate(LaTeXFeatures & features) const
1675 params().validate(features);
1679 for_each(paragraphs().begin(), paragraphs().end(),
1680 bind(&Paragraph::validate, _1, ref(features)));
1682 if (lyxerr.debugging(Debug::LATEX)) {
1683 features.showStruct();
1688 void Buffer::getLabelList(vector<docstring> & list) const
1690 // If this is a child document, use the parent's list instead.
1691 Buffer const * const pbuf = d->parent();
1693 pbuf->getLabelList(list);
1698 Toc & toc = d->toc_backend.toc("label");
1699 TocIterator toc_it = toc.begin();
1700 TocIterator end = toc.end();
1701 for (; toc_it != end; ++toc_it) {
1702 if (toc_it->depth() == 0)
1703 list.push_back(toc_it->str());
1708 void Buffer::updateBibfilesCache(UpdateScope scope) const
1710 // FIXME This is probably unnecssary, given where we call this.
1711 // If this is a child document, use the parent's cache instead.
1712 Buffer const * const pbuf = d->parent();
1713 if (pbuf && scope != UpdateChildOnly) {
1714 pbuf->updateBibfilesCache();
1718 d->bibfiles_cache_.clear();
1719 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1720 if (it->lyxCode() == BIBTEX_CODE) {
1721 InsetBibtex const & inset =
1722 static_cast<InsetBibtex const &>(*it);
1723 support::FileNameList const bibfiles = inset.getBibFiles();
1724 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1727 } else if (it->lyxCode() == INCLUDE_CODE) {
1728 InsetInclude & inset =
1729 static_cast<InsetInclude &>(*it);
1730 Buffer const * const incbuf = inset.getChildBuffer();
1733 support::FileNameList const & bibfiles =
1734 incbuf->getBibfilesCache(UpdateChildOnly);
1735 if (!bibfiles.empty()) {
1736 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1742 d->bibfile_cache_valid_ = true;
1743 d->bibinfo_cache_valid_ = false;
1747 void Buffer::invalidateBibinfoCache() const
1749 d->bibinfo_cache_valid_ = false;
1750 // also invalidate the cache for the parent buffer
1751 Buffer const * const pbuf = d->parent();
1753 pbuf->invalidateBibinfoCache();
1757 void Buffer::invalidateBibfileCache() const
1759 d->bibfile_cache_valid_ = false;
1760 d->bibinfo_cache_valid_ = false;
1761 // also invalidate the cache for the parent buffer
1762 Buffer const * const pbuf = d->parent();
1764 pbuf->invalidateBibfileCache();
1768 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1770 // FIXME This is probably unnecessary, given where we call this.
1771 // If this is a child document, use the master's cache instead.
1772 Buffer const * const pbuf = masterBuffer();
1773 if (pbuf != this && scope != UpdateChildOnly)
1774 return pbuf->getBibfilesCache();
1776 if (!d->bibfile_cache_valid_)
1777 this->updateBibfilesCache(scope);
1779 return d->bibfiles_cache_;
1783 BiblioInfo const & Buffer::masterBibInfo() const
1785 Buffer const * const tmp = masterBuffer();
1787 return tmp->masterBibInfo();
1792 void Buffer::checkBibInfoCache() const
1794 // use the master's cache
1795 Buffer const * const tmp = masterBuffer();
1797 tmp->checkBibInfoCache();
1801 // this will also reload the cache if it is invalid
1802 support::FileNameList const & bibfiles_cache = getBibfilesCache();
1804 // compare the cached timestamps with the actual ones.
1805 support::FileNameList::const_iterator ei = bibfiles_cache.begin();
1806 support::FileNameList::const_iterator en = bibfiles_cache.end();
1807 for (; ei != en; ++ ei) {
1808 time_t lastw = ei->lastModified();
1809 time_t prevw = d->bibfile_status_[*ei];
1810 if (lastw != prevw) {
1811 d->bibinfo_cache_valid_ = false;
1812 d->bibfile_status_[*ei] = lastw;
1816 // if not valid, then reload the info
1817 if (!d->bibinfo_cache_valid_) {
1818 d->bibinfo_.clear();
1819 fillWithBibKeys(d->bibinfo_);
1820 d->bibinfo_cache_valid_ = true;
1825 void Buffer::fillWithBibKeys(BiblioInfo & keys) const
1827 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1828 it->fillWithBibKeys(keys, it);
1832 bool Buffer::isDepClean(string const & name) const
1834 DepClean::const_iterator const it = d->dep_clean.find(name);
1835 if (it == d->dep_clean.end())
1841 void Buffer::markDepClean(string const & name)
1843 d->dep_clean[name] = true;
1847 bool Buffer::isExportableFormat(string const & format) const
1849 typedef vector<Format const *> Formats;
1851 formats = exportableFormats(true);
1852 Formats::const_iterator fit = formats.begin();
1853 Formats::const_iterator end = formats.end();
1854 for (; fit != end ; ++fit) {
1855 if ((*fit)->name() == format)
1862 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1865 // FIXME? if there is an Buffer LFUN that can be dispatched even
1866 // if internal, put a switch '(cmd.action)' here.
1872 switch (cmd.action()) {
1874 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1875 flag.setOnOff(isReadonly());
1878 // FIXME: There is need for a command-line import.
1879 //case LFUN_BUFFER_IMPORT:
1881 case LFUN_BUFFER_AUTO_SAVE:
1884 case LFUN_BUFFER_EXPORT_CUSTOM:
1885 // FIXME: Nothing to check here?
1888 case LFUN_BUFFER_EXPORT: {
1889 docstring const arg = cmd.argument();
1890 enable = arg == "custom" || isExportable(to_utf8(arg));
1892 flag.message(bformat(
1893 _("Don't know how to export to format: %1$s"), arg));
1897 case LFUN_BUFFER_CHKTEX:
1898 enable = isLatex() && !lyxrc.chktex_command.empty();
1901 case LFUN_BUILD_PROGRAM:
1902 enable = isExportable("program");
1905 case LFUN_BRANCH_ACTIVATE:
1906 case LFUN_BRANCH_DEACTIVATE: {
1907 BranchList const & branchList = params().branchlist();
1908 docstring const branchName = cmd.argument();
1909 enable = !branchName.empty() && branchList.find(branchName);
1913 case LFUN_BRANCH_ADD:
1914 case LFUN_BRANCHES_RENAME:
1915 case LFUN_BUFFER_PRINT:
1916 // if no Buffer is present, then of course we won't be called!
1919 case LFUN_BUFFER_LANGUAGE:
1920 enable = !isReadonly();
1926 flag.setEnabled(enable);
1931 void Buffer::dispatch(string const & command, DispatchResult & result)
1933 return dispatch(lyxaction.lookupFunc(command), result);
1937 // NOTE We can end up here even if we have no GUI, because we are called
1938 // by LyX::exec to handled command-line requests. So we may need to check
1939 // whether we have a GUI or not. The boolean use_gui holds this information.
1940 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
1943 // FIXME? if there is an Buffer LFUN that can be dispatched even
1944 // if internal, put a switch '(cmd.action())' here.
1945 dr.dispatched(false);
1948 string const argument = to_utf8(func.argument());
1949 // We'll set this back to false if need be.
1950 bool dispatched = true;
1951 undo().beginUndoGroup();
1953 switch (func.action()) {
1954 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1955 if (lyxvc().inUse())
1956 lyxvc().toggleReadOnly();
1958 setReadonly(!isReadonly());
1961 case LFUN_BUFFER_EXPORT: {
1962 bool success = doExport(argument, false, false);
1963 dr.setError(!success);
1965 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
1970 case LFUN_BUILD_PROGRAM:
1971 doExport("program", true, false);
1974 case LFUN_BUFFER_CHKTEX:
1978 case LFUN_BUFFER_EXPORT_CUSTOM: {
1980 string command = split(argument, format_name, ' ');
1981 Format const * format = formats.getFormat(format_name);
1983 lyxerr << "Format \"" << format_name
1984 << "\" not recognized!"
1989 // The name of the file created by the conversion process
1992 // Output to filename
1993 if (format->name() == "lyx") {
1994 string const latexname = latexName(false);
1995 filename = changeExtension(latexname,
1996 format->extension());
1997 filename = addName(temppath(), filename);
1999 if (!writeFile(FileName(filename)))
2003 doExport(format_name, true, false, filename);
2006 // Substitute $$FName for filename
2007 if (!contains(command, "$$FName"))
2008 command = "( " + command + " ) < $$FName";
2009 command = subst(command, "$$FName", filename);
2011 // Execute the command in the background
2013 call.startscript(Systemcall::DontWait, command);
2017 // FIXME: There is need for a command-line import.
2019 case LFUN_BUFFER_IMPORT:
2024 case LFUN_BUFFER_AUTO_SAVE:
2028 case LFUN_BRANCH_ADD: {
2029 docstring branch_name = func.argument();
2030 if (branch_name.empty()) {
2034 BranchList & branch_list = params().branchlist();
2035 vector<docstring> const branches =
2036 getVectorFromString(branch_name, branch_list.separator());
2038 for (vector<docstring>::const_iterator it = branches.begin();
2039 it != branches.end(); ++it) {
2041 Branch * branch = branch_list.find(branch_name);
2043 LYXERR0("Branch " << branch_name << " already exists.");
2047 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2049 branch_list.add(branch_name);
2050 branch = branch_list.find(branch_name);
2051 string const x11hexname = X11hexname(branch->color());
2052 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2053 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2055 dr.update(Update::Force);
2063 case LFUN_BRANCH_ACTIVATE:
2064 case LFUN_BRANCH_DEACTIVATE: {
2065 BranchList & branchList = params().branchlist();
2066 docstring const branchName = func.argument();
2067 // the case without a branch name is handled elsewhere
2068 if (branchName.empty()) {
2072 Branch * branch = branchList.find(branchName);
2074 LYXERR0("Branch " << branchName << " does not exist.");
2076 docstring const msg =
2077 bformat(_("Branch \"%1$s\" does not exist."), branchName);
2080 branch->setSelected(func.action() == LFUN_BRANCH_ACTIVATE);
2082 dr.update(Update::Force);
2083 dr.forceBufferUpdate();
2088 case LFUN_BRANCHES_RENAME: {
2089 if (func.argument().empty())
2092 docstring const oldname = from_utf8(func.getArg(0));
2093 docstring const newname = from_utf8(func.getArg(1));
2094 InsetIterator it = inset_iterator_begin(inset());
2095 InsetIterator const end = inset_iterator_end(inset());
2096 bool success = false;
2097 for (; it != end; ++it) {
2098 if (it->lyxCode() == BRANCH_CODE) {
2099 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2100 if (ins.branch() == oldname) {
2101 undo().recordUndo(it);
2102 ins.rename(newname);
2107 if (it->lyxCode() == INCLUDE_CODE) {
2108 // get buffer of external file
2109 InsetInclude const & ins =
2110 static_cast<InsetInclude const &>(*it);
2111 Buffer * child = ins.getChildBuffer();
2114 child->dispatch(func, dr);
2119 dr.update(Update::Force);
2120 dr.forceBufferUpdate();
2125 case LFUN_BUFFER_PRINT: {
2126 // we'll assume there's a problem until we succeed
2128 string target = func.getArg(0);
2129 string target_name = func.getArg(1);
2130 string command = func.getArg(2);
2133 || target_name.empty()
2134 || command.empty()) {
2135 LYXERR0("Unable to parse " << func.argument());
2136 docstring const msg =
2137 bformat(_("Unable to parse \"%1$s\""), func.argument());
2141 if (target != "printer" && target != "file") {
2142 LYXERR0("Unrecognized target \"" << target << '"');
2143 docstring const msg =
2144 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2149 bool const update_unincluded =
2150 params().maintain_unincluded_children
2151 && !params().getIncludedChildren().empty();
2152 if (!doExport("dvi", true, update_unincluded)) {
2153 showPrintError(absFileName());
2154 dr.setMessage(_("Error exporting to DVI."));
2158 // Push directory path.
2159 string const path = temppath();
2160 // Prevent the compiler from optimizing away p
2164 // there are three cases here:
2165 // 1. we print to a file
2166 // 2. we print directly to a printer
2167 // 3. we print using a spool command (print to file first)
2170 string const dviname = changeExtension(latexName(true), "dvi");
2172 if (target == "printer") {
2173 if (!lyxrc.print_spool_command.empty()) {
2174 // case 3: print using a spool
2175 string const psname = changeExtension(dviname,".ps");
2176 command += ' ' + lyxrc.print_to_file
2179 + quoteName(dviname);
2181 string command2 = lyxrc.print_spool_command + ' ';
2182 if (target_name != "default") {
2183 command2 += lyxrc.print_spool_printerprefix
2187 command2 += quoteName(psname);
2189 // If successful, then spool command
2190 res = one.startscript(Systemcall::Wait, command);
2193 // If there's no GUI, we have to wait on this command. Otherwise,
2194 // LyX deletes the temporary directory, and with it the spooled
2195 // file, before it can be printed!!
2196 Systemcall::Starttype stype = use_gui ?
2197 Systemcall::DontWait : Systemcall::Wait;
2198 res = one.startscript(stype, command2);
2201 // case 2: print directly to a printer
2202 if (target_name != "default")
2203 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2205 Systemcall::Starttype stype = use_gui ?
2206 Systemcall::DontWait : Systemcall::Wait;
2207 res = one.startscript(stype, command + quoteName(dviname));
2211 // case 1: print to a file
2212 FileName const filename(makeAbsPath(target_name, filePath()));
2213 FileName const dvifile(makeAbsPath(dviname, path));
2214 if (filename.exists()) {
2215 docstring text = bformat(
2216 _("The file %1$s already exists.\n\n"
2217 "Do you want to overwrite that file?"),
2218 makeDisplayPath(filename.absFileName()));
2219 if (Alert::prompt(_("Overwrite file?"),
2220 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2223 command += ' ' + lyxrc.print_to_file
2224 + quoteName(filename.toFilesystemEncoding())
2226 + quoteName(dvifile.toFilesystemEncoding());
2228 Systemcall::Starttype stype = use_gui ?
2229 Systemcall::DontWait : Systemcall::Wait;
2230 res = one.startscript(stype, command);
2236 dr.setMessage(_("Error running external commands."));
2237 showPrintError(absFileName());
2242 case LFUN_BUFFER_LANGUAGE: {
2243 Language const * oldL = params().language;
2244 Language const * newL = languages.getLanguage(argument);
2245 if (!newL || oldL == newL)
2247 if (oldL->rightToLeft() == newL->rightToLeft() && !isMultiLingual()) {
2248 changeLanguage(oldL, newL);
2249 dr.forceBufferUpdate();
2258 dr.dispatched(dispatched);
2259 undo().endUndoGroup();
2263 void Buffer::changeLanguage(Language const * from, Language const * to)
2265 LASSERT(from, /**/);
2268 for_each(par_iterator_begin(),
2270 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2274 bool Buffer::isMultiLingual() const
2276 ParConstIterator end = par_iterator_end();
2277 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2278 if (it->isMultiLingual(params()))
2285 std::set<Language const *> Buffer::getLanguages() const
2287 std::set<Language const *> languages;
2288 getLanguages(languages);
2293 void Buffer::getLanguages(std::set<Language const *> & languages) const
2295 ParConstIterator end = par_iterator_end();
2296 // add the buffer language, even if it's not actively used
2297 languages.insert(language());
2298 // iterate over the paragraphs
2299 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2300 it->getLanguages(languages);
2302 ListOfBuffers clist = getChildren();
2303 ListOfBuffers::const_iterator cit = clist.begin();
2304 ListOfBuffers::const_iterator const cen = clist.end();
2305 for (; cit != cen; ++cit)
2306 (*cit)->getLanguages(languages);
2310 DocIterator Buffer::getParFromID(int const id) const
2312 Buffer * buf = const_cast<Buffer *>(this);
2314 // John says this is called with id == -1 from undo
2315 lyxerr << "getParFromID(), id: " << id << endl;
2316 return doc_iterator_end(buf);
2319 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2320 if (it.paragraph().id() == id)
2323 return doc_iterator_end(buf);
2327 bool Buffer::hasParWithID(int const id) const
2329 return !getParFromID(id).atEnd();
2333 ParIterator Buffer::par_iterator_begin()
2335 return ParIterator(doc_iterator_begin(this));
2339 ParIterator Buffer::par_iterator_end()
2341 return ParIterator(doc_iterator_end(this));
2345 ParConstIterator Buffer::par_iterator_begin() const
2347 return ParConstIterator(doc_iterator_begin(this));
2351 ParConstIterator Buffer::par_iterator_end() const
2353 return ParConstIterator(doc_iterator_end(this));
2357 Language const * Buffer::language() const
2359 return params().language;
2363 docstring const Buffer::B_(string const & l10n) const
2365 return params().B_(l10n);
2369 bool Buffer::isClean() const
2371 return d->lyx_clean;
2375 bool Buffer::isExternallyModified(CheckMethod method) const
2377 LASSERT(d->filename.exists(), /**/);
2378 // if method == timestamp, check timestamp before checksum
2379 return (method == checksum_method
2380 || d->timestamp_ != d->filename.lastModified())
2381 && d->checksum_ != d->filename.checksum();
2385 void Buffer::saveCheckSum(FileName const & file) const
2387 if (file.exists()) {
2388 d->timestamp_ = file.lastModified();
2389 d->checksum_ = file.checksum();
2391 // in the case of save to a new file.
2398 void Buffer::markClean() const
2400 if (!d->lyx_clean) {
2401 d->lyx_clean = true;
2404 // if the .lyx file has been saved, we don't need an
2406 d->bak_clean = true;
2407 d->undo_.markDirty();
2411 void Buffer::setUnnamed(bool flag)
2417 bool Buffer::isUnnamed() const
2424 /// Don't check unnamed, here: isInternal() is used in
2425 /// newBuffer(), where the unnamed flag has not been set by anyone
2426 /// yet. Also, for an internal buffer, there should be no need for
2427 /// retrieving fileName() nor for checking if it is unnamed or not.
2428 bool Buffer::isInternal() const
2430 return fileName().extension() == "internal";
2434 void Buffer::markDirty()
2437 d->lyx_clean = false;
2440 d->bak_clean = false;
2442 DepClean::iterator it = d->dep_clean.begin();
2443 DepClean::const_iterator const end = d->dep_clean.end();
2445 for (; it != end; ++it)
2450 FileName Buffer::fileName() const
2456 string Buffer::absFileName() const
2458 return d->filename.absFileName();
2462 string Buffer::filePath() const
2464 return d->filename.onlyPath().absFileName() + "/";
2468 bool Buffer::isReadonly() const
2470 return d->read_only;
2474 void Buffer::setParent(Buffer const * buffer)
2476 // Avoids recursive include.
2477 d->setParent(buffer == this ? 0 : buffer);
2482 Buffer const * Buffer::parent() const
2488 void Buffer::Impl::collectRelatives(BufferSet & bufs) const
2490 bufs.insert(owner_);
2492 parent()->d->collectRelatives(bufs);
2494 // loop over children
2495 BufferPositionMap::const_iterator it = children_positions.begin();
2496 BufferPositionMap::const_iterator end = children_positions.end();
2497 for (; it != end; ++it)
2498 bufs.insert(const_cast<Buffer *>(it->first));
2502 ListOfBuffers Buffer::allRelatives() const
2505 d->collectRelatives(bufs);
2506 BufferSet::iterator it = bufs.begin();
2508 for (; it != bufs.end(); ++it)
2514 Buffer const * Buffer::masterBuffer() const
2516 Buffer const * const pbuf = d->parent();
2520 return pbuf->masterBuffer();
2524 bool Buffer::isChild(Buffer * child) const
2526 return d->children_positions.find(child) != d->children_positions.end();
2530 DocIterator Buffer::firstChildPosition(Buffer const * child)
2532 Impl::BufferPositionMap::iterator it;
2533 it = d->children_positions.find(child);
2534 if (it == d->children_positions.end())
2535 return DocIterator(this);
2540 void Buffer::getChildren(ListOfBuffers & clist, bool grand_children) const
2542 // loop over children
2543 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2544 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2545 for (; it != end; ++it) {
2546 Buffer * child = const_cast<Buffer *>(it->first);
2547 clist.push_back(child);
2548 if (grand_children) {
2549 // there might be grandchildren
2550 ListOfBuffers glist = child->getChildren();
2551 clist.insert(clist.end(), glist.begin(), glist.end());
2557 ListOfBuffers Buffer::getChildren(bool grand_children) const
2560 getChildren(v, grand_children);
2565 template<typename M>
2566 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
2571 typename M::const_iterator it = m.lower_bound(x);
2572 if (it == m.begin())
2580 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
2581 DocIterator const & pos) const
2583 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2585 // if paragraphs have no macro context set, pos will be empty
2589 // we haven't found anything yet
2590 DocIterator bestPos = owner_->par_iterator_begin();
2591 MacroData const * bestData = 0;
2593 // find macro definitions for name
2594 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
2595 if (nameIt != macros.end()) {
2596 // find last definition in front of pos or at pos itself
2597 PositionScopeMacroMap::const_iterator it
2598 = greatest_below(nameIt->second, pos);
2599 if (it != nameIt->second.end()) {
2601 // scope ends behind pos?
2602 if (pos < it->second.first) {
2603 // Looks good, remember this. If there
2604 // is no external macro behind this,
2605 // we found the right one already.
2606 bestPos = it->first;
2607 bestData = &it->second.second;
2611 // try previous macro if there is one
2612 if (it == nameIt->second.begin())
2619 // find macros in included files
2620 PositionScopeBufferMap::const_iterator it
2621 = greatest_below(position_to_children, pos);
2622 if (it == position_to_children.end())
2623 // no children before
2627 // do we know something better (i.e. later) already?
2628 if (it->first < bestPos )
2631 // scope ends behind pos?
2632 if (pos < it->second.first) {
2633 // look for macro in external file
2635 MacroData const * data
2636 = it->second.second->getMacro(name, false);
2639 bestPos = it->first;
2645 // try previous file if there is one
2646 if (it == position_to_children.begin())
2651 // return the best macro we have found
2656 MacroData const * Buffer::getMacro(docstring const & name,
2657 DocIterator const & pos, bool global) const
2662 // query buffer macros
2663 MacroData const * data = d->getBufferMacro(name, pos);
2667 // If there is a master buffer, query that
2668 Buffer const * const pbuf = d->parent();
2670 d->macro_lock = true;
2671 MacroData const * macro = pbuf->getMacro(
2672 name, *this, false);
2673 d->macro_lock = false;
2679 data = MacroTable::globalMacros().get(name);
2688 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2690 // set scope end behind the last paragraph
2691 DocIterator scope = par_iterator_begin();
2692 scope.pit() = scope.lastpit() + 1;
2694 return getMacro(name, scope, global);
2698 MacroData const * Buffer::getMacro(docstring const & name,
2699 Buffer const & child, bool global) const
2701 // look where the child buffer is included first
2702 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2703 if (it == d->children_positions.end())
2706 // check for macros at the inclusion position
2707 return getMacro(name, it->second, global);
2711 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
2713 pit_type const lastpit = it.lastpit();
2715 // look for macros in each paragraph
2716 while (it.pit() <= lastpit) {
2717 Paragraph & par = it.paragraph();
2719 // iterate over the insets of the current paragraph
2720 InsetList const & insets = par.insetList();
2721 InsetList::const_iterator iit = insets.begin();
2722 InsetList::const_iterator end = insets.end();
2723 for (; iit != end; ++iit) {
2724 it.pos() = iit->pos;
2726 // is it a nested text inset?
2727 if (iit->inset->asInsetText()) {
2728 // Inset needs its own scope?
2729 InsetText const * itext = iit->inset->asInsetText();
2730 bool newScope = itext->isMacroScope();
2732 // scope which ends just behind the inset
2733 DocIterator insetScope = it;
2736 // collect macros in inset
2737 it.push_back(CursorSlice(*iit->inset));
2738 updateMacros(it, newScope ? insetScope : scope);
2743 // is it an external file?
2744 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2745 // get buffer of external file
2746 InsetInclude const & inset =
2747 static_cast<InsetInclude const &>(*iit->inset);
2749 Buffer * child = inset.getChildBuffer();
2754 // register its position, but only when it is
2755 // included first in the buffer
2756 if (children_positions.find(child) ==
2757 children_positions.end())
2758 children_positions[child] = it;
2760 // register child with its scope
2761 position_to_children[it] = Impl::ScopeBuffer(scope, child);
2765 if (doing_export && iit->inset->asInsetMath()) {
2766 InsetMath * im = static_cast<InsetMath *>(iit->inset);
2767 if (im->asHullInset()) {
2768 InsetMathHull * hull = static_cast<InsetMathHull *>(im);
2769 hull->recordLocation(it);
2773 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2777 MathMacroTemplate & macroTemplate =
2778 static_cast<MathMacroTemplate &>(*iit->inset);
2779 MacroContext mc(owner_, it);
2780 macroTemplate.updateToContext(mc);
2783 bool valid = macroTemplate.validMacro();
2784 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2785 // then the BufferView's cursor will be invalid in
2786 // some cases which leads to crashes.
2791 // FIXME (Abdel), I don't understandt why we pass 'it' here
2792 // instead of 'macroTemplate' defined above... is this correct?
2793 macros[macroTemplate.name()][it] =
2794 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
2804 void Buffer::updateMacros() const
2809 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2811 // start with empty table
2813 d->children_positions.clear();
2814 d->position_to_children.clear();
2816 // Iterate over buffer, starting with first paragraph
2817 // The scope must be bigger than any lookup DocIterator
2818 // later. For the global lookup, lastpit+1 is used, hence
2819 // we use lastpit+2 here.
2820 DocIterator it = par_iterator_begin();
2821 DocIterator outerScope = it;
2822 outerScope.pit() = outerScope.lastpit() + 2;
2823 d->updateMacros(it, outerScope);
2827 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
2829 InsetIterator it = inset_iterator_begin(inset());
2830 InsetIterator const end = inset_iterator_end(inset());
2831 for (; it != end; ++it) {
2832 if (it->lyxCode() == BRANCH_CODE) {
2833 InsetBranch & br = static_cast<InsetBranch &>(*it);
2834 docstring const name = br.branch();
2835 if (!from_master && !params().branchlist().find(name))
2836 result.push_back(name);
2837 else if (from_master && !masterBuffer()->params().branchlist().find(name))
2838 result.push_back(name);
2841 if (it->lyxCode() == INCLUDE_CODE) {
2842 // get buffer of external file
2843 InsetInclude const & ins =
2844 static_cast<InsetInclude const &>(*it);
2845 Buffer * child = ins.getChildBuffer();
2848 child->getUsedBranches(result, true);
2851 // remove duplicates
2856 void Buffer::updateMacroInstances() const
2858 LYXERR(Debug::MACROS, "updateMacroInstances for "
2859 << d->filename.onlyFileName());
2860 DocIterator it = doc_iterator_begin(this);
2862 DocIterator const end = doc_iterator_end(this);
2863 for (; it != end; it.forwardInset()) {
2864 // look for MathData cells in InsetMathNest insets
2865 InsetMath * minset = it.nextInset()->asInsetMath();
2869 // update macro in all cells of the InsetMathNest
2870 DocIterator::idx_type n = minset->nargs();
2871 MacroContext mc = MacroContext(this, it);
2872 for (DocIterator::idx_type i = 0; i < n; ++i) {
2873 MathData & data = minset->cell(i);
2874 data.updateMacros(0, mc);
2880 void Buffer::listMacroNames(MacroNameSet & macros) const
2885 d->macro_lock = true;
2887 // loop over macro names
2888 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2889 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2890 for (; nameIt != nameEnd; ++nameIt)
2891 macros.insert(nameIt->first);
2893 // loop over children
2894 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2895 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2896 for (; it != end; ++it)
2897 it->first->listMacroNames(macros);
2900 Buffer const * const pbuf = d->parent();
2902 pbuf->listMacroNames(macros);
2904 d->macro_lock = false;
2908 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2910 Buffer const * const pbuf = d->parent();
2915 pbuf->listMacroNames(names);
2918 MacroNameSet::iterator it = names.begin();
2919 MacroNameSet::iterator end = names.end();
2920 for (; it != end; ++it) {
2922 MacroData const * data =
2923 pbuf->getMacro(*it, *this, false);
2925 macros.insert(data);
2927 // we cannot access the original MathMacroTemplate anymore
2928 // here to calls validate method. So we do its work here manually.
2929 // FIXME: somehow make the template accessible here.
2930 if (data->optionals() > 0)
2931 features.require("xargs");
2937 Buffer::References & Buffer::references(docstring const & label)
2940 return const_cast<Buffer *>(masterBuffer())->references(label);
2942 RefCache::iterator it = d->ref_cache_.find(label);
2943 if (it != d->ref_cache_.end())
2944 return it->second.second;
2946 static InsetLabel const * dummy_il = 0;
2947 static References const dummy_refs;
2948 it = d->ref_cache_.insert(
2949 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2950 return it->second.second;
2954 Buffer::References const & Buffer::references(docstring const & label) const
2956 return const_cast<Buffer *>(this)->references(label);
2960 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2962 masterBuffer()->d->ref_cache_[label].first = il;
2966 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2968 return masterBuffer()->d->ref_cache_[label].first;
2972 void Buffer::clearReferenceCache() const
2975 d->ref_cache_.clear();
2979 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2982 //FIXME: This does not work for child documents yet.
2983 LASSERT(code == CITE_CODE, /**/);
2984 // Check if the label 'from' appears more than once
2985 vector<docstring> labels;
2987 checkBibInfoCache();
2988 BiblioInfo const & keys = masterBibInfo();
2989 BiblioInfo::const_iterator bit = keys.begin();
2990 BiblioInfo::const_iterator bend = keys.end();
2992 for (; bit != bend; ++bit)
2994 labels.push_back(bit->first);
2997 if (count(labels.begin(), labels.end(), from) > 1)
3000 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3001 if (it->lyxCode() == code) {
3002 InsetCommand & inset = static_cast<InsetCommand &>(*it);
3003 docstring const oldValue = inset.getParam(paramName);
3004 if (oldValue == from)
3005 inset.setParam(paramName, to);
3011 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
3012 pit_type par_end, bool full_source) const
3014 OutputParams runparams(¶ms().encoding());
3015 runparams.nice = true;
3016 runparams.flavor = params().useXetex ?
3017 OutputParams::XETEX : OutputParams::LATEX;
3018 runparams.linelen = lyxrc.plaintext_linelen;
3019 // No side effect of file copying and image conversion
3020 runparams.dryrun = true;
3023 os << "% " << _("Preview source code") << "\n\n";
3025 d->texrow.newline();
3026 d->texrow.newline();
3028 writeDocBookSource(os, absFileName(), runparams, false);
3030 // latex or literate
3031 writeLaTeXSource(os, string(), runparams, true, true);
3033 runparams.par_begin = par_begin;
3034 runparams.par_end = par_end;
3035 if (par_begin + 1 == par_end) {
3037 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3041 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3042 convert<docstring>(par_begin),
3043 convert<docstring>(par_end - 1))
3050 // output paragraphs
3052 docbookParagraphs(text(), *this, os, runparams);
3054 // latex or literate
3055 latexParagraphs(*this, text(), os, texrow, runparams);
3060 ErrorList & Buffer::errorList(string const & type) const
3062 static ErrorList emptyErrorList;
3063 map<string, ErrorList>::iterator it = d->errorLists.find(type);
3064 if (it == d->errorLists.end())
3065 return emptyErrorList;
3071 void Buffer::updateTocItem(std::string const & type,
3072 DocIterator const & dit) const
3075 d->gui_->updateTocItem(type, dit);
3079 void Buffer::structureChanged() const
3082 d->gui_->structureChanged();
3086 void Buffer::errors(string const & err, bool from_master) const
3089 d->gui_->errors(err, from_master);
3093 void Buffer::message(docstring const & msg) const
3096 d->gui_->message(msg);
3100 void Buffer::setBusy(bool on) const
3103 d->gui_->setBusy(on);
3107 void Buffer::updateTitles() const
3110 d->wa_->updateTitles();
3114 void Buffer::resetAutosaveTimers() const
3117 d->gui_->resetAutosaveTimers();
3121 bool Buffer::hasGuiDelegate() const
3127 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3136 class AutoSaveBuffer : public ForkedProcess {
3139 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3140 : buffer_(buffer), fname_(fname) {}
3142 virtual shared_ptr<ForkedProcess> clone() const
3144 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3149 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3150 from_utf8(fname_.absFileName())));
3151 return run(DontWait);
3155 virtual int generateChild();
3157 Buffer const & buffer_;
3162 int AutoSaveBuffer::generateChild()
3164 #if defined(__APPLE__)
3165 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3166 * We should use something else like threads.
3168 * Since I do not know how to determine at run time what is the OS X
3169 * version, I just disable forking altogether for now (JMarc)
3171 pid_t const pid = -1;
3173 // tmp_ret will be located (usually) in /tmp
3174 // will that be a problem?
3175 // Note that this calls ForkedCalls::fork(), so it's
3176 // ok cross-platform.
3177 pid_t const pid = fork();
3178 // If you want to debug the autosave
3179 // you should set pid to -1, and comment out the fork.
3180 if (pid != 0 && pid != -1)
3184 // pid = -1 signifies that lyx was unable
3185 // to fork. But we will do the save
3187 bool failed = false;
3188 FileName const tmp_ret = FileName::tempName("lyxauto");
3189 if (!tmp_ret.empty()) {
3190 buffer_.writeFile(tmp_ret);
3191 // assume successful write of tmp_ret
3192 if (!tmp_ret.moveTo(fname_))
3198 // failed to write/rename tmp_ret so try writing direct
3199 if (!buffer_.writeFile(fname_)) {
3200 // It is dangerous to do this in the child,
3201 // but safe in the parent, so...
3202 if (pid == -1) // emit message signal.
3203 buffer_.message(_("Autosave failed!"));
3207 if (pid == 0) // we are the child so...
3216 FileName Buffer::getAutosaveFileName() const
3218 // if the document is unnamed try to save in the backup dir, else
3219 // in the default document path, and as a last try in the filePath,
3220 // which will most often be the temporary directory
3223 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3224 : lyxrc.backupdir_path;
3225 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3228 string const fname = "#" + d->filename.onlyFileName() + "#";
3229 return makeAbsPath(fname, fpath);
3233 void Buffer::removeAutosaveFile() const
3235 FileName const f = getAutosaveFileName();
3241 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3243 FileName const newauto = getAutosaveFileName();
3245 if (newauto != oldauto && oldauto.exists())
3246 if (!oldauto.moveTo(newauto))
3247 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3251 // Perfect target for a thread...
3252 void Buffer::autoSave() const
3254 if (d->bak_clean || isReadonly()) {
3255 // We don't save now, but we'll try again later
3256 resetAutosaveTimers();
3260 // emit message signal.
3261 message(_("Autosaving current document..."));
3262 AutoSaveBuffer autosave(*this, getAutosaveFileName());
3265 d->bak_clean = true;
3267 resetAutosaveTimers();
3271 string Buffer::bufferFormat() const
3273 string format = params().documentClass().outputFormat();
3274 if (format == "latex") {
3275 if (params().useXetex)
3277 if (params().encoding().package() == Encoding::japanese)
3284 string Buffer::getDefaultOutputFormat() const
3286 if (!params().defaultOutputFormat.empty()
3287 && params().defaultOutputFormat != "default")
3288 return params().defaultOutputFormat;
3289 typedef vector<Format const *> Formats;
3290 Formats formats = exportableFormats(true);
3293 || params().useXetex
3294 || params().encoding().package() == Encoding::japanese) {
3295 if (formats.empty())
3297 // return the first we find
3298 return formats.front()->name();
3300 return lyxrc.default_view_format;
3305 // helper class, to guarantee this gets reset properly
3306 class MarkAsExporting {
3308 MarkAsExporting(Buffer const * buf) : buf_(buf)
3310 LASSERT(buf_, /* */);
3311 buf_->setExportStatus(true);
3315 buf_->setExportStatus(false);
3318 Buffer const * const buf_;
3323 void Buffer::setExportStatus(bool e) const
3325 d->doing_export = e;
3329 bool Buffer::isExporting() const
3331 return d->doing_export;
3335 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3336 bool includeall, string & result_file) const
3338 MarkAsExporting exporting(this);
3339 string backend_format;
3340 OutputParams runparams(¶ms().encoding());
3341 runparams.flavor = OutputParams::LATEX;
3342 runparams.linelen = lyxrc.plaintext_linelen;
3343 runparams.includeall = includeall;
3344 vector<string> backs = backends();
3345 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3346 // Get shortest path to format
3347 Graph::EdgePath path;
3348 for (vector<string>::const_iterator it = backs.begin();
3349 it != backs.end(); ++it) {
3350 Graph::EdgePath p = theConverters().getPath(*it, format);
3351 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3352 backend_format = *it;
3357 if (!put_in_tempdir) {
3358 // Only show this alert if this is an export to a non-temporary
3359 // file (not for previewing).
3360 Alert::error(_("Couldn't export file"), bformat(
3361 _("No information for exporting the format %1$s."),
3362 formats.prettyName(format)));
3366 runparams.flavor = theConverters().getFlavor(path);
3369 backend_format = format;
3370 // FIXME: Don't hardcode format names here, but use a flag
3371 if (backend_format == "pdflatex")
3372 runparams.flavor = OutputParams::PDFLATEX;
3375 string filename = latexName(false);
3376 filename = addName(temppath(), filename);
3377 filename = changeExtension(filename,
3378 formats.extension(backend_format));
3381 updateMacroInstances();
3383 // Plain text backend
3384 if (backend_format == "text") {
3385 runparams.flavor = OutputParams::TEXT;
3386 writePlaintextFile(*this, FileName(filename), runparams);
3389 else if (backend_format == "xhtml") {
3390 runparams.flavor = OutputParams::HTML;
3391 switch (params().html_math_output) {
3392 case BufferParams::MathML:
3393 runparams.math_flavor = OutputParams::MathAsMathML;
3395 case BufferParams::HTML:
3396 runparams.math_flavor = OutputParams::MathAsHTML;
3398 case BufferParams::Images:
3399 runparams.math_flavor = OutputParams::MathAsImages;
3401 case BufferParams::LaTeX:
3402 runparams.math_flavor = OutputParams::MathAsLaTeX;
3406 makeLyXHTMLFile(FileName(filename), runparams);
3407 } else if (backend_format == "lyx")
3408 writeFile(FileName(filename));
3410 else if (isDocBook()) {
3411 runparams.nice = !put_in_tempdir;
3412 makeDocBookFile(FileName(filename), runparams);
3415 else if (backend_format == format) {
3416 runparams.nice = true;
3417 if (!makeLaTeXFile(FileName(filename), string(), runparams))
3419 } else if (!lyxrc.tex_allows_spaces
3420 && contains(filePath(), ' ')) {
3421 Alert::error(_("File name error"),
3422 _("The directory path to the document cannot contain spaces."));
3425 runparams.nice = false;
3426 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
3430 string const error_type = (format == "program")
3431 ? "Build" : bufferFormat();
3432 ErrorList & error_list = d->errorLists[error_type];
3433 string const ext = formats.extension(format);
3434 FileName const tmp_result_file(changeExtension(filename, ext));
3435 bool const success = theConverters().convert(this, FileName(filename),
3436 tmp_result_file, FileName(absFileName()), backend_format, format,
3439 // Emit the signal to show the error list or copy it back to the
3440 // cloned Buffer so that it cab be emitted afterwards.
3441 if (format != backend_format) {
3442 if (d->cloned_buffer_) {
3443 d->cloned_buffer_->d->errorLists[error_type] =
3444 d->errorLists[error_type];
3447 // also to the children, in case of master-buffer-view
3448 ListOfBuffers clist = getChildren();
3449 ListOfBuffers::const_iterator cit = clist.begin();
3450 ListOfBuffers::const_iterator const cen = clist.end();
3451 for (; cit != cen; ++cit) {
3452 if (d->cloned_buffer_) {
3453 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
3454 (*cit)->d->errorLists[error_type];
3456 (*cit)->errors(error_type, true);
3460 if (d->cloned_buffer_) {
3461 // Enable reverse dvi or pdf to work by copying back the texrow
3462 // object to the cloned buffer.
3463 // FIXME: There is a possibility of concurrent access to texrow
3464 // here from the main GUI thread that should be securized.
3465 d->cloned_buffer_->d->texrow = d->texrow;
3466 string const error_type = bufferFormat();
3467 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
3473 if (put_in_tempdir) {
3474 result_file = tmp_result_file.absFileName();
3478 result_file = changeExtension(d->exportFileName().absFileName(), ext);
3479 // We need to copy referenced files (e. g. included graphics
3480 // if format == "dvi") to the result dir.
3481 vector<ExportedFile> const files =
3482 runparams.exportdata->externalFiles(format);
3483 string const dest = onlyPath(result_file);
3484 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
3485 : force_overwrite == ALL_FILES;
3486 CopyStatus status = use_force ? FORCE : SUCCESS;
3488 vector<ExportedFile>::const_iterator it = files.begin();
3489 vector<ExportedFile>::const_iterator const en = files.end();
3490 for (; it != en && status != CANCEL; ++it) {
3491 string const fmt = formats.getFormatFromFile(it->sourceName);
3492 status = copyFile(fmt, it->sourceName,
3493 makeAbsPath(it->exportName, dest),
3494 it->exportName, status == FORCE);
3497 if (status == CANCEL) {
3498 message(_("Document export cancelled."));
3499 } else if (tmp_result_file.exists()) {
3500 // Finally copy the main file
3501 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
3502 : force_overwrite != NO_FILES;
3503 if (status == SUCCESS && use_force)
3505 status = copyFile(format, tmp_result_file,
3506 FileName(result_file), result_file,
3508 message(bformat(_("Document exported as %1$s "
3510 formats.prettyName(format),
3511 makeDisplayPath(result_file)));
3513 // This must be a dummy converter like fax (bug 1888)
3514 message(bformat(_("Document exported as %1$s"),
3515 formats.prettyName(format)));
3522 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3523 bool includeall) const
3526 // (1) export with all included children (omit \includeonly)
3527 if (includeall && !doExport(format, put_in_tempdir, true, result_file))
3529 // (2) export with included children only
3530 return doExport(format, put_in_tempdir, false, result_file);
3534 bool Buffer::preview(string const & format, bool includeall) const
3536 MarkAsExporting exporting(this);
3538 // (1) export with all included children (omit \includeonly)
3539 if (includeall && !doExport(format, true, true))
3541 // (2) export with included children only
3542 if (!doExport(format, true, false, result_file))
3544 return formats.view(*this, FileName(result_file), format);
3548 bool Buffer::isExportable(string const & format) const
3550 vector<string> backs = backends();
3551 for (vector<string>::const_iterator it = backs.begin();
3552 it != backs.end(); ++it)
3553 if (theConverters().isReachable(*it, format))
3559 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
3561 vector<string> const backs = backends();
3562 vector<Format const *> result =
3563 theConverters().getReachable(backs[0], only_viewable, true);
3564 for (vector<string>::const_iterator it = backs.begin() + 1;
3565 it != backs.end(); ++it) {
3566 vector<Format const *> r =
3567 theConverters().getReachable(*it, only_viewable, false);
3568 result.insert(result.end(), r.begin(), r.end());
3574 vector<string> Buffer::backends() const
3577 v.push_back(bufferFormat());
3578 // FIXME: Don't hardcode format names here, but use a flag
3579 if (v.back() == "latex")
3580 v.push_back("pdflatex");
3581 v.push_back("xhtml");
3582 v.push_back("text");
3588 bool Buffer::readFileHelper(FileName const & s)
3590 // File information about normal file
3592 docstring const file = makeDisplayPath(s.absFileName(), 50);
3593 docstring text = bformat(_("The specified document\n%1$s"
3594 "\ncould not be read."), file);
3595 Alert::error(_("Could not read document"), text);
3599 // Check if emergency save file exists and is newer.
3600 FileName const e(s.absFileName() + ".emergency");
3602 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
3603 docstring const file = makeDisplayPath(s.absFileName(), 20);
3604 docstring const text =
3605 bformat(_("An emergency save of the document "
3607 "Recover emergency save?"), file);
3608 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
3609 _("&Recover"), _("&Load Original"),
3613 // the file is not saved if we load the emergency file.
3618 if ((res = readFile(e)) == success)
3619 str = _("Document was successfully recovered.");
3621 str = _("Document was NOT successfully recovered.");
3622 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3623 makeDisplayPath(e.absFileName()));
3625 if (!Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3626 _("&Remove"), _("&Keep it"))) {
3629 Alert::warning(_("Emergency file deleted"),
3630 _("Do not forget to save your file now!"), true);
3635 if (!Alert::prompt(_("Delete emergency file?"),
3636 _("Remove emergency file now?"), 1, 1,
3637 _("&Remove"), _("&Keep it")))
3645 // Now check if autosave file is newer.
3646 FileName const a(onlyPath(s.absFileName()) + '#' + onlyFileName(s.absFileName()) + '#');
3648 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
3649 docstring const file = makeDisplayPath(s.absFileName(), 20);
3650 docstring const text =
3651 bformat(_("The backup of the document "
3652 "%1$s is newer.\n\nLoad the "
3653 "backup instead?"), file);
3654 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
3655 _("&Load backup"), _("Load &original"),
3659 // the file is not saved if we load the autosave file.
3663 // Here we delete the autosave
3674 bool Buffer::loadLyXFile(FileName const & s)
3676 // If the file is not readable, we try to
3677 // retrieve the file from version control.
3678 if (!s.isReadableFile()
3679 && !LyXVC::file_not_found_hook(s))
3682 if (s.isReadableFile()){
3683 // InsetInfo needs to know if file is under VCS
3684 lyxvc().file_found_hook(s);
3685 if (readFileHelper(s)) {
3686 d->read_only = !s.isWritable();
3694 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3696 TeXErrors::Errors::const_iterator cit = terr.begin();
3697 TeXErrors::Errors::const_iterator end = terr.end();
3699 for (; cit != end; ++cit) {
3702 int errorRow = cit->error_in_line;
3703 bool found = d->texrow.getIdFromRow(errorRow, id_start,
3709 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
3710 } while (found && id_start == id_end && pos_start == pos_end);
3712 errorList.push_back(ErrorItem(cit->error_desc,
3713 cit->error_text, id_start, pos_start, pos_end));
3718 void Buffer::setBuffersForInsets() const
3720 inset().setBuffer(const_cast<Buffer &>(*this));
3724 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
3726 // Use the master text class also for child documents
3727 Buffer const * const master = masterBuffer();
3728 DocumentClass const & textclass = master->params().documentClass();
3730 // do this only if we are the top-level Buffer
3732 checkBibInfoCache();
3734 // keep the buffers to be children in this set. If the call from the
3735 // master comes back we can see which of them were actually seen (i.e.
3736 // via an InsetInclude). The remaining ones in the set need still be updated.
3737 static std::set<Buffer const *> bufToUpdate;
3738 if (scope == UpdateMaster) {
3739 // If this is a child document start with the master
3740 if (master != this) {
3741 bufToUpdate.insert(this);
3742 master->updateBuffer(UpdateMaster, utype);
3743 // Do this here in case the master has no gui associated with it. Then,
3744 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3745 if (!master->d->gui_)
3748 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3749 if (bufToUpdate.find(this) == bufToUpdate.end())
3753 // start over the counters in the master
3754 textclass.counters().reset();
3757 // update will be done below for this buffer
3758 bufToUpdate.erase(this);
3760 // update all caches
3761 clearReferenceCache();
3764 Buffer & cbuf = const_cast<Buffer &>(*this);
3766 LASSERT(!text().paragraphs().empty(), /**/);
3769 ParIterator parit = cbuf.par_iterator_begin();
3770 updateBuffer(parit, utype);
3773 // TocBackend update will be done later.
3776 cbuf.tocBackend().update();
3777 if (scope == UpdateMaster)
3778 cbuf.structureChanged();
3782 static depth_type getDepth(DocIterator const & it)
3784 depth_type depth = 0;
3785 for (size_t i = 0 ; i < it.depth() ; ++i)
3786 if (!it[i].inset().inMathed())
3787 depth += it[i].paragraph().getDepth() + 1;
3788 // remove 1 since the outer inset does not count
3792 static depth_type getItemDepth(ParIterator const & it)
3794 Paragraph const & par = *it;
3795 LabelType const labeltype = par.layout().labeltype;
3797 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3800 // this will hold the lowest depth encountered up to now.
3801 depth_type min_depth = getDepth(it);
3802 ParIterator prev_it = it;
3805 --prev_it.top().pit();
3807 // start of nested inset: go to outer par
3809 if (prev_it.empty()) {
3810 // start of document: nothing to do
3815 // We search for the first paragraph with same label
3816 // that is not more deeply nested.
3817 Paragraph & prev_par = *prev_it;
3818 depth_type const prev_depth = getDepth(prev_it);
3819 if (labeltype == prev_par.layout().labeltype) {
3820 if (prev_depth < min_depth)
3821 return prev_par.itemdepth + 1;
3822 if (prev_depth == min_depth)
3823 return prev_par.itemdepth;
3825 min_depth = min(min_depth, prev_depth);
3826 // small optimization: if we are at depth 0, we won't
3827 // find anything else
3828 if (prev_depth == 0)
3834 static bool needEnumCounterReset(ParIterator const & it)
3836 Paragraph const & par = *it;
3837 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3838 depth_type const cur_depth = par.getDepth();
3839 ParIterator prev_it = it;
3840 while (prev_it.pit()) {
3841 --prev_it.top().pit();
3842 Paragraph const & prev_par = *prev_it;
3843 if (prev_par.getDepth() <= cur_depth)
3844 return prev_par.layout().labeltype != LABEL_ENUMERATE;
3846 // start of nested inset: reset
3851 // set the label of a paragraph. This includes the counters.
3852 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
3854 BufferParams const & bp = owner_->masterBuffer()->params();
3855 DocumentClass const & textclass = bp.documentClass();
3856 Paragraph & par = it.paragraph();
3857 Layout const & layout = par.layout();
3858 Counters & counters = textclass.counters();
3860 if (par.params().startOfAppendix()) {
3861 // FIXME: only the counter corresponding to toplevel
3862 // sectioning should be reset
3864 counters.appendix(true);
3866 par.params().appendix(counters.appendix());
3868 // Compute the item depth of the paragraph
3869 par.itemdepth = getItemDepth(it);
3871 if (layout.margintype == MARGIN_MANUAL
3872 || layout.latextype == LATEX_BIB_ENVIRONMENT) {
3873 if (par.params().labelWidthString().empty())
3874 par.params().labelWidthString(par.expandLabel(layout, bp));
3876 par.params().labelWidthString(docstring());
3879 switch(layout.labeltype) {
3881 if (layout.toclevel <= bp.secnumdepth
3882 && (layout.latextype != LATEX_ENVIRONMENT
3883 || it.text()->isFirstInSequence(it.pit()))) {
3884 counters.step(layout.counter, utype);
3885 par.params().labelString(
3886 par.expandLabel(layout, bp));
3888 par.params().labelString(docstring());
3891 case LABEL_ITEMIZE: {
3892 // At some point of time we should do something more
3893 // clever here, like:
3894 // par.params().labelString(
3895 // bp.user_defined_bullet(par.itemdepth).getText());
3896 // for now, use a simple hardcoded label
3897 docstring itemlabel;
3898 switch (par.itemdepth) {
3900 itemlabel = char_type(0x2022);
3903 itemlabel = char_type(0x2013);
3906 itemlabel = char_type(0x2217);
3909 itemlabel = char_type(0x2219); // or 0x00b7
3912 par.params().labelString(itemlabel);
3916 case LABEL_ENUMERATE: {
3917 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
3919 switch (par.itemdepth) {
3928 enumcounter += "iv";
3931 // not a valid enumdepth...
3935 // Maybe we have to reset the enumeration counter.
3936 if (needEnumCounterReset(it))
3937 counters.reset(enumcounter);
3938 counters.step(enumcounter, utype);
3940 string const & lang = par.getParLanguage(bp)->code();
3941 par.params().labelString(counters.theCounter(enumcounter, lang));
3946 case LABEL_SENSITIVE: {
3947 string const & type = counters.current_float();
3948 docstring full_label;
3950 full_label = owner_->B_("Senseless!!! ");
3952 docstring name = owner_->B_(textclass.floats().getType(type).name());
3953 if (counters.hasCounter(from_utf8(type))) {
3954 string const & lang = par.getParLanguage(bp)->code();
3955 counters.step(from_utf8(type), utype);
3956 full_label = bformat(from_ascii("%1$s %2$s:"),
3958 counters.theCounter(from_utf8(type), lang));
3960 full_label = bformat(from_ascii("%1$s #:"), name);
3962 par.params().labelString(full_label);
3966 case LABEL_NO_LABEL:
3967 par.params().labelString(docstring());
3971 case LABEL_TOP_ENVIRONMENT:
3972 case LABEL_CENTERED_TOP_ENVIRONMENT:
3975 par.params().labelString(par.expandLabel(layout, bp));
3981 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
3983 LASSERT(parit.pit() == 0, /**/);
3985 // set the position of the text in the buffer to be able
3986 // to resolve macros in it. This has nothing to do with
3987 // labels, but by putting it here we avoid implementing
3988 // a whole bunch of traversal routines just for this call.
3989 parit.text()->setMacrocontextPosition(parit);
3991 depth_type maxdepth = 0;
3992 pit_type const lastpit = parit.lastpit();
3993 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
3994 // reduce depth if necessary
3995 parit->params().depth(min(parit->params().depth(), maxdepth));
3996 maxdepth = parit->getMaxDepthAfter();
3998 if (utype == OutputUpdate) {
3999 // track the active counters
4000 // we have to do this for the master buffer, since the local
4001 // buffer isn't tracking anything.
4002 masterBuffer()->params().documentClass().counters().
4003 setActiveLayout(parit->layout());
4006 // set the counter for this paragraph
4007 d->setLabel(parit, utype);
4010 InsetList::const_iterator iit = parit->insetList().begin();
4011 InsetList::const_iterator end = parit->insetList().end();
4012 for (; iit != end; ++iit) {
4013 parit.pos() = iit->pos;
4014 iit->inset->updateBuffer(parit, utype);
4020 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4021 WordLangTuple & word_lang, docstring_list & suggestions) const
4025 suggestions.clear();
4026 word_lang = WordLangTuple();
4027 // OK, we start from here.
4028 DocIterator const end = doc_iterator_end(this);
4029 for (; from != end; from.forwardPos()) {
4030 // We are only interested in text so remove the math CursorSlice.
4031 while (from.inMathed()) {
4035 // If from is at the end of the document (which is possible
4036 // when leaving the mathed) LyX will crash later.
4040 from.paragraph().spellCheck();
4041 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4042 if (SpellChecker::misspelled(res)) {
4047 // Do not increase progress when from == to, otherwise the word
4048 // count will be wrong.
4058 bool Buffer::reload()
4062 removeAutosaveFile();
4063 // e.g., read-only status could have changed due to version control
4064 d->filename.refresh();
4065 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4067 bool const success = loadLyXFile(d->filename);
4073 message(bformat(_("Document %1$s reloaded."), disp_fn));
4075 message(bformat(_("Could not reload document %1$s."), disp_fn));
4078 thePreviews().removeLoader(*this);
4079 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
4080 thePreviews().generateBufferPreviews(*this);
4086 // FIXME We could do better here, but it is complicated. What would be
4087 // nice is to offer either (a) to save the child buffer to an appropriate
4088 // location, so that it would "move with the master", or else (b) to update
4089 // the InsetInclude so that it pointed to the same file. But (a) is a bit
4090 // complicated, because the code for this lives in GuiView.
4091 void Buffer::checkChildBuffers()
4093 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4094 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4095 for (; it != en; ++it) {
4096 DocIterator dit = it->second;
4097 Buffer * cbuf = const_cast<Buffer *>(it->first);
4098 if (!cbuf || !theBufferList().isLoaded(cbuf))
4100 Inset * inset = dit.nextInset();
4101 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4102 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4103 docstring const & incfile = inset_inc->getParam("filename");
4104 string oldloc = cbuf->absFileName();
4105 string newloc = makeAbsPath(to_utf8(incfile),
4106 onlyPath(absFileName())).absFileName();
4107 if (oldloc == newloc)
4109 // the location of the child file is incorrect.
4110 Alert::warning(_("Included File Invalid"),
4111 bformat(_("Saving this document to a new location has made the file:\n"
4113 "inaccessible. You will need to update the included filename."),
4114 from_utf8(oldloc)));
4116 inset_inc->setChildBuffer(0);
4118 // invalidate cache of children
4119 d->children_positions.clear();
4120 d->position_to_children.clear();