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/InsetTabular.h"
74 #include "insets/InsetText.h"
76 #include "mathed/InsetMathHull.h"
77 #include "mathed/MacroTable.h"
78 #include "mathed/MathMacroTemplate.h"
79 #include "mathed/MathSupport.h"
81 #include "frontends/alert.h"
82 #include "frontends/Delegates.h"
83 #include "frontends/WorkAreaManager.h"
85 #include "graphics/Previews.h"
87 #include "support/lassert.h"
88 #include "support/convert.h"
89 #include "support/debug.h"
90 #include "support/docstring_list.h"
91 #include "support/ExceptionMessage.h"
92 #include "support/FileName.h"
93 #include "support/FileNameList.h"
94 #include "support/filetools.h"
95 #include "support/ForkedCalls.h"
96 #include "support/gettext.h"
97 #include "support/gzstream.h"
98 #include "support/lstrings.h"
99 #include "support/lyxalgo.h"
100 #include "support/os.h"
101 #include "support/Package.h"
102 #include "support/Path.h"
103 #include "support/Systemcall.h"
104 #include "support/textutils.h"
105 #include "support/types.h"
107 #include "support/bind.h"
108 #include "support/shared_ptr.h"
120 using namespace lyx::support;
124 namespace Alert = frontend::Alert;
125 namespace os = support::os;
129 // Do not remove the comment below, so we get merge conflict in
130 // independent branches. Instead add your own.
131 int const LYX_FORMAT = 404; // rgh: refstyle
133 typedef map<string, bool> DepClean;
134 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
136 void showPrintError(string const & name)
138 docstring str = bformat(_("Could not print the document %1$s.\n"
139 "Check that your printer is set up correctly."),
140 makeDisplayPath(name, 50));
141 Alert::error(_("Print document failed"), str);
150 Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
161 /// search for macro in local (buffer) table or in children
162 MacroData const * getBufferMacro(docstring const & name,
163 DocIterator const & pos) const;
165 /// Update macro table starting with position of it \param it in some
167 void updateMacros(DocIterator & it, DocIterator & scope);
169 void setLabel(ParIterator & it, UpdateType utype) const;
171 /** If we have branches that use the file suffix
172 feature, return the file name with suffix appended.
174 support::FileName exportFileName() const;
181 mutable TexRow texrow;
183 /// need to regenerate .tex?
187 mutable bool lyx_clean;
189 /// is autosave needed?
190 mutable bool bak_clean;
192 /// is this a unnamed file (New...)?
198 /// name of the file the buffer is associated with.
201 /** Set to true only when the file is fully loaded.
202 * Used to prevent the premature generation of previews
203 * and by the citation inset.
205 bool file_fully_loaded;
208 mutable TocBackend toc_backend;
211 typedef pair<DocIterator, MacroData> ScopeMacro;
212 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
213 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
214 /// map from the macro name to the position map,
215 /// which maps the macro definition position to the scope and the MacroData.
216 NamePositionScopeMacroMap macros;
217 /// This seem to change the way Buffer::getMacro() works
218 mutable bool macro_lock;
220 /// positions of child buffers in the buffer
221 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
222 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
223 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
224 /// position of children buffers in this buffer
225 BufferPositionMap children_positions;
226 /// map from children inclusion positions to their scope and their buffer
227 PositionScopeBufferMap position_to_children;
229 /// Container for all sort of Buffer dependant errors.
230 map<string, ErrorList> errorLists;
232 /// timestamp and checksum used to test if the file has been externally
233 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
235 unsigned long checksum_;
238 frontend::WorkAreaManager * wa_;
240 frontend::GuiBufferDelegate * gui_;
245 /// A cache for the bibfiles (including bibfiles of loaded child
246 /// documents), needed for appropriate update of natbib labels.
247 mutable support::FileNameList bibfiles_cache_;
249 // FIXME The caching mechanism could be improved. At present, we have a
250 // cache for each Buffer, that caches all the bibliography info for that
251 // Buffer. A more efficient solution would be to have a global cache per
252 // file, and then to construct the Buffer's bibinfo from that.
253 /// A cache for bibliography info
254 mutable BiblioInfo bibinfo_;
255 /// whether the bibinfo cache is valid
256 mutable bool bibinfo_cache_valid_;
257 /// whether the bibfile cache is valid
258 mutable bool bibfile_cache_valid_;
259 /// Cache of timestamps of .bib files
260 map<FileName, time_t> bibfile_status_;
262 mutable RefCache ref_cache_;
264 /// our Text that should be wrapped in an InsetText
267 /// This is here to force the test to be done whenever parent_buffer
269 Buffer const * parent() const {
270 // if parent_buffer is not loaded, then it has been unloaded,
271 // which means that parent_buffer is an invalid pointer. So we
272 // set it to null in that case.
273 // however, the BufferList doesn't know about cloned buffers, so
274 // they will always be regarded as unloaded. in that case, we hope
276 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
278 return parent_buffer;
282 void setParent(Buffer const * pb) {
283 if (parent_buffer == pb)
286 if (!cloned_buffer_ && parent_buffer && pb)
287 LYXERR0("Warning: a buffer should not have two parents!");
289 if (!cloned_buffer_ && parent_buffer) {
290 parent_buffer->invalidateBibfileCache();
291 parent_buffer->invalidateBibinfoCache();
295 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
296 /// This one is useful for preview detached in a thread.
297 Buffer const * cloned_buffer_;
298 /// are we in the process of exporting this buffer?
299 mutable bool doing_export;
302 /// So we can force access via the accessors.
303 mutable Buffer const * parent_buffer;
308 /// Creates the per buffer temporary directory
309 static FileName createBufferTmpDir()
312 // We are in our own directory. Why bother to mangle name?
313 // In fact I wrote this code to circumvent a problematic behaviour
314 // (bug?) of EMX mkstemp().
315 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
316 convert<string>(count++));
318 if (!tmpfl.createDirectory(0777)) {
319 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
320 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
321 from_utf8(tmpfl.absFileName())));
327 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
328 Buffer const * cloned_buffer)
329 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
330 read_only(readonly_), filename(file), file_fully_loaded(false),
331 toc_backend(owner), macro_lock(false), timestamp_(0),
332 checksum_(0), wa_(0), gui_(0), undo_(*owner), bibinfo_cache_valid_(false),
333 bibfile_cache_valid_(false), cloned_buffer_(cloned_buffer),
334 doing_export(false), parent_buffer(0)
336 if (!cloned_buffer_) {
337 temppath = createBufferTmpDir();
338 lyxvc.setBuffer(owner_);
340 wa_ = new frontend::WorkAreaManager;
343 temppath = cloned_buffer_->d->temppath;
344 file_fully_loaded = true;
345 params = cloned_buffer_->d->params;
346 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
347 bibinfo_ = cloned_buffer_->d->bibinfo_;
348 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
349 bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
350 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
354 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
355 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
357 LYXERR(Debug::INFO, "Buffer::Buffer()");
359 d->inset = new InsetText(*cloned_buffer->d->inset);
360 d->inset->setBuffer(*this);
361 // FIXME: optimize this loop somewhat, maybe by creating a new
362 // general recursive Inset::setId().
363 DocIterator it = doc_iterator_begin(this);
364 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
365 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
366 it.paragraph().setId(cloned_it.paragraph().id());
368 d->inset = new InsetText(this);
369 d->inset->setAutoBreakRows(true);
370 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
376 LYXERR(Debug::INFO, "Buffer::~Buffer()");
377 // here the buffer should take care that it is
378 // saved properly, before it goes into the void.
380 // GuiView already destroyed
384 // No need to do additional cleanups for internal buffer.
389 // loop over children
390 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
391 Impl::BufferPositionMap::iterator end = d->children_positions.end();
392 for (; it != end; ++it) {
393 Buffer * child = const_cast<Buffer *>(it->first);
394 if (d->cloned_buffer_)
396 // The child buffer might have been closed already.
397 else if (theBufferList().isLoaded(child))
398 theBufferList().releaseChild(this, child);
402 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
403 msg += emergencyWrite();
404 Alert::warning(_("Attempting to close changed document!"), msg);
407 // clear references to children in macro tables
408 d->children_positions.clear();
409 d->position_to_children.clear();
411 if (!d->cloned_buffer_ && !d->temppath.destroyDirectory()) {
412 Alert::warning(_("Could not remove temporary directory"),
413 bformat(_("Could not remove the temporary directory %1$s"),
414 from_utf8(d->temppath.absFileName())));
424 Buffer * Buffer::clone() const
426 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
427 buffer_clone->d->macro_lock = true;
428 buffer_clone->d->children_positions.clear();
429 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
430 // math macro caches need to be rethought and simplified.
431 // I am not sure wether we should handle Buffer cloning here or in BufferList.
432 // Right now BufferList knows nothing about buffer clones.
433 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
434 Impl::BufferPositionMap::iterator end = d->children_positions.end();
435 for (; it != end; ++it) {
436 DocIterator dit = it->second.clone(buffer_clone);
437 dit.setBuffer(buffer_clone);
438 Buffer * child = const_cast<Buffer *>(it->first);
439 Buffer * child_clone = child->clone();
440 Inset * inset = dit.nextInset();
441 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
442 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
443 inset_inc->setChildBuffer(child_clone);
444 child_clone->d->setParent(buffer_clone);
445 buffer_clone->setChild(dit, child_clone);
447 buffer_clone->d->macro_lock = false;
452 bool Buffer::isClone() const
454 return d->cloned_buffer_;
458 void Buffer::changed(bool update_metrics) const
461 d->wa_->redrawAll(update_metrics);
465 frontend::WorkAreaManager & Buffer::workAreaManager() const
467 LASSERT(d->wa_, /**/);
472 Text & Buffer::text() const
474 return d->inset->text();
478 Inset & Buffer::inset() const
484 BufferParams & Buffer::params()
490 BufferParams const & Buffer::params() const
496 ParagraphList & Buffer::paragraphs()
498 return text().paragraphs();
502 ParagraphList const & Buffer::paragraphs() const
504 return text().paragraphs();
508 LyXVC & Buffer::lyxvc()
514 LyXVC const & Buffer::lyxvc() const
520 string const Buffer::temppath() const
522 return d->temppath.absFileName();
526 TexRow & Buffer::texrow()
532 TexRow const & Buffer::texrow() const
538 TocBackend & Buffer::tocBackend() const
540 return d->toc_backend;
544 Undo & Buffer::undo()
550 void Buffer::setChild(DocIterator const & dit, Buffer * child)
552 d->children_positions[child] = dit;
556 string Buffer::latexName(bool const no_path) const
558 FileName latex_name =
559 makeLatexName(d->exportFileName());
560 return no_path ? latex_name.onlyFileName()
561 : latex_name.absFileName();
565 FileName Buffer::Impl::exportFileName() const
567 docstring const branch_suffix =
568 params.branchlist().getFileNameSuffix();
569 if (branch_suffix.empty())
572 string const name = filename.onlyFileNameWithoutExt()
573 + to_utf8(branch_suffix);
574 FileName res(filename.onlyPath().absFileName() + "/" + name);
575 res.changeExtension(filename.extension());
581 string Buffer::logName(LogType * type) const
583 string const filename = latexName(false);
585 if (filename.empty()) {
591 string const path = temppath();
593 FileName const fname(addName(temppath(),
594 onlyFileName(changeExtension(filename,
597 // FIXME: how do we know this is the name of the build log?
598 FileName const bname(
599 addName(path, onlyFileName(
600 changeExtension(filename,
601 formats.extension(bufferFormat()) + ".out"))));
603 // Also consider the master buffer log file
604 FileName masterfname = fname;
606 if (masterBuffer() != this) {
607 string const mlogfile = masterBuffer()->logName(&mtype);
608 masterfname = FileName(mlogfile);
611 // If no Latex log or Build log is newer, show Build log
612 if (bname.exists() &&
613 ((!fname.exists() && !masterfname.exists())
614 || (fname.lastModified() < bname.lastModified()
615 && masterfname.lastModified() < bname.lastModified()))) {
616 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
619 return bname.absFileName();
620 // If we have a newer master file log or only a master log, show this
621 } else if (fname != masterfname
622 && (!fname.exists() && (masterfname.exists()
623 || fname.lastModified() < masterfname.lastModified()))) {
624 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
627 return masterfname.absFileName();
629 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
632 return fname.absFileName();
636 void Buffer::setReadonly(bool const flag)
638 if (d->read_only != flag) {
645 void Buffer::setFileName(string const & newfile)
647 d->filename = makeAbsPath(newfile);
648 setReadonly(d->filename.isReadOnly());
653 int Buffer::readHeader(Lexer & lex)
655 int unknown_tokens = 0;
657 int begin_header_line = -1;
659 // Initialize parameters that may be/go lacking in header:
660 params().branchlist().clear();
661 params().preamble.erase();
662 params().options.erase();
663 params().master.erase();
664 params().float_placement.erase();
665 params().paperwidth.erase();
666 params().paperheight.erase();
667 params().leftmargin.erase();
668 params().rightmargin.erase();
669 params().topmargin.erase();
670 params().bottommargin.erase();
671 params().headheight.erase();
672 params().headsep.erase();
673 params().footskip.erase();
674 params().columnsep.erase();
675 params().fontsCJK.erase();
676 params().listings_params.clear();
677 params().clearLayoutModules();
678 params().clearRemovedModules();
679 params().clearIncludedChildren();
680 params().pdfoptions().clear();
681 params().indiceslist().clear();
682 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
683 params().isbackgroundcolor = false;
684 params().fontcolor = lyx::rgbFromHexName("#000000");
685 params().isfontcolor = false;
686 params().notefontcolor = lyx::rgbFromHexName("#cccccc");
687 params().boxbgcolor = lyx::rgbFromHexName("#ff0000");
688 params().html_latex_start.clear();
689 params().html_latex_end.clear();
690 params().html_math_img_scale = 1.0;
691 params().output_sync_macro.erase();
693 for (int i = 0; i < 4; ++i) {
694 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
695 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
698 ErrorList & errorList = d->errorLists["Parse"];
707 if (token == "\\end_header")
711 if (token == "\\begin_header") {
712 begin_header_line = line;
716 LYXERR(Debug::PARSER, "Handling document header token: `"
719 string unknown = params().readToken(lex, token, d->filename.onlyPath());
720 if (!unknown.empty()) {
721 if (unknown[0] != '\\' && token == "\\textclass") {
722 Alert::warning(_("Unknown document class"),
723 bformat(_("Using the default document class, because the "
724 "class %1$s is unknown."), from_utf8(unknown)));
727 docstring const s = bformat(_("Unknown token: "
731 errorList.push_back(ErrorItem(_("Document header error"),
736 if (begin_header_line) {
737 docstring const s = _("\\begin_header is missing");
738 errorList.push_back(ErrorItem(_("Document header error"),
742 params().makeDocumentClass();
744 return unknown_tokens;
749 // changed to be public and have one parameter
750 // Returns true if "\end_document" is not read (Asger)
751 bool Buffer::readDocument(Lexer & lex)
753 ErrorList & errorList = d->errorLists["Parse"];
756 // remove dummy empty par
757 paragraphs().clear();
759 if (!lex.checkFor("\\begin_document")) {
760 docstring const s = _("\\begin_document is missing");
761 errorList.push_back(ErrorItem(_("Document header error"),
767 if (params().outputChanges) {
768 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
769 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
770 LaTeXFeatures::isAvailable("xcolor");
772 if (!dvipost && !xcolorulem) {
773 Alert::warning(_("Changes not shown in LaTeX output"),
774 _("Changes will not be highlighted in LaTeX output, "
775 "because neither dvipost nor xcolor/ulem are installed.\n"
776 "Please install these packages or redefine "
777 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
778 } else if (!xcolorulem) {
779 Alert::warning(_("Changes not shown in LaTeX output"),
780 _("Changes will not be highlighted in LaTeX output "
781 "when using pdflatex, because xcolor and ulem are not installed.\n"
782 "Please install both packages or redefine "
783 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
787 if (!params().master.empty()) {
788 FileName const master_file = makeAbsPath(params().master,
789 onlyPath(absFileName()));
790 if (isLyXFileName(master_file.absFileName())) {
792 checkAndLoadLyXFile(master_file, true);
794 // necessary e.g. after a reload
795 // to re-register the child (bug 5873)
796 // FIXME: clean up updateMacros (here, only
797 // child registering is needed).
798 master->updateMacros();
799 // set master as master buffer, but only
800 // if we are a real child
801 if (master->isChild(this))
803 // if the master is not fully loaded
804 // it is probably just loading this
805 // child. No warning needed then.
806 else if (master->isFullyLoaded())
807 LYXERR0("The master '"
809 << "' assigned to this document ("
811 << ") does not include "
812 "this document. Ignoring the master assignment.");
817 // assure we have a default index
818 params().indiceslist().addDefault(B_("Index"));
821 bool const res = text().read(lex, errorList, d->inset);
825 updateMacroInstances();
830 bool Buffer::readString(string const & s)
832 params().compressed = false;
837 FileName const fn = FileName::tempName("Buffer_readString");
840 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
841 if (ret_plf != ReadSuccess)
844 if (file_format != LYX_FORMAT) {
845 // We need to call lyx2lyx, so write the input to a file
846 ofstream os(fn.toFilesystemEncoding().c_str());
850 return readFile(fn) == ReadSuccess;
853 if (readDocument(lex))
859 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
866 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
867 if (ret_plf != ReadSuccess)
870 if (file_format != LYX_FORMAT) {
872 ReadStatus const ret_clf = convertLyXFormat(fn, tmpFile, file_format);
873 if (ret_clf != ReadSuccess)
875 return readFile(tmpFile);
878 if (readDocument(lex)) {
879 Alert::error(_("Document format failure"),
880 bformat(_("%1$s ended unexpectedly, which means"
881 " that it is probably corrupted."),
882 from_utf8(fn.absFileName())));
883 return ReadDocumentFailure;
886 d->file_fully_loaded = true;
887 // InsetInfo needs to know if file is under VCS
888 lyxvc().file_found_hook(fn);
889 d->read_only = !fname.isWritable();
890 params().compressed = fname.isZippedFile();
896 bool Buffer::isFullyLoaded() const
898 return d->file_fully_loaded;
902 void Buffer::setFullyLoaded(bool value)
904 d->file_fully_loaded = value;
908 void Buffer::updatePreviews() const
910 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
911 thePreviews().generateBufferPreviews(*this);
915 void Buffer::removePreviews() const
917 thePreviews().removeLoader(*this);
921 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
922 FileName const & fn, int & file_format) const
924 if(!lex.checkFor("\\lyxformat")) {
925 Alert::error(_("Document format failure"),
926 bformat(_("%1$s is not a readable LyX document."),
927 from_utf8(fn.absFileName())));
928 return ReadNoLyXFormat;
934 // LyX formats 217 and earlier were written as 2.17. This corresponds
935 // to files from LyX versions < 1.1.6.3. We just remove the dot in
936 // these cases. See also: www.lyx.org/trac/changeset/1313.
937 size_t dot = tmp_format.find_first_of(".,");
938 if (dot != string::npos)
939 tmp_format.erase(dot, 1);
941 file_format = convert<int>(tmp_format);
946 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
947 FileName & tmpfile, int from_format)
949 tmpfile = FileName::tempName("Buffer_convertLyXFormat");
950 if(tmpfile.empty()) {
951 Alert::error(_("Conversion failed"),
952 bformat(_("%1$s is from a different"
953 " version of LyX, but a temporary"
954 " file for converting it could"
956 from_utf8(fn.absFileName())));
957 return LyX2LyXNoTempFile;
960 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
961 if (lyx2lyx.empty()) {
962 Alert::error(_("Conversion script not found"),
963 bformat(_("%1$s is from a different"
964 " version of LyX, but the"
965 " conversion script lyx2lyx"
966 " could not be found."),
967 from_utf8(fn.absFileName())));
968 return LyX2LyXNotFound;
972 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
973 ostringstream command;
974 command << os::python()
975 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
976 << " -t " << convert<string>(LYX_FORMAT)
977 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
978 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
979 string const command_str = command.str();
981 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
983 cmd_ret const ret = runCommand(command_str);
984 if (ret.first != 0) {
985 if (from_format < LYX_FORMAT) {
986 Alert::error(_("Conversion script failed"),
987 bformat(_("%1$s is from an older version"
988 " of LyX, but the lyx2lyx script"
989 " failed to convert it."),
990 from_utf8(fn.absFileName())));
991 return LyX2LyXOlderFormat;
993 Alert::error(_("Conversion script failed"),
994 bformat(_("%1$s is from an newer version"
995 " of LyX, but the lyx2lyx script"
996 " failed to convert it."),
997 from_utf8(fn.absFileName())));
998 return LyX2LyXNewerFormat;
1005 // Should probably be moved to somewhere else: BufferView? GuiView?
1006 bool Buffer::save() const
1008 // ask if the disk file has been externally modified (use checksum method)
1009 if (fileName().exists() && isExternallyModified(checksum_method)) {
1010 docstring const file = makeDisplayPath(absFileName(), 20);
1011 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
1012 "you want to overwrite this file?"), file);
1013 int const ret = Alert::prompt(_("Overwrite modified file?"),
1014 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1019 // We don't need autosaves in the immediate future. (Asger)
1020 resetAutosaveTimers();
1022 FileName backupName;
1023 bool madeBackup = false;
1025 // make a backup if the file already exists
1026 if (lyxrc.make_backup && fileName().exists()) {
1027 backupName = FileName(absFileName() + '~');
1028 if (!lyxrc.backupdir_path.empty()) {
1029 string const mangledName =
1030 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1031 backupName = FileName(addName(lyxrc.backupdir_path,
1034 // do not copy because of #6587
1035 if (fileName().moveTo(backupName)) {
1038 Alert::error(_("Backup failure"),
1039 bformat(_("Cannot create backup file %1$s.\n"
1040 "Please check whether the directory exists and is writeable."),
1041 from_utf8(backupName.absFileName())));
1042 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1046 if (writeFile(d->filename)) {
1050 // Saving failed, so backup is not backup
1052 backupName.moveTo(d->filename);
1058 bool Buffer::writeFile(FileName const & fname) const
1060 if (d->read_only && fname == d->filename)
1063 bool retval = false;
1065 docstring const str = bformat(_("Saving document %1$s..."),
1066 makeDisplayPath(fname.absFileName()));
1069 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1071 if (params().compressed) {
1072 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1073 retval = ofs && write(ofs);
1075 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1076 retval = ofs && write(ofs);
1080 message(str + _(" could not write file!"));
1085 // removeAutosaveFile();
1088 message(str + _(" done."));
1094 docstring Buffer::emergencyWrite()
1096 // No need to save if the buffer has not changed.
1100 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1102 docstring user_message = bformat(
1103 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1105 // We try to save three places:
1106 // 1) Same place as document. Unless it is an unnamed doc.
1108 string s = absFileName();
1111 if (writeFile(FileName(s))) {
1113 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1114 return user_message;
1116 user_message += _(" Save failed! Trying again...\n");
1120 // 2) In HOME directory.
1121 string s = addName(package().home_dir().absFileName(), absFileName());
1123 lyxerr << ' ' << s << endl;
1124 if (writeFile(FileName(s))) {
1126 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1127 return user_message;
1130 user_message += _(" Save failed! Trying yet again...\n");
1132 // 3) In "/tmp" directory.
1133 // MakeAbsPath to prepend the current
1134 // drive letter on OS/2
1135 s = addName(package().temp_dir().absFileName(), absFileName());
1137 lyxerr << ' ' << s << endl;
1138 if (writeFile(FileName(s))) {
1140 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1141 return user_message;
1144 user_message += _(" Save failed! Bummer. Document is lost.");
1147 return user_message;
1151 bool Buffer::write(ostream & ofs) const
1154 // Use the standard "C" locale for file output.
1155 ofs.imbue(locale::classic());
1158 // The top of the file should not be written by params().
1160 // write out a comment in the top of the file
1161 ofs << "#LyX " << lyx_version
1162 << " created this file. For more info see http://www.lyx.org/\n"
1163 << "\\lyxformat " << LYX_FORMAT << "\n"
1164 << "\\begin_document\n";
1166 /// For each author, set 'used' to true if there is a change
1167 /// by this author in the document; otherwise set it to 'false'.
1168 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1169 AuthorList::Authors::const_iterator a_end = params().authors().end();
1170 for (; a_it != a_end; ++a_it)
1171 a_it->setUsed(false);
1173 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1174 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1175 for ( ; it != end; ++it)
1176 it->checkAuthors(params().authors());
1178 // now write out the buffer parameters.
1179 ofs << "\\begin_header\n";
1180 params().writeFile(ofs);
1181 ofs << "\\end_header\n";
1184 ofs << "\n\\begin_body\n";
1186 ofs << "\n\\end_body\n";
1188 // Write marker that shows file is complete
1189 ofs << "\\end_document" << endl;
1191 // Shouldn't really be needed....
1194 // how to check if close went ok?
1195 // Following is an attempt... (BE 20001011)
1197 // good() returns false if any error occured, including some
1198 // formatting error.
1199 // bad() returns true if something bad happened in the buffer,
1200 // which should include file system full errors.
1205 lyxerr << "File was not closed properly." << endl;
1212 bool Buffer::makeLaTeXFile(FileName const & fname,
1213 string const & original_path,
1214 OutputParams const & runparams_in,
1215 bool output_preamble, bool output_body) const
1217 OutputParams runparams = runparams_in;
1218 if (params().useXetex)
1219 runparams.flavor = OutputParams::XETEX;
1221 string const encoding = runparams.encoding->iconvName();
1222 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1225 try { ofs.reset(encoding); }
1226 catch (iconv_codecvt_facet_exception & e) {
1227 lyxerr << "Caught iconv exception: " << e.what() << endl;
1228 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1229 "verify that the support software for your encoding (%1$s) is "
1230 "properly installed"), from_ascii(encoding)));
1233 if (!openFileWrite(ofs, fname))
1236 //TexStream ts(ofs.rdbuf(), &texrow());
1237 ErrorList & errorList = d->errorLists["Export"];
1239 bool failed_export = false;
1242 writeLaTeXSource(ofs, original_path,
1243 runparams, output_preamble, output_body);
1245 catch (EncodingException & e) {
1246 odocstringstream ods;
1247 ods.put(e.failed_char);
1249 oss << "0x" << hex << e.failed_char << dec;
1250 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1251 " (code point %2$s)"),
1252 ods.str(), from_utf8(oss.str()));
1253 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1254 "representable in the chosen encoding.\n"
1255 "Changing the document encoding to utf8 could help."),
1256 e.par_id, e.pos, e.pos + 1));
1257 failed_export = true;
1259 catch (iconv_codecvt_facet_exception & e) {
1260 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1261 _(e.what()), -1, 0, 0));
1262 failed_export = true;
1264 catch (exception const & e) {
1265 errorList.push_back(ErrorItem(_("conversion failed"),
1266 _(e.what()), -1, 0, 0));
1267 failed_export = true;
1270 lyxerr << "Caught some really weird exception..." << endl;
1276 failed_export = true;
1277 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1281 return !failed_export;
1285 void Buffer::writeLaTeXSource(odocstream & os,
1286 string const & original_path,
1287 OutputParams const & runparams_in,
1288 bool const output_preamble, bool const output_body) const
1290 // The child documents, if any, shall be already loaded at this point.
1292 OutputParams runparams = runparams_in;
1294 // Classify the unicode characters appearing in math insets
1295 Encodings::initUnicodeMath(*this);
1297 // validate the buffer.
1298 LYXERR(Debug::LATEX, " Validating buffer...");
1299 LaTeXFeatures features(*this, params(), runparams);
1301 LYXERR(Debug::LATEX, " Buffer validation done.");
1303 // The starting paragraph of the coming rows is the
1304 // first paragraph of the document. (Asger)
1305 if (output_preamble && runparams.nice) {
1306 os << "%% LyX " << lyx_version << " created this file. "
1307 "For more info, see http://www.lyx.org/.\n"
1308 "%% Do not edit unless you really know what "
1310 d->texrow.newline();
1311 d->texrow.newline();
1313 LYXERR(Debug::INFO, "lyx document header finished");
1315 // Don't move this behind the parent_buffer=0 code below,
1316 // because then the macros will not get the right "redefinition"
1317 // flag as they don't see the parent macros which are output before.
1320 // fold macros if possible, still with parent buffer as the
1321 // macros will be put in the prefix anyway.
1322 updateMacroInstances();
1324 // There are a few differences between nice LaTeX and usual files:
1325 // usual is \batchmode and has a
1326 // special input@path to allow the including of figures
1327 // with either \input or \includegraphics (what figinsets do).
1328 // input@path is set when the actual parameter
1329 // original_path is set. This is done for usual tex-file, but not
1330 // for nice-latex-file. (Matthias 250696)
1331 // Note that input@path is only needed for something the user does
1332 // in the preamble, included .tex files or ERT, files included by
1333 // LyX work without it.
1334 if (output_preamble) {
1335 if (!runparams.nice) {
1336 // code for usual, NOT nice-latex-file
1337 os << "\\batchmode\n"; // changed
1338 // from \nonstopmode
1339 d->texrow.newline();
1341 if (!original_path.empty()) {
1343 // We don't know the encoding of inputpath
1344 docstring const inputpath = from_utf8(support::latex_path(original_path));
1345 docstring uncodable_glyphs;
1346 Encoding const * const enc = runparams.encoding;
1348 for (size_t n = 0; n < inputpath.size(); ++n) {
1349 docstring const glyph =
1350 docstring(1, inputpath[n]);
1351 if (enc->latexChar(inputpath[n], true) != glyph) {
1352 LYXERR0("Uncodable character '"
1354 << "' in input path!");
1355 uncodable_glyphs += glyph;
1360 // warn user if we found uncodable glyphs.
1361 if (!uncodable_glyphs.empty()) {
1362 frontend::Alert::warning(_("Uncodable character in file path"),
1363 support::bformat(_("The path of your document\n"
1365 "contains glyphs that are unknown in the\n"
1366 "current document encoding (namely %2$s).\n"
1367 "This will likely result in incomplete output.\n\n"
1368 "Choose an appropriate document encoding (such as utf8)\n"
1369 "or change the file path name."), inputpath, uncodable_glyphs));
1371 os << "\\makeatletter\n"
1372 << "\\def\\input@path{{"
1373 << inputpath << "/}}\n"
1374 << "\\makeatother\n";
1375 d->texrow.newline();
1376 d->texrow.newline();
1377 d->texrow.newline();
1381 // get parent macros (if this buffer has a parent) which will be
1382 // written at the document begin further down.
1383 MacroSet parentMacros;
1384 listParentMacros(parentMacros, features);
1386 // Write the preamble
1387 runparams.use_babel = params().writeLaTeX(os, features,
1389 d->filename.onlyPath());
1391 runparams.use_japanese = features.isRequired("japanese");
1397 os << "\\begin{document}\n";
1398 d->texrow.newline();
1400 // output the parent macros
1401 MacroSet::iterator it = parentMacros.begin();
1402 MacroSet::iterator end = parentMacros.end();
1403 for (; it != end; ++it) {
1404 int num_lines = (*it)->write(os, true);
1405 d->texrow.newlines(num_lines);
1408 } // output_preamble
1410 d->texrow.start(paragraphs().begin()->id(), 0);
1412 LYXERR(Debug::INFO, "preamble finished, now the body.");
1414 // if we are doing a real file with body, even if this is the
1415 // child of some other buffer, let's cut the link here.
1416 // This happens for example if only a child document is printed.
1417 Buffer const * save_parent = 0;
1418 if (output_preamble) {
1419 save_parent = d->parent();
1424 latexParagraphs(*this, text(), os, d->texrow, runparams);
1426 // Restore the parenthood if needed
1427 if (output_preamble)
1428 d->setParent(save_parent);
1430 // add this just in case after all the paragraphs
1432 d->texrow.newline();
1434 if (output_preamble) {
1435 os << "\\end{document}\n";
1436 d->texrow.newline();
1437 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1439 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1441 runparams_in.encoding = runparams.encoding;
1443 // Just to be sure. (Asger)
1444 d->texrow.newline();
1446 //for (int i = 0; i<d->texrow.rows(); i++) {
1448 // if (d->texrow.getIdFromRow(i+1,id,pos) && id>0)
1449 // lyxerr << i+1 << ":" << id << ":" << getParFromID(id).paragraph().asString()<<"\n";
1452 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1453 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1457 bool Buffer::isLatex() const
1459 return params().documentClass().outputType() == LATEX;
1463 bool Buffer::isLiterate() const
1465 return params().documentClass().outputType() == LITERATE;
1469 bool Buffer::isDocBook() const
1471 return params().documentClass().outputType() == DOCBOOK;
1475 void Buffer::makeDocBookFile(FileName const & fname,
1476 OutputParams const & runparams,
1477 bool const body_only) const
1479 LYXERR(Debug::LATEX, "makeDocBookFile...");
1482 if (!openFileWrite(ofs, fname))
1485 writeDocBookSource(ofs, fname.absFileName(), runparams, body_only);
1489 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1493 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1494 OutputParams const & runparams,
1495 bool const only_body) const
1497 LaTeXFeatures features(*this, params(), runparams);
1502 DocumentClass const & tclass = params().documentClass();
1503 string const top_element = tclass.latexname();
1506 if (runparams.flavor == OutputParams::XML)
1507 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1510 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1513 if (! tclass.class_header().empty())
1514 os << from_ascii(tclass.class_header());
1515 else if (runparams.flavor == OutputParams::XML)
1516 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1517 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1519 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1521 docstring preamble = from_utf8(params().preamble);
1522 if (runparams.flavor != OutputParams::XML ) {
1523 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1524 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1525 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1526 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1529 string const name = runparams.nice
1530 ? changeExtension(absFileName(), ".sgml") : fname;
1531 preamble += features.getIncludedFiles(name);
1532 preamble += features.getLyXSGMLEntities();
1534 if (!preamble.empty()) {
1535 os << "\n [ " << preamble << " ]";
1540 string top = top_element;
1542 if (runparams.flavor == OutputParams::XML)
1543 top += params().language->code();
1545 top += params().language->code().substr(0, 2);
1548 if (!params().options.empty()) {
1550 top += params().options;
1553 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1554 << " file was created by LyX " << lyx_version
1555 << "\n See http://www.lyx.org/ for more information -->\n";
1557 params().documentClass().counters().reset();
1561 sgml::openTag(os, top);
1563 docbookParagraphs(text(), *this, os, runparams);
1564 sgml::closeTag(os, top_element);
1568 void Buffer::makeLyXHTMLFile(FileName const & fname,
1569 OutputParams const & runparams,
1570 bool const body_only) const
1572 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1575 if (!openFileWrite(ofs, fname))
1578 writeLyXHTMLSource(ofs, runparams, body_only);
1582 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1586 void Buffer::writeLyXHTMLSource(odocstream & os,
1587 OutputParams const & runparams,
1588 bool const only_body) const
1590 LaTeXFeatures features(*this, params(), runparams);
1592 updateBuffer(UpdateMaster, OutputUpdate);
1593 d->bibinfo_.makeCitationLabels(*this);
1595 updateMacroInstances();
1598 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1599 << "<!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"
1600 // FIXME Language should be set properly.
1601 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
1603 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
1604 // FIXME Presumably need to set this right
1605 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1607 docstring const & doctitle = features.htmlTitle();
1609 << (doctitle.empty() ? from_ascii("LyX Document") : doctitle)
1612 os << "\n<!-- Text Class Preamble -->\n"
1613 << features.getTClassHTMLPreamble()
1614 << "\n<!-- Premable Snippets -->\n"
1615 << from_utf8(features.getPreambleSnippets());
1617 os << "\n<!-- Layout-provided Styles -->\n";
1618 docstring const styleinfo = features.getTClassHTMLStyles();
1619 if (!styleinfo.empty()) {
1620 os << "<style type='text/css'>\n"
1624 os << "</head>\n<body>\n";
1628 params().documentClass().counters().reset();
1629 xhtmlParagraphs(text(), *this, xs, runparams);
1631 os << "</body>\n</html>\n";
1635 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1636 // Other flags: -wall -v0 -x
1637 int Buffer::runChktex()
1641 // get LaTeX-Filename
1642 FileName const path(temppath());
1643 string const name = addName(path.absFileName(), latexName());
1644 string const org_path = filePath();
1646 PathChanger p(path); // path to LaTeX file
1647 message(_("Running chktex..."));
1649 // Generate the LaTeX file if neccessary
1650 OutputParams runparams(¶ms().encoding());
1651 runparams.flavor = OutputParams::LATEX;
1652 runparams.nice = false;
1653 runparams.linelen = lyxrc.plaintext_linelen;
1654 makeLaTeXFile(FileName(name), org_path, runparams);
1657 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
1658 int const res = chktex.run(terr); // run chktex
1661 Alert::error(_("chktex failure"),
1662 _("Could not run chktex successfully."));
1663 } else if (res > 0) {
1664 ErrorList & errlist = d->errorLists["ChkTeX"];
1666 bufferErrors(terr, errlist);
1677 void Buffer::validate(LaTeXFeatures & features) const
1679 params().validate(features);
1683 for_each(paragraphs().begin(), paragraphs().end(),
1684 bind(&Paragraph::validate, _1, ref(features)));
1686 if (lyxerr.debugging(Debug::LATEX)) {
1687 features.showStruct();
1692 void Buffer::getLabelList(vector<docstring> & list) const
1694 // If this is a child document, use the master's list instead.
1696 masterBuffer()->getLabelList(list);
1701 Toc & toc = d->toc_backend.toc("label");
1702 TocIterator toc_it = toc.begin();
1703 TocIterator end = toc.end();
1704 for (; toc_it != end; ++toc_it) {
1705 if (toc_it->depth() == 0)
1706 list.push_back(toc_it->str());
1711 void Buffer::updateBibfilesCache(UpdateScope scope) const
1713 // FIXME This is probably unnecssary, given where we call this.
1714 // If this is a child document, use the parent's cache instead.
1715 if (parent() && scope != UpdateChildOnly) {
1716 masterBuffer()->updateBibfilesCache();
1720 d->bibfiles_cache_.clear();
1721 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1722 if (it->lyxCode() == BIBTEX_CODE) {
1723 InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
1724 support::FileNameList const bibfiles = inset.getBibFiles();
1725 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1728 } else if (it->lyxCode() == INCLUDE_CODE) {
1729 InsetInclude & inset = 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.screenUpdate(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.screenUpdate(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.screenUpdate(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 = getDescendents();
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() const
2387 FileName const & file = d->filename;
2388 if (file.exists()) {
2389 d->timestamp_ = file.lastModified();
2390 d->checksum_ = file.checksum();
2392 // in the case of save to a new file.
2399 void Buffer::markClean() const
2401 if (!d->lyx_clean) {
2402 d->lyx_clean = true;
2405 // if the .lyx file has been saved, we don't need an
2407 d->bak_clean = true;
2408 d->undo_.markDirty();
2412 void Buffer::setUnnamed(bool flag)
2418 bool Buffer::isUnnamed() const
2425 /// Don't check unnamed, here: isInternal() is used in
2426 /// newBuffer(), where the unnamed flag has not been set by anyone
2427 /// yet. Also, for an internal buffer, there should be no need for
2428 /// retrieving fileName() nor for checking if it is unnamed or not.
2429 bool Buffer::isInternal() const
2431 return fileName().extension() == "internal";
2435 void Buffer::markDirty()
2438 d->lyx_clean = false;
2441 d->bak_clean = false;
2443 DepClean::iterator it = d->dep_clean.begin();
2444 DepClean::const_iterator const end = d->dep_clean.end();
2446 for (; it != end; ++it)
2451 FileName Buffer::fileName() const
2457 string Buffer::absFileName() const
2459 return d->filename.absFileName();
2463 string Buffer::filePath() const
2465 return d->filename.onlyPath().absFileName() + "/";
2469 bool Buffer::isReadonly() const
2471 return d->read_only;
2475 void Buffer::setParent(Buffer const * buffer)
2477 // Avoids recursive include.
2478 d->setParent(buffer == this ? 0 : buffer);
2483 Buffer const * Buffer::parent() const
2489 ListOfBuffers Buffer::allRelatives() const
2491 ListOfBuffers lb = masterBuffer()->getDescendents();
2492 lb.push_front(const_cast<Buffer *>(this));
2497 Buffer const * Buffer::masterBuffer() const
2499 // FIXME Should be make sure we are not in some kind
2500 // of recursive include? A -> B -> A will crash this.
2501 Buffer const * const pbuf = d->parent();
2505 return pbuf->masterBuffer();
2509 bool Buffer::isChild(Buffer * child) const
2511 return d->children_positions.find(child) != d->children_positions.end();
2515 DocIterator Buffer::firstChildPosition(Buffer const * child)
2517 Impl::BufferPositionMap::iterator it;
2518 it = d->children_positions.find(child);
2519 if (it == d->children_positions.end())
2520 return DocIterator(this);
2525 bool Buffer::hasChildren() const
2527 return !d->children_positions.empty();
2531 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
2533 // loop over children
2534 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2535 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2536 for (; it != end; ++it) {
2537 Buffer * child = const_cast<Buffer *>(it->first);
2539 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
2540 if (bit != clist.end())
2542 clist.push_back(child);
2544 // there might be grandchildren
2545 child->collectChildren(clist, true);
2550 ListOfBuffers Buffer::getChildren() const
2553 collectChildren(v, false);
2558 ListOfBuffers Buffer::getDescendents() const
2561 collectChildren(v, true);
2566 template<typename M>
2567 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
2572 typename M::const_iterator it = m.lower_bound(x);
2573 if (it == m.begin())
2581 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
2582 DocIterator const & pos) const
2584 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2586 // if paragraphs have no macro context set, pos will be empty
2590 // we haven't found anything yet
2591 DocIterator bestPos = owner_->par_iterator_begin();
2592 MacroData const * bestData = 0;
2594 // find macro definitions for name
2595 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
2596 if (nameIt != macros.end()) {
2597 // find last definition in front of pos or at pos itself
2598 PositionScopeMacroMap::const_iterator it
2599 = greatest_below(nameIt->second, pos);
2600 if (it != nameIt->second.end()) {
2602 // scope ends behind pos?
2603 if (pos < it->second.first) {
2604 // Looks good, remember this. If there
2605 // is no external macro behind this,
2606 // we found the right one already.
2607 bestPos = it->first;
2608 bestData = &it->second.second;
2612 // try previous macro if there is one
2613 if (it == nameIt->second.begin())
2620 // find macros in included files
2621 PositionScopeBufferMap::const_iterator it
2622 = greatest_below(position_to_children, pos);
2623 if (it == position_to_children.end())
2624 // no children before
2628 // do we know something better (i.e. later) already?
2629 if (it->first < bestPos )
2632 // scope ends behind pos?
2633 if (pos < it->second.first) {
2634 // look for macro in external file
2636 MacroData const * data
2637 = it->second.second->getMacro(name, false);
2640 bestPos = it->first;
2646 // try previous file if there is one
2647 if (it == position_to_children.begin())
2652 // return the best macro we have found
2657 MacroData const * Buffer::getMacro(docstring const & name,
2658 DocIterator const & pos, bool global) const
2663 // query buffer macros
2664 MacroData const * data = d->getBufferMacro(name, pos);
2668 // If there is a master buffer, query that
2669 Buffer const * const pbuf = d->parent();
2671 d->macro_lock = true;
2672 MacroData const * macro = pbuf->getMacro(
2673 name, *this, false);
2674 d->macro_lock = false;
2680 data = MacroTable::globalMacros().get(name);
2689 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2691 // set scope end behind the last paragraph
2692 DocIterator scope = par_iterator_begin();
2693 scope.pit() = scope.lastpit() + 1;
2695 return getMacro(name, scope, global);
2699 MacroData const * Buffer::getMacro(docstring const & name,
2700 Buffer const & child, bool global) const
2702 // look where the child buffer is included first
2703 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2704 if (it == d->children_positions.end())
2707 // check for macros at the inclusion position
2708 return getMacro(name, it->second, global);
2712 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
2714 pit_type const lastpit = it.lastpit();
2716 // look for macros in each paragraph
2717 while (it.pit() <= lastpit) {
2718 Paragraph & par = it.paragraph();
2720 // iterate over the insets of the current paragraph
2721 InsetList const & insets = par.insetList();
2722 InsetList::const_iterator iit = insets.begin();
2723 InsetList::const_iterator end = insets.end();
2724 for (; iit != end; ++iit) {
2725 it.pos() = iit->pos;
2727 // is it a nested text inset?
2728 if (iit->inset->asInsetText()) {
2729 // Inset needs its own scope?
2730 InsetText const * itext = iit->inset->asInsetText();
2731 bool newScope = itext->isMacroScope();
2733 // scope which ends just behind the inset
2734 DocIterator insetScope = it;
2737 // collect macros in inset
2738 it.push_back(CursorSlice(*iit->inset));
2739 updateMacros(it, newScope ? insetScope : scope);
2744 if (iit->inset->asInsetTabular()) {
2745 CursorSlice slice(*iit->inset);
2746 size_t const numcells = slice.nargs();
2747 for (; slice.idx() < numcells; slice.forwardIdx()) {
2748 it.push_back(slice);
2749 updateMacros(it, scope);
2755 // is it an external file?
2756 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2757 // get buffer of external file
2758 InsetInclude const & inset =
2759 static_cast<InsetInclude const &>(*iit->inset);
2761 Buffer * child = inset.getChildBuffer();
2766 // register its position, but only when it is
2767 // included first in the buffer
2768 if (children_positions.find(child) ==
2769 children_positions.end())
2770 children_positions[child] = it;
2772 // register child with its scope
2773 position_to_children[it] = Impl::ScopeBuffer(scope, child);
2777 InsetMath * im = iit->inset->asInsetMath();
2778 if (doing_export && im) {
2779 InsetMathHull * hull = im->asHullInset();
2781 hull->recordLocation(it);
2784 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2788 MathMacroTemplate & macroTemplate =
2789 *iit->inset->asInsetMath()->asMacroTemplate();
2790 MacroContext mc(owner_, it);
2791 macroTemplate.updateToContext(mc);
2794 bool valid = macroTemplate.validMacro();
2795 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2796 // then the BufferView's cursor will be invalid in
2797 // some cases which leads to crashes.
2802 // FIXME (Abdel), I don't understandt why we pass 'it' here
2803 // instead of 'macroTemplate' defined above... is this correct?
2804 macros[macroTemplate.name()][it] =
2805 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
2815 void Buffer::updateMacros() const
2820 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2822 // start with empty table
2824 d->children_positions.clear();
2825 d->position_to_children.clear();
2827 // Iterate over buffer, starting with first paragraph
2828 // The scope must be bigger than any lookup DocIterator
2829 // later. For the global lookup, lastpit+1 is used, hence
2830 // we use lastpit+2 here.
2831 DocIterator it = par_iterator_begin();
2832 DocIterator outerScope = it;
2833 outerScope.pit() = outerScope.lastpit() + 2;
2834 d->updateMacros(it, outerScope);
2838 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
2840 InsetIterator it = inset_iterator_begin(inset());
2841 InsetIterator const end = inset_iterator_end(inset());
2842 for (; it != end; ++it) {
2843 if (it->lyxCode() == BRANCH_CODE) {
2844 InsetBranch & br = static_cast<InsetBranch &>(*it);
2845 docstring const name = br.branch();
2846 if (!from_master && !params().branchlist().find(name))
2847 result.push_back(name);
2848 else if (from_master && !masterBuffer()->params().branchlist().find(name))
2849 result.push_back(name);
2852 if (it->lyxCode() == INCLUDE_CODE) {
2853 // get buffer of external file
2854 InsetInclude const & ins =
2855 static_cast<InsetInclude const &>(*it);
2856 Buffer * child = ins.getChildBuffer();
2859 child->getUsedBranches(result, true);
2862 // remove duplicates
2867 void Buffer::updateMacroInstances() const
2869 LYXERR(Debug::MACROS, "updateMacroInstances for "
2870 << d->filename.onlyFileName());
2871 DocIterator it = doc_iterator_begin(this);
2873 DocIterator const end = doc_iterator_end(this);
2874 for (; it != end; it.forwardInset()) {
2875 // look for MathData cells in InsetMathNest insets
2876 InsetMath * minset = it.nextInset()->asInsetMath();
2880 // update macro in all cells of the InsetMathNest
2881 DocIterator::idx_type n = minset->nargs();
2882 MacroContext mc = MacroContext(this, it);
2883 for (DocIterator::idx_type i = 0; i < n; ++i) {
2884 MathData & data = minset->cell(i);
2885 data.updateMacros(0, mc);
2891 void Buffer::listMacroNames(MacroNameSet & macros) const
2896 d->macro_lock = true;
2898 // loop over macro names
2899 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2900 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2901 for (; nameIt != nameEnd; ++nameIt)
2902 macros.insert(nameIt->first);
2904 // loop over children
2905 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2906 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2907 for (; it != end; ++it)
2908 it->first->listMacroNames(macros);
2911 Buffer const * const pbuf = d->parent();
2913 pbuf->listMacroNames(macros);
2915 d->macro_lock = false;
2919 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2921 Buffer const * const pbuf = d->parent();
2926 pbuf->listMacroNames(names);
2929 MacroNameSet::iterator it = names.begin();
2930 MacroNameSet::iterator end = names.end();
2931 for (; it != end; ++it) {
2933 MacroData const * data =
2934 pbuf->getMacro(*it, *this, false);
2936 macros.insert(data);
2938 // we cannot access the original MathMacroTemplate anymore
2939 // here to calls validate method. So we do its work here manually.
2940 // FIXME: somehow make the template accessible here.
2941 if (data->optionals() > 0)
2942 features.require("xargs");
2948 Buffer::References & Buffer::references(docstring const & label)
2951 return const_cast<Buffer *>(masterBuffer())->references(label);
2953 RefCache::iterator it = d->ref_cache_.find(label);
2954 if (it != d->ref_cache_.end())
2955 return it->second.second;
2957 static InsetLabel const * dummy_il = 0;
2958 static References const dummy_refs;
2959 it = d->ref_cache_.insert(
2960 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2961 return it->second.second;
2965 Buffer::References const & Buffer::references(docstring const & label) const
2967 return const_cast<Buffer *>(this)->references(label);
2971 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2973 masterBuffer()->d->ref_cache_[label].first = il;
2977 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2979 return masterBuffer()->d->ref_cache_[label].first;
2983 void Buffer::clearReferenceCache() const
2986 d->ref_cache_.clear();
2990 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2993 //FIXME: This does not work for child documents yet.
2994 LASSERT(code == CITE_CODE, /**/);
2995 // Check if the label 'from' appears more than once
2996 vector<docstring> labels;
2998 checkBibInfoCache();
2999 BiblioInfo const & keys = masterBibInfo();
3000 BiblioInfo::const_iterator bit = keys.begin();
3001 BiblioInfo::const_iterator bend = keys.end();
3003 for (; bit != bend; ++bit)
3005 labels.push_back(bit->first);
3008 if (count(labels.begin(), labels.end(), from) > 1)
3011 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3012 if (it->lyxCode() == code) {
3013 InsetCommand * inset = it->asInsetCommand();
3016 docstring const oldValue = inset->getParam(paramName);
3017 if (oldValue == from)
3018 inset->setParam(paramName, to);
3024 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
3025 pit_type par_end, bool full_source) const
3027 OutputParams runparams(¶ms().encoding());
3028 runparams.nice = true;
3029 runparams.flavor = params().useXetex ?
3030 OutputParams::XETEX : OutputParams::LATEX;
3031 runparams.linelen = lyxrc.plaintext_linelen;
3032 // No side effect of file copying and image conversion
3033 runparams.dryrun = true;
3036 os << "% " << _("Preview source code") << "\n\n";
3038 d->texrow.newline();
3039 d->texrow.newline();
3041 writeDocBookSource(os, absFileName(), runparams, false);
3043 // latex or literate
3044 writeLaTeXSource(os, string(), runparams, true, true);
3046 runparams.par_begin = par_begin;
3047 runparams.par_end = par_end;
3048 if (par_begin + 1 == par_end) {
3050 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3054 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3055 convert<docstring>(par_begin),
3056 convert<docstring>(par_end - 1))
3063 // output paragraphs
3065 docbookParagraphs(text(), *this, os, runparams);
3067 // latex or literate
3068 latexParagraphs(*this, text(), os, texrow, runparams);
3073 ErrorList & Buffer::errorList(string const & type) const
3075 static ErrorList emptyErrorList;
3076 map<string, ErrorList>::iterator it = d->errorLists.find(type);
3077 if (it == d->errorLists.end())
3078 return emptyErrorList;
3084 void Buffer::updateTocItem(std::string const & type,
3085 DocIterator const & dit) const
3088 d->gui_->updateTocItem(type, dit);
3092 void Buffer::structureChanged() const
3095 d->gui_->structureChanged();
3099 void Buffer::errors(string const & err, bool from_master) const
3102 d->gui_->errors(err, from_master);
3106 void Buffer::message(docstring const & msg) const
3109 d->gui_->message(msg);
3113 void Buffer::setBusy(bool on) const
3116 d->gui_->setBusy(on);
3120 void Buffer::updateTitles() const
3123 d->wa_->updateTitles();
3127 void Buffer::resetAutosaveTimers() const
3130 d->gui_->resetAutosaveTimers();
3134 bool Buffer::hasGuiDelegate() const
3140 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3149 class AutoSaveBuffer : public ForkedProcess {
3152 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3153 : buffer_(buffer), fname_(fname) {}
3155 virtual shared_ptr<ForkedProcess> clone() const
3157 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3162 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3163 from_utf8(fname_.absFileName())));
3164 return run(DontWait);
3168 virtual int generateChild();
3170 Buffer const & buffer_;
3175 int AutoSaveBuffer::generateChild()
3177 #if defined(__APPLE__)
3178 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3179 * We should use something else like threads.
3181 * Since I do not know how to determine at run time what is the OS X
3182 * version, I just disable forking altogether for now (JMarc)
3184 pid_t const pid = -1;
3186 // tmp_ret will be located (usually) in /tmp
3187 // will that be a problem?
3188 // Note that this calls ForkedCalls::fork(), so it's
3189 // ok cross-platform.
3190 pid_t const pid = fork();
3191 // If you want to debug the autosave
3192 // you should set pid to -1, and comment out the fork.
3193 if (pid != 0 && pid != -1)
3197 // pid = -1 signifies that lyx was unable
3198 // to fork. But we will do the save
3200 bool failed = false;
3201 FileName const tmp_ret = FileName::tempName("lyxauto");
3202 if (!tmp_ret.empty()) {
3203 buffer_.writeFile(tmp_ret);
3204 // assume successful write of tmp_ret
3205 if (!tmp_ret.moveTo(fname_))
3211 // failed to write/rename tmp_ret so try writing direct
3212 if (!buffer_.writeFile(fname_)) {
3213 // It is dangerous to do this in the child,
3214 // but safe in the parent, so...
3215 if (pid == -1) // emit message signal.
3216 buffer_.message(_("Autosave failed!"));
3220 if (pid == 0) // we are the child so...
3229 FileName Buffer::getEmergencyFileName() const
3231 return getEmergencyFileNameFor(d->filename);
3235 FileName Buffer::getEmergencyFileNameFor(FileName const & fn) const
3237 return FileName(fn.absFileName() + ".emergency");
3241 FileName Buffer::getAutosaveFileName() const
3243 // if the document is unnamed try to save in the backup dir, else
3244 // in the default document path, and as a last try in the filePath,
3245 // which will most often be the temporary directory
3248 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3249 : lyxrc.backupdir_path;
3250 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3253 string const fname = d->filename.onlyFileName();
3254 return getAutosaveFileNameFor(makeAbsPath(fname, fpath));
3258 FileName Buffer::getAutosaveFileNameFor(FileName const & fn) const
3260 string const fname = "#" + onlyFileName(fn.absFileName()) + "#";
3261 return FileName(onlyPath(fn.absFileName()) + fname);
3265 void Buffer::removeAutosaveFile() const
3267 FileName const f = getAutosaveFileName();
3273 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3275 FileName const newauto = getAutosaveFileName();
3277 if (newauto != oldauto && oldauto.exists())
3278 if (!oldauto.moveTo(newauto))
3279 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3283 // Perfect target for a thread...
3284 void Buffer::autoSave() const
3286 if (d->bak_clean || isReadonly()) {
3287 // We don't save now, but we'll try again later
3288 resetAutosaveTimers();
3292 // emit message signal.
3293 message(_("Autosaving current document..."));
3294 AutoSaveBuffer autosave(*this, getAutosaveFileName());
3297 d->bak_clean = true;
3299 resetAutosaveTimers();
3303 string Buffer::bufferFormat() const
3305 string format = params().documentClass().outputFormat();
3306 if (format == "latex") {
3307 if (params().useXetex)
3309 if (params().encoding().package() == Encoding::japanese)
3316 string Buffer::getDefaultOutputFormat() const
3318 if (!params().defaultOutputFormat.empty()
3319 && params().defaultOutputFormat != "default")
3320 return params().defaultOutputFormat;
3321 typedef vector<Format const *> Formats;
3322 Formats formats = exportableFormats(true);
3325 || params().useXetex
3326 || params().encoding().package() == Encoding::japanese) {
3327 if (formats.empty())
3329 // return the first we find
3330 return formats.front()->name();
3332 return lyxrc.default_view_format;
3337 // helper class, to guarantee this gets reset properly
3338 class MarkAsExporting {
3340 MarkAsExporting(Buffer const * buf) : buf_(buf)
3342 LASSERT(buf_, /* */);
3343 buf_->setExportStatus(true);
3347 buf_->setExportStatus(false);
3350 Buffer const * const buf_;
3355 void Buffer::setExportStatus(bool e) const
3357 d->doing_export = e;
3361 bool Buffer::isExporting() const
3363 return d->doing_export;
3367 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3368 bool includeall, string & result_file) const
3370 MarkAsExporting exporting(this);
3371 string backend_format;
3372 OutputParams runparams(¶ms().encoding());
3373 runparams.flavor = OutputParams::LATEX;
3374 runparams.linelen = lyxrc.plaintext_linelen;
3375 runparams.includeall = includeall;
3376 vector<string> backs = backends();
3377 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3378 // Get shortest path to format
3379 Graph::EdgePath path;
3380 for (vector<string>::const_iterator it = backs.begin();
3381 it != backs.end(); ++it) {
3382 Graph::EdgePath p = theConverters().getPath(*it, format);
3383 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3384 backend_format = *it;
3389 if (!put_in_tempdir) {
3390 // Only show this alert if this is an export to a non-temporary
3391 // file (not for previewing).
3392 Alert::error(_("Couldn't export file"), bformat(
3393 _("No information for exporting the format %1$s."),
3394 formats.prettyName(format)));
3398 runparams.flavor = theConverters().getFlavor(path);
3401 backend_format = format;
3402 // FIXME: Don't hardcode format names here, but use a flag
3403 if (backend_format == "pdflatex")
3404 runparams.flavor = OutputParams::PDFLATEX;
3407 string filename = latexName(false);
3408 filename = addName(temppath(), filename);
3409 filename = changeExtension(filename,
3410 formats.extension(backend_format));
3413 updateMacroInstances();
3415 // Plain text backend
3416 if (backend_format == "text") {
3417 runparams.flavor = OutputParams::TEXT;
3418 writePlaintextFile(*this, FileName(filename), runparams);
3421 else if (backend_format == "xhtml") {
3422 runparams.flavor = OutputParams::HTML;
3423 switch (params().html_math_output) {
3424 case BufferParams::MathML:
3425 runparams.math_flavor = OutputParams::MathAsMathML;
3427 case BufferParams::HTML:
3428 runparams.math_flavor = OutputParams::MathAsHTML;
3430 case BufferParams::Images:
3431 runparams.math_flavor = OutputParams::MathAsImages;
3433 case BufferParams::LaTeX:
3434 runparams.math_flavor = OutputParams::MathAsLaTeX;
3438 makeLyXHTMLFile(FileName(filename), runparams);
3439 } else if (backend_format == "lyx")
3440 writeFile(FileName(filename));
3442 else if (isDocBook()) {
3443 runparams.nice = !put_in_tempdir;
3444 makeDocBookFile(FileName(filename), runparams);
3447 else if (backend_format == format) {
3448 runparams.nice = true;
3449 if (!makeLaTeXFile(FileName(filename), string(), runparams))
3451 } else if (!lyxrc.tex_allows_spaces
3452 && contains(filePath(), ' ')) {
3453 Alert::error(_("File name error"),
3454 _("The directory path to the document cannot contain spaces."));
3457 runparams.nice = false;
3458 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
3462 string const error_type = (format == "program")
3463 ? "Build" : bufferFormat();
3464 ErrorList & error_list = d->errorLists[error_type];
3465 string const ext = formats.extension(format);
3466 FileName const tmp_result_file(changeExtension(filename, ext));
3467 bool const success = theConverters().convert(this, FileName(filename),
3468 tmp_result_file, FileName(absFileName()), backend_format, format,
3471 // Emit the signal to show the error list or copy it back to the
3472 // cloned Buffer so that it cab be emitted afterwards.
3473 if (format != backend_format) {
3474 if (d->cloned_buffer_) {
3475 d->cloned_buffer_->d->errorLists[error_type] =
3476 d->errorLists[error_type];
3479 // also to the children, in case of master-buffer-view
3480 ListOfBuffers clist = getDescendents();
3481 ListOfBuffers::const_iterator cit = clist.begin();
3482 ListOfBuffers::const_iterator const cen = clist.end();
3483 for (; cit != cen; ++cit) {
3484 if (d->cloned_buffer_) {
3485 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
3486 (*cit)->d->errorLists[error_type];
3488 (*cit)->errors(error_type, true);
3492 if (d->cloned_buffer_) {
3493 // Enable reverse dvi or pdf to work by copying back the texrow
3494 // object to the cloned buffer.
3495 // FIXME: There is a possibility of concurrent access to texrow
3496 // here from the main GUI thread that should be securized.
3497 d->cloned_buffer_->d->texrow = d->texrow;
3498 string const error_type = bufferFormat();
3499 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
3505 if (put_in_tempdir) {
3506 result_file = tmp_result_file.absFileName();
3510 result_file = changeExtension(d->exportFileName().absFileName(), ext);
3511 // We need to copy referenced files (e. g. included graphics
3512 // if format == "dvi") to the result dir.
3513 vector<ExportedFile> const files =
3514 runparams.exportdata->externalFiles(format);
3515 string const dest = onlyPath(result_file);
3516 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
3517 : force_overwrite == ALL_FILES;
3518 CopyStatus status = use_force ? FORCE : SUCCESS;
3520 vector<ExportedFile>::const_iterator it = files.begin();
3521 vector<ExportedFile>::const_iterator const en = files.end();
3522 for (; it != en && status != CANCEL; ++it) {
3523 string const fmt = formats.getFormatFromFile(it->sourceName);
3524 status = copyFile(fmt, it->sourceName,
3525 makeAbsPath(it->exportName, dest),
3526 it->exportName, status == FORCE);
3529 if (status == CANCEL) {
3530 message(_("Document export cancelled."));
3531 } else if (tmp_result_file.exists()) {
3532 // Finally copy the main file
3533 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
3534 : force_overwrite != NO_FILES;
3535 if (status == SUCCESS && use_force)
3537 status = copyFile(format, tmp_result_file,
3538 FileName(result_file), result_file,
3540 message(bformat(_("Document exported as %1$s "
3542 formats.prettyName(format),
3543 makeDisplayPath(result_file)));
3545 // This must be a dummy converter like fax (bug 1888)
3546 message(bformat(_("Document exported as %1$s"),
3547 formats.prettyName(format)));
3554 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3555 bool includeall) const
3558 // (1) export with all included children (omit \includeonly)
3559 if (includeall && !doExport(format, put_in_tempdir, true, result_file))
3561 // (2) export with included children only
3562 return doExport(format, put_in_tempdir, false, result_file);
3566 bool Buffer::preview(string const & format, bool includeall) const
3568 MarkAsExporting exporting(this);
3570 // (1) export with all included children (omit \includeonly)
3571 if (includeall && !doExport(format, true, true))
3573 // (2) export with included children only
3574 if (!doExport(format, true, false, result_file))
3576 return formats.view(*this, FileName(result_file), format);
3580 bool Buffer::isExportable(string const & format) const
3582 vector<string> backs = backends();
3583 for (vector<string>::const_iterator it = backs.begin();
3584 it != backs.end(); ++it)
3585 if (theConverters().isReachable(*it, format))
3591 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
3593 vector<string> const backs = backends();
3594 vector<Format const *> result =
3595 theConverters().getReachable(backs[0], only_viewable, true);
3596 for (vector<string>::const_iterator it = backs.begin() + 1;
3597 it != backs.end(); ++it) {
3598 vector<Format const *> r =
3599 theConverters().getReachable(*it, only_viewable, false);
3600 result.insert(result.end(), r.begin(), r.end());
3606 vector<string> Buffer::backends() const
3609 v.push_back(bufferFormat());
3610 // FIXME: Don't hardcode format names here, but use a flag
3611 if (v.back() == "latex")
3612 v.push_back("pdflatex");
3613 v.push_back("xhtml");
3614 v.push_back("text");
3620 Buffer::ReadStatus Buffer::extractFromVC(FileName const & fn)
3622 bool const found = LyXVC::file_not_found_hook(fn);
3624 return ReadFileNotFound;
3625 if (!fn.isReadableFile())
3631 Buffer::ReadStatus Buffer::loadEmergency(FileName const & fn)
3633 FileName const emergencyFile = getEmergencyFileNameFor(fn);
3634 if (!emergencyFile.exists()
3635 || emergencyFile.lastModified() <= fn.lastModified())
3636 return ReadFileNotFound;
3638 docstring const file = makeDisplayPath(fn.absFileName(), 20);
3639 docstring const text = bformat(_("An emergency save of the document "
3640 "%1$s exists.\n\nRecover emergency save?"), file);
3642 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
3643 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
3649 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
3650 bool const success = (ret_llf == ReadSuccess);
3653 str = _("Document was successfully recovered.");
3655 str = _("Document was NOT successfully recovered.");
3656 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3657 makeDisplayPath(emergencyFile.absFileName()));
3659 int const del_emerg =
3660 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3661 _("&Remove"), _("&Keep"));
3662 if (del_emerg == 0) {
3663 emergencyFile.removeFile();
3665 Alert::warning(_("Emergency file deleted"),
3666 _("Do not forget to save your file now!"), true);
3668 return success ? ReadSuccess : ReadEmergencyFailure;
3671 int const del_emerg =
3672 Alert::prompt(_("Delete emergency file?"),
3673 _("Remove emergency file now?"), 1, 1,
3674 _("&Remove"), _("&Keep"));
3676 emergencyFile.removeFile();
3677 return ReadOriginal;
3687 Buffer::ReadStatus Buffer::loadAutosave(FileName const & fn)
3689 // Now check if autosave file is newer.
3690 FileName const autosaveFile = getAutosaveFileNameFor(fn);
3691 if (!autosaveFile.exists()
3692 || autosaveFile.lastModified() <= fn.lastModified())
3693 return ReadFileNotFound;
3695 docstring const file = makeDisplayPath(fn.absFileName(), 20);
3696 docstring const text = bformat(_("The backup of the document %1$s "
3697 "is newer.\n\nLoad the backup instead?"), file);
3698 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
3699 _("&Load backup"), _("Load &original"), _("&Cancel"));
3704 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
3705 // the file is not saved if we load the autosave file.
3706 if (ret_llf == ReadSuccess) {
3710 return ReadAutosaveFailure;
3713 // Here we delete the autosave
3714 autosaveFile.removeFile();
3715 return ReadOriginal;
3723 Buffer::ReadStatus Buffer::loadLyXFile(FileName const & fn)
3725 if (!fn.isReadableFile()) {
3726 ReadStatus const ret_rvc = extractFromVC(fn);
3727 if (ret_rvc != ReadSuccess)
3731 ReadStatus const ret_re = loadEmergency(fn);
3732 if (ret_re == ReadSuccess || ret_re == ReadCancel)
3735 ReadStatus const ret_ra = loadAutosave(fn);
3736 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
3739 return loadThisLyXFile(fn);
3743 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
3745 return readFile(fn);
3749 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3751 TeXErrors::Errors::const_iterator cit = terr.begin();
3752 TeXErrors::Errors::const_iterator end = terr.end();
3754 for (; cit != end; ++cit) {
3757 int errorRow = cit->error_in_line;
3758 bool found = d->texrow.getIdFromRow(errorRow, id_start,
3764 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
3765 } while (found && id_start == id_end && pos_start == pos_end);
3767 errorList.push_back(ErrorItem(cit->error_desc,
3768 cit->error_text, id_start, pos_start, pos_end));
3773 void Buffer::setBuffersForInsets() const
3775 inset().setBuffer(const_cast<Buffer &>(*this));
3779 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
3781 // Use the master text class also for child documents
3782 Buffer const * const master = masterBuffer();
3783 DocumentClass const & textclass = master->params().documentClass();
3785 // do this only if we are the top-level Buffer
3787 checkBibInfoCache();
3789 // keep the buffers to be children in this set. If the call from the
3790 // master comes back we can see which of them were actually seen (i.e.
3791 // via an InsetInclude). The remaining ones in the set need still be updated.
3792 static std::set<Buffer const *> bufToUpdate;
3793 if (scope == UpdateMaster) {
3794 // If this is a child document start with the master
3795 if (master != this) {
3796 bufToUpdate.insert(this);
3797 master->updateBuffer(UpdateMaster, utype);
3798 // Do this here in case the master has no gui associated with it. Then,
3799 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3800 if (!master->d->gui_)
3803 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3804 if (bufToUpdate.find(this) == bufToUpdate.end())
3808 // start over the counters in the master
3809 textclass.counters().reset();
3812 // update will be done below for this buffer
3813 bufToUpdate.erase(this);
3815 // update all caches
3816 clearReferenceCache();
3819 Buffer & cbuf = const_cast<Buffer &>(*this);
3821 LASSERT(!text().paragraphs().empty(), /**/);
3824 ParIterator parit = cbuf.par_iterator_begin();
3825 updateBuffer(parit, utype);
3828 // TocBackend update will be done later.
3831 cbuf.tocBackend().update();
3832 if (scope == UpdateMaster)
3833 cbuf.structureChanged();
3837 static depth_type getDepth(DocIterator const & it)
3839 depth_type depth = 0;
3840 for (size_t i = 0 ; i < it.depth() ; ++i)
3841 if (!it[i].inset().inMathed())
3842 depth += it[i].paragraph().getDepth() + 1;
3843 // remove 1 since the outer inset does not count
3847 static depth_type getItemDepth(ParIterator const & it)
3849 Paragraph const & par = *it;
3850 LabelType const labeltype = par.layout().labeltype;
3852 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3855 // this will hold the lowest depth encountered up to now.
3856 depth_type min_depth = getDepth(it);
3857 ParIterator prev_it = it;
3860 --prev_it.top().pit();
3862 // start of nested inset: go to outer par
3864 if (prev_it.empty()) {
3865 // start of document: nothing to do
3870 // We search for the first paragraph with same label
3871 // that is not more deeply nested.
3872 Paragraph & prev_par = *prev_it;
3873 depth_type const prev_depth = getDepth(prev_it);
3874 if (labeltype == prev_par.layout().labeltype) {
3875 if (prev_depth < min_depth)
3876 return prev_par.itemdepth + 1;
3877 if (prev_depth == min_depth)
3878 return prev_par.itemdepth;
3880 min_depth = min(min_depth, prev_depth);
3881 // small optimization: if we are at depth 0, we won't
3882 // find anything else
3883 if (prev_depth == 0)
3889 static bool needEnumCounterReset(ParIterator const & it)
3891 Paragraph const & par = *it;
3892 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3893 depth_type const cur_depth = par.getDepth();
3894 ParIterator prev_it = it;
3895 while (prev_it.pit()) {
3896 --prev_it.top().pit();
3897 Paragraph const & prev_par = *prev_it;
3898 if (prev_par.getDepth() <= cur_depth)
3899 return prev_par.layout().labeltype != LABEL_ENUMERATE;
3901 // start of nested inset: reset
3906 // set the label of a paragraph. This includes the counters.
3907 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
3909 BufferParams const & bp = owner_->masterBuffer()->params();
3910 DocumentClass const & textclass = bp.documentClass();
3911 Paragraph & par = it.paragraph();
3912 Layout const & layout = par.layout();
3913 Counters & counters = textclass.counters();
3915 if (par.params().startOfAppendix()) {
3916 // FIXME: only the counter corresponding to toplevel
3917 // sectioning should be reset
3919 counters.appendix(true);
3921 par.params().appendix(counters.appendix());
3923 // Compute the item depth of the paragraph
3924 par.itemdepth = getItemDepth(it);
3926 if (layout.margintype == MARGIN_MANUAL
3927 || layout.latextype == LATEX_BIB_ENVIRONMENT) {
3928 if (par.params().labelWidthString().empty())
3929 par.params().labelWidthString(par.expandLabel(layout, bp));
3931 par.params().labelWidthString(docstring());
3934 switch(layout.labeltype) {
3936 if (layout.toclevel <= bp.secnumdepth
3937 && (layout.latextype != LATEX_ENVIRONMENT
3938 || it.text()->isFirstInSequence(it.pit()))) {
3939 counters.step(layout.counter, utype);
3940 par.params().labelString(
3941 par.expandLabel(layout, bp));
3943 par.params().labelString(docstring());
3946 case LABEL_ITEMIZE: {
3947 // At some point of time we should do something more
3948 // clever here, like:
3949 // par.params().labelString(
3950 // bp.user_defined_bullet(par.itemdepth).getText());
3951 // for now, use a simple hardcoded label
3952 docstring itemlabel;
3953 switch (par.itemdepth) {
3955 itemlabel = char_type(0x2022);
3958 itemlabel = char_type(0x2013);
3961 itemlabel = char_type(0x2217);
3964 itemlabel = char_type(0x2219); // or 0x00b7
3967 par.params().labelString(itemlabel);
3971 case LABEL_ENUMERATE: {
3972 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
3974 switch (par.itemdepth) {
3983 enumcounter += "iv";
3986 // not a valid enumdepth...
3990 // Maybe we have to reset the enumeration counter.
3991 if (needEnumCounterReset(it))
3992 counters.reset(enumcounter);
3993 counters.step(enumcounter, utype);
3995 string const & lang = par.getParLanguage(bp)->code();
3996 par.params().labelString(counters.theCounter(enumcounter, lang));
4001 case LABEL_SENSITIVE: {
4002 string const & type = counters.current_float();
4003 docstring full_label;
4005 full_label = owner_->B_("Senseless!!! ");
4007 docstring name = owner_->B_(textclass.floats().getType(type).name());
4008 if (counters.hasCounter(from_utf8(type))) {
4009 string const & lang = par.getParLanguage(bp)->code();
4010 counters.step(from_utf8(type), utype);
4011 full_label = bformat(from_ascii("%1$s %2$s:"),
4013 counters.theCounter(from_utf8(type), lang));
4015 full_label = bformat(from_ascii("%1$s #:"), name);
4017 par.params().labelString(full_label);
4021 case LABEL_NO_LABEL:
4022 par.params().labelString(docstring());
4026 case LABEL_TOP_ENVIRONMENT:
4027 case LABEL_CENTERED_TOP_ENVIRONMENT:
4030 par.params().labelString(par.expandLabel(layout, bp));
4036 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4038 LASSERT(parit.pit() == 0, /**/);
4040 // Set the position of the text in the buffer to be able
4041 // to resolve macros in it.
4042 parit.text()->setMacrocontextPosition(parit);
4044 depth_type maxdepth = 0;
4045 pit_type const lastpit = parit.lastpit();
4046 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4047 // reduce depth if necessary
4048 parit->params().depth(min(parit->params().depth(), maxdepth));
4049 maxdepth = parit->getMaxDepthAfter();
4051 if (utype == OutputUpdate) {
4052 // track the active counters
4053 // we have to do this for the master buffer, since the local
4054 // buffer isn't tracking anything.
4055 masterBuffer()->params().documentClass().counters().
4056 setActiveLayout(parit->layout());
4059 // set the counter for this paragraph
4060 d->setLabel(parit, utype);
4063 InsetList::const_iterator iit = parit->insetList().begin();
4064 InsetList::const_iterator end = parit->insetList().end();
4065 for (; iit != end; ++iit) {
4066 parit.pos() = iit->pos;
4067 iit->inset->updateBuffer(parit, utype);
4073 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4074 WordLangTuple & word_lang, docstring_list & suggestions) const
4078 suggestions.clear();
4079 word_lang = WordLangTuple();
4080 // OK, we start from here.
4081 DocIterator const end = doc_iterator_end(this);
4082 for (; from != end; from.forwardPos()) {
4083 // We are only interested in text so remove the math CursorSlice.
4084 while (from.inMathed()) {
4088 // If from is at the end of the document (which is possible
4089 // when leaving the mathed) LyX will crash later.
4093 from.paragraph().spellCheck();
4094 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4095 if (SpellChecker::misspelled(res)) {
4100 // Do not increase progress when from == to, otherwise the word
4101 // count will be wrong.
4111 Buffer::ReadStatus Buffer::reload()
4115 removeAutosaveFile();
4116 // e.g., read-only status could have changed due to version control
4117 d->filename.refresh();
4118 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4120 ReadStatus const status = loadLyXFile(d->filename);
4121 if (status == ReadSuccess) {
4126 message(bformat(_("Document %1$s reloaded."), disp_fn));
4128 message(bformat(_("Could not reload document %1$s."), disp_fn));
4138 // FIXME We could do better here, but it is complicated. What would be
4139 // nice is to offer either (a) to save the child buffer to an appropriate
4140 // location, so that it would "move with the master", or else (b) to update
4141 // the InsetInclude so that it pointed to the same file. But (a) is a bit
4142 // complicated, because the code for this lives in GuiView.
4143 void Buffer::checkChildBuffers()
4145 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4146 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4147 for (; it != en; ++it) {
4148 DocIterator dit = it->second;
4149 Buffer * cbuf = const_cast<Buffer *>(it->first);
4150 if (!cbuf || !theBufferList().isLoaded(cbuf))
4152 Inset * inset = dit.nextInset();
4153 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4154 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4155 docstring const & incfile = inset_inc->getParam("filename");
4156 string oldloc = cbuf->absFileName();
4157 string newloc = makeAbsPath(to_utf8(incfile),
4158 onlyPath(absFileName())).absFileName();
4159 if (oldloc == newloc)
4161 // the location of the child file is incorrect.
4162 Alert::warning(_("Included File Invalid"),
4163 bformat(_("Saving this document to a new location has made the file:\n"
4165 "inaccessible. You will need to update the included filename."),
4166 from_utf8(oldloc)));
4168 inset_inc->setChildBuffer(0);
4170 // invalidate cache of children
4171 d->children_positions.clear();
4172 d->position_to_children.clear();