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/InsetBibtex.h"
70 #include "insets/InsetBranch.h"
71 #include "insets/InsetInclude.h"
72 #include "insets/InsetTabular.h"
73 #include "insets/InsetText.h"
75 #include "mathed/InsetMathHull.h"
76 #include "mathed/MacroTable.h"
77 #include "mathed/MathMacroTemplate.h"
78 #include "mathed/MathSupport.h"
80 #include "frontends/alert.h"
81 #include "frontends/Delegates.h"
82 #include "frontends/WorkAreaManager.h"
84 #include "graphics/Previews.h"
86 #include "support/lassert.h"
87 #include "support/convert.h"
88 #include "support/debug.h"
89 #include "support/docstring_list.h"
90 #include "support/ExceptionMessage.h"
91 #include "support/FileName.h"
92 #include "support/FileNameList.h"
93 #include "support/filetools.h"
94 #include "support/ForkedCalls.h"
95 #include "support/gettext.h"
96 #include "support/gzstream.h"
97 #include "support/lstrings.h"
98 #include "support/lyxalgo.h"
99 #include "support/os.h"
100 #include "support/Package.h"
101 #include "support/Path.h"
102 #include "support/Systemcall.h"
103 #include "support/textutils.h"
104 #include "support/types.h"
106 #include "support/bind.h"
107 #include "support/shared_ptr.h"
119 using namespace lyx::support;
123 namespace Alert = frontend::Alert;
124 namespace os = support::os;
128 // Do not remove the comment below, so we get merge conflict in
129 // independent branches. Instead add your own.
130 int const LYX_FORMAT = 410; // rgh: dummy format for list->labeling
132 typedef map<string, bool> DepClean;
133 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
135 void showPrintError(string const & name)
137 docstring str = bformat(_("Could not print the document %1$s.\n"
138 "Check that your printer is set up correctly."),
139 makeDisplayPath(name, 50));
140 Alert::error(_("Print document failed"), str);
149 Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
160 /// search for macro in local (buffer) table or in children
161 MacroData const * getBufferMacro(docstring const & name,
162 DocIterator const & pos) const;
164 /// Update macro table starting with position of it \param it in some
166 void updateMacros(DocIterator & it, DocIterator & scope);
168 void setLabel(ParIterator & it, UpdateType utype) const;
170 /** If we have branches that use the file suffix
171 feature, return the file name with suffix appended.
173 support::FileName exportFileName() const;
180 mutable TexRow texrow;
182 /// need to regenerate .tex?
186 mutable bool lyx_clean;
188 /// is autosave needed?
189 mutable bool bak_clean;
191 /// is this an unnamed file (New...)?
197 /// name of the file the buffer is associated with.
200 /** Set to true only when the file is fully loaded.
201 * Used to prevent the premature generation of previews
202 * and by the citation inset.
204 bool file_fully_loaded;
207 mutable TocBackend toc_backend;
210 typedef pair<DocIterator, MacroData> ScopeMacro;
211 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
212 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
213 /// map from the macro name to the position map,
214 /// which maps the macro definition position to the scope and the MacroData.
215 NamePositionScopeMacroMap macros;
216 /// This seem to change the way Buffer::getMacro() works
217 mutable bool macro_lock;
219 /// positions of child buffers in the buffer
220 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
221 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
222 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
223 /// position of children buffers in this buffer
224 BufferPositionMap children_positions;
225 /// map from children inclusion positions to their scope and their buffer
226 PositionScopeBufferMap position_to_children;
228 /// Container for all sort of Buffer dependant errors.
229 map<string, ErrorList> errorLists;
231 /// timestamp and checksum used to test if the file has been externally
232 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
234 unsigned long checksum_;
237 frontend::WorkAreaManager * wa_;
239 frontend::GuiBufferDelegate * gui_;
244 /// A cache for the bibfiles (including bibfiles of loaded child
245 /// documents), needed for appropriate update of natbib labels.
246 mutable support::FileNameList bibfiles_cache_;
248 // FIXME The caching mechanism could be improved. At present, we have a
249 // cache for each Buffer, that caches all the bibliography info for that
250 // Buffer. A more efficient solution would be to have a global cache per
251 // file, and then to construct the Buffer's bibinfo from that.
252 /// A cache for bibliography info
253 mutable BiblioInfo bibinfo_;
254 /// whether the bibinfo cache is valid
255 mutable bool bibinfo_cache_valid_;
256 /// whether the bibfile cache is valid
257 mutable bool bibfile_cache_valid_;
258 /// Cache of timestamps of .bib files
259 map<FileName, time_t> bibfile_status_;
261 mutable RefCache ref_cache_;
263 /// our Text that should be wrapped in an InsetText
266 /// This is here to force the test to be done whenever parent_buffer
268 Buffer const * parent() const {
269 // if parent_buffer is not loaded, then it has been unloaded,
270 // which means that parent_buffer is an invalid pointer. So we
271 // set it to null in that case.
272 // however, the BufferList doesn't know about cloned buffers, so
273 // they will always be regarded as unloaded. in that case, we hope
275 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
277 return parent_buffer;
281 void setParent(Buffer const * pb) {
282 if (parent_buffer == pb)
285 if (!cloned_buffer_ && parent_buffer && pb)
286 LYXERR0("Warning: a buffer should not have two parents!");
288 if (!cloned_buffer_ && parent_buffer) {
289 parent_buffer->invalidateBibfileCache();
290 parent_buffer->invalidateBibinfoCache();
294 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
295 /// This one is useful for preview detached in a thread.
296 Buffer const * cloned_buffer_;
297 /// are we in the process of exporting this buffer?
298 mutable bool doing_export;
301 /// So we can force access via the accessors.
302 mutable Buffer const * parent_buffer;
307 /// Creates the per buffer temporary directory
308 static FileName createBufferTmpDir()
311 // We are in our own directory. Why bother to mangle name?
312 // In fact I wrote this code to circumvent a problematic behaviour
313 // (bug?) of EMX mkstemp().
314 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
315 convert<string>(count++));
317 if (!tmpfl.createDirectory(0777)) {
318 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
319 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
320 from_utf8(tmpfl.absFileName())));
326 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
327 Buffer const * cloned_buffer)
328 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
329 read_only(readonly_), filename(file), file_fully_loaded(false),
330 toc_backend(owner), macro_lock(false), timestamp_(0),
331 checksum_(0), wa_(0), gui_(0), undo_(*owner), bibinfo_cache_valid_(false),
332 bibfile_cache_valid_(false), cloned_buffer_(cloned_buffer),
333 doing_export(false), parent_buffer(0)
335 if (!cloned_buffer_) {
336 temppath = createBufferTmpDir();
337 lyxvc.setBuffer(owner_);
339 wa_ = new frontend::WorkAreaManager;
342 temppath = cloned_buffer_->d->temppath;
343 file_fully_loaded = true;
344 params = cloned_buffer_->d->params;
345 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
346 bibinfo_ = cloned_buffer_->d->bibinfo_;
347 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
348 bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
349 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
353 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
354 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
356 LYXERR(Debug::INFO, "Buffer::Buffer()");
358 d->inset = new InsetText(*cloned_buffer->d->inset);
359 d->inset->setBuffer(*this);
360 // FIXME: optimize this loop somewhat, maybe by creating a new
361 // general recursive Inset::setId().
362 DocIterator it = doc_iterator_begin(this);
363 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
364 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
365 it.paragraph().setId(cloned_it.paragraph().id());
367 d->inset = new InsetText(this);
368 d->inset->setAutoBreakRows(true);
369 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
375 LYXERR(Debug::INFO, "Buffer::~Buffer()");
376 // here the buffer should take care that it is
377 // saved properly, before it goes into the void.
379 // GuiView already destroyed
383 // No need to do additional cleanups for internal buffer.
388 // loop over children
389 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
390 Impl::BufferPositionMap::iterator end = d->children_positions.end();
391 for (; it != end; ++it) {
392 Buffer * child = const_cast<Buffer *>(it->first);
393 if (d->cloned_buffer_)
395 // The child buffer might have been closed already.
396 else if (theBufferList().isLoaded(child))
397 theBufferList().releaseChild(this, child);
401 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
402 msg += emergencyWrite();
403 Alert::warning(_("Attempting to close changed document!"), msg);
406 // clear references to children in macro tables
407 d->children_positions.clear();
408 d->position_to_children.clear();
410 if (!d->cloned_buffer_ && !d->temppath.destroyDirectory()) {
411 Alert::warning(_("Could not remove temporary directory"),
412 bformat(_("Could not remove the temporary directory %1$s"),
413 from_utf8(d->temppath.absFileName())));
423 Buffer * Buffer::clone() const
425 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
426 buffer_clone->d->macro_lock = true;
427 buffer_clone->d->children_positions.clear();
428 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
429 // math macro caches need to be rethought and simplified.
430 // I am not sure wether we should handle Buffer cloning here or in BufferList.
431 // Right now BufferList knows nothing about buffer clones.
432 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
433 Impl::BufferPositionMap::iterator end = d->children_positions.end();
434 for (; it != end; ++it) {
435 DocIterator dit = it->second.clone(buffer_clone);
436 dit.setBuffer(buffer_clone);
437 Buffer * child = const_cast<Buffer *>(it->first);
438 Buffer * child_clone = child->clone();
439 Inset * inset = dit.nextInset();
440 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
441 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
442 inset_inc->setChildBuffer(child_clone);
443 child_clone->d->setParent(buffer_clone);
444 buffer_clone->setChild(dit, child_clone);
446 buffer_clone->d->macro_lock = false;
451 bool Buffer::isClone() const
453 return d->cloned_buffer_;
457 void Buffer::changed(bool update_metrics) const
460 d->wa_->redrawAll(update_metrics);
464 frontend::WorkAreaManager & Buffer::workAreaManager() const
466 LASSERT(d->wa_, /**/);
471 Text & Buffer::text() const
473 return d->inset->text();
477 Inset & Buffer::inset() const
483 BufferParams & Buffer::params()
489 BufferParams const & Buffer::params() const
495 ParagraphList & Buffer::paragraphs()
497 return text().paragraphs();
501 ParagraphList const & Buffer::paragraphs() const
503 return text().paragraphs();
507 LyXVC & Buffer::lyxvc()
513 LyXVC const & Buffer::lyxvc() const
519 string const Buffer::temppath() const
521 return d->temppath.absFileName();
525 TexRow & Buffer::texrow()
531 TexRow const & Buffer::texrow() const
537 TocBackend & Buffer::tocBackend() const
539 return d->toc_backend;
543 Undo & Buffer::undo()
549 void Buffer::setChild(DocIterator const & dit, Buffer * child)
551 d->children_positions[child] = dit;
555 string Buffer::latexName(bool const no_path) const
557 FileName latex_name =
558 makeLatexName(d->exportFileName());
559 return no_path ? latex_name.onlyFileName()
560 : latex_name.absFileName();
564 FileName Buffer::Impl::exportFileName() const
566 docstring const branch_suffix =
567 params.branchlist().getFileNameSuffix();
568 if (branch_suffix.empty())
571 string const name = filename.onlyFileNameWithoutExt()
572 + to_utf8(branch_suffix);
573 FileName res(filename.onlyPath().absFileName() + "/" + name);
574 res.changeExtension(filename.extension());
580 string Buffer::logName(LogType * type) const
582 string const filename = latexName(false);
584 if (filename.empty()) {
590 string const path = temppath();
592 FileName const fname(addName(temppath(),
593 onlyFileName(changeExtension(filename,
596 // FIXME: how do we know this is the name of the build log?
597 FileName const bname(
598 addName(path, onlyFileName(
599 changeExtension(filename,
600 formats.extension(bufferFormat()) + ".out"))));
602 // Also consider the master buffer log file
603 FileName masterfname = fname;
605 if (masterBuffer() != this) {
606 string const mlogfile = masterBuffer()->logName(&mtype);
607 masterfname = FileName(mlogfile);
610 // If no Latex log or Build log is newer, show Build log
611 if (bname.exists() &&
612 ((!fname.exists() && !masterfname.exists())
613 || (fname.lastModified() < bname.lastModified()
614 && masterfname.lastModified() < bname.lastModified()))) {
615 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
618 return bname.absFileName();
619 // If we have a newer master file log or only a master log, show this
620 } else if (fname != masterfname
621 && (!fname.exists() && (masterfname.exists()
622 || fname.lastModified() < masterfname.lastModified()))) {
623 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
626 return masterfname.absFileName();
628 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
631 return fname.absFileName();
635 void Buffer::setReadonly(bool const flag)
637 if (d->read_only != flag) {
644 void Buffer::setFileName(FileName const & fname)
647 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().fonts_cjk.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 // FIXME: InsetInfo needs to know whether the file is under VCS
879 // during the parse process, so this has to be done before.
880 lyxvc().file_found_hook(d->filename);
882 if (readDocument(lex)) {
883 Alert::error(_("Document format failure"),
884 bformat(_("%1$s ended unexpectedly, which means"
885 " that it is probably corrupted."),
886 from_utf8(fn.absFileName())));
887 return ReadDocumentFailure;
890 d->file_fully_loaded = true;
891 d->read_only = !d->filename.isWritable();
892 params().compressed = d->filename.isZippedFile();
898 bool Buffer::isFullyLoaded() const
900 return d->file_fully_loaded;
904 void Buffer::setFullyLoaded(bool value)
906 d->file_fully_loaded = value;
910 void Buffer::updatePreviews() const
912 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
913 thePreviews().generateBufferPreviews(*this);
917 void Buffer::removePreviews() const
919 thePreviews().removeLoader(*this);
923 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
924 FileName const & fn, int & file_format) const
926 if(!lex.checkFor("\\lyxformat")) {
927 Alert::error(_("Document format failure"),
928 bformat(_("%1$s is not a readable LyX document."),
929 from_utf8(fn.absFileName())));
930 return ReadNoLyXFormat;
936 // LyX formats 217 and earlier were written as 2.17. This corresponds
937 // to files from LyX versions < 1.1.6.3. We just remove the dot in
938 // these cases. See also: www.lyx.org/trac/changeset/1313.
939 size_t dot = tmp_format.find_first_of(".,");
940 if (dot != string::npos)
941 tmp_format.erase(dot, 1);
943 file_format = convert<int>(tmp_format);
948 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
949 FileName & tmpfile, int from_format)
951 tmpfile = FileName::tempName("Buffer_convertLyXFormat");
952 if(tmpfile.empty()) {
953 Alert::error(_("Conversion failed"),
954 bformat(_("%1$s is from a different"
955 " version of LyX, but a temporary"
956 " file for converting it could"
958 from_utf8(fn.absFileName())));
959 return LyX2LyXNoTempFile;
962 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
963 if (lyx2lyx.empty()) {
964 Alert::error(_("Conversion script not found"),
965 bformat(_("%1$s is from a different"
966 " version of LyX, but the"
967 " conversion script lyx2lyx"
968 " could not be found."),
969 from_utf8(fn.absFileName())));
970 return LyX2LyXNotFound;
974 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
975 ostringstream command;
976 command << os::python()
977 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
978 << " -t " << convert<string>(LYX_FORMAT)
979 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
980 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
981 string const command_str = command.str();
983 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
985 cmd_ret const ret = runCommand(command_str);
986 if (ret.first != 0) {
987 if (from_format < LYX_FORMAT) {
988 Alert::error(_("Conversion script failed"),
989 bformat(_("%1$s is from an older version"
990 " of LyX and the lyx2lyx script"
991 " failed to convert it."),
992 from_utf8(fn.absFileName())));
993 return LyX2LyXOlderFormat;
995 Alert::error(_("Conversion script failed"),
996 bformat(_("%1$s is from a newer version"
997 " of LyX and the lyx2lyx script"
998 " failed to convert it."),
999 from_utf8(fn.absFileName())));
1000 return LyX2LyXNewerFormat;
1007 // Should probably be moved to somewhere else: BufferView? GuiView?
1008 bool Buffer::save() const
1010 docstring const file = makeDisplayPath(absFileName(), 20);
1011 d->filename.refresh();
1013 // check the read-only status before moving the file as a backup
1014 if (d->filename.exists()) {
1015 bool const read_only = !d->filename.isWritable();
1017 Alert::warning(_("File is read-only"),
1018 bformat(_("The file %1$s cannot be written because it "
1019 "is marked as read-only."), file));
1024 // ask if the disk file has been externally modified (use checksum method)
1025 if (fileName().exists() && isExternallyModified(checksum_method)) {
1027 bformat(_("Document %1$s has been externally modified. "
1028 "Are you sure you want to overwrite this file?"), file);
1029 int const ret = Alert::prompt(_("Overwrite modified file?"),
1030 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1035 // We don't need autosaves in the immediate future. (Asger)
1036 resetAutosaveTimers();
1038 FileName backupName;
1039 bool madeBackup = false;
1041 // make a backup if the file already exists
1042 if (lyxrc.make_backup && fileName().exists()) {
1043 backupName = FileName(absFileName() + '~');
1044 if (!lyxrc.backupdir_path.empty()) {
1045 string const mangledName =
1046 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1047 backupName = FileName(addName(lyxrc.backupdir_path,
1050 // do not copy because of #6587
1051 if (fileName().moveTo(backupName)) {
1054 Alert::error(_("Backup failure"),
1055 bformat(_("Cannot create backup file %1$s.\n"
1056 "Please check whether the directory exists and is writeable."),
1057 from_utf8(backupName.absFileName())));
1058 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1062 if (writeFile(d->filename)) {
1066 // Saving failed, so backup is not backup
1068 backupName.moveTo(d->filename);
1074 bool Buffer::writeFile(FileName const & fname) const
1076 if (d->read_only && fname == d->filename)
1079 bool retval = false;
1081 docstring const str = bformat(_("Saving document %1$s..."),
1082 makeDisplayPath(fname.absFileName()));
1085 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1087 if (params().compressed) {
1088 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1089 retval = ofs && write(ofs);
1091 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1092 retval = ofs && write(ofs);
1096 message(str + _(" could not write file!"));
1101 // removeAutosaveFile();
1104 message(str + _(" done."));
1110 docstring Buffer::emergencyWrite()
1112 // No need to save if the buffer has not changed.
1116 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1118 docstring user_message = bformat(
1119 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1121 // We try to save three places:
1122 // 1) Same place as document. Unless it is an unnamed doc.
1124 string s = absFileName();
1127 if (writeFile(FileName(s))) {
1129 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1130 return user_message;
1132 user_message += " " + _("Save failed! Trying again...\n");
1136 // 2) In HOME directory.
1137 string s = addName(package().home_dir().absFileName(), absFileName());
1139 lyxerr << ' ' << s << endl;
1140 if (writeFile(FileName(s))) {
1142 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1143 return user_message;
1146 user_message += " " + _("Save failed! Trying yet again...\n");
1148 // 3) In "/tmp" directory.
1149 // MakeAbsPath to prepend the current
1150 // drive letter on OS/2
1151 s = addName(package().temp_dir().absFileName(), absFileName());
1153 lyxerr << ' ' << s << endl;
1154 if (writeFile(FileName(s))) {
1156 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1157 return user_message;
1160 user_message += " " + _("Save failed! Bummer. Document is lost.");
1163 return user_message;
1167 bool Buffer::write(ostream & ofs) const
1170 // Use the standard "C" locale for file output.
1171 ofs.imbue(locale::classic());
1174 // The top of the file should not be written by params().
1176 // write out a comment in the top of the file
1177 ofs << "#LyX " << lyx_version
1178 << " created this file. For more info see http://www.lyx.org/\n"
1179 << "\\lyxformat " << LYX_FORMAT << "\n"
1180 << "\\begin_document\n";
1182 /// For each author, set 'used' to true if there is a change
1183 /// by this author in the document; otherwise set it to 'false'.
1184 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1185 AuthorList::Authors::const_iterator a_end = params().authors().end();
1186 for (; a_it != a_end; ++a_it)
1187 a_it->setUsed(false);
1189 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1190 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1191 for ( ; it != end; ++it)
1192 it->checkAuthors(params().authors());
1194 // now write out the buffer parameters.
1195 ofs << "\\begin_header\n";
1196 params().writeFile(ofs);
1197 ofs << "\\end_header\n";
1200 ofs << "\n\\begin_body\n";
1202 ofs << "\n\\end_body\n";
1204 // Write marker that shows file is complete
1205 ofs << "\\end_document" << endl;
1207 // Shouldn't really be needed....
1210 // how to check if close went ok?
1211 // Following is an attempt... (BE 20001011)
1213 // good() returns false if any error occured, including some
1214 // formatting error.
1215 // bad() returns true if something bad happened in the buffer,
1216 // which should include file system full errors.
1221 lyxerr << "File was not closed properly." << endl;
1228 bool Buffer::makeLaTeXFile(FileName const & fname,
1229 string const & original_path,
1230 OutputParams const & runparams_in,
1231 bool output_preamble, bool output_body) const
1233 OutputParams runparams = runparams_in;
1235 // This is necessary for LuaTeX/XeTeX with tex fonts.
1236 // See FIXME in BufferParams::encoding()
1237 if (runparams.isFullUnicode())
1238 runparams.encoding = encodings.fromLyXName("utf8-plain");
1240 string const encoding = runparams.encoding->iconvName();
1241 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1244 try { ofs.reset(encoding); }
1245 catch (iconv_codecvt_facet_exception & e) {
1246 lyxerr << "Caught iconv exception: " << e.what() << endl;
1247 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1248 "verify that the support software for your encoding (%1$s) is "
1249 "properly installed"), from_ascii(encoding)));
1252 if (!openFileWrite(ofs, fname))
1255 //TexStream ts(ofs.rdbuf(), &texrow());
1256 ErrorList & errorList = d->errorLists["Export"];
1258 bool failed_export = false;
1261 writeLaTeXSource(ofs, original_path,
1262 runparams, output_preamble, output_body);
1264 catch (EncodingException & e) {
1265 odocstringstream ods;
1266 ods.put(e.failed_char);
1268 oss << "0x" << hex << e.failed_char << dec;
1269 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1270 " (code point %2$s)"),
1271 ods.str(), from_utf8(oss.str()));
1272 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1273 "representable in the chosen encoding.\n"
1274 "Changing the document encoding to utf8 could help."),
1275 e.par_id, e.pos, e.pos + 1));
1276 failed_export = true;
1278 catch (iconv_codecvt_facet_exception & e) {
1279 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1280 _(e.what()), -1, 0, 0));
1281 failed_export = true;
1283 catch (exception const & e) {
1284 errorList.push_back(ErrorItem(_("conversion failed"),
1285 _(e.what()), -1, 0, 0));
1286 failed_export = true;
1289 lyxerr << "Caught some really weird exception..." << endl;
1295 failed_export = true;
1296 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1300 return !failed_export;
1304 void Buffer::writeLaTeXSource(odocstream & os,
1305 string const & original_path,
1306 OutputParams const & runparams_in,
1307 bool const output_preamble, bool const output_body) const
1309 // The child documents, if any, shall be already loaded at this point.
1311 OutputParams runparams = runparams_in;
1313 // Classify the unicode characters appearing in math insets
1314 Encodings::initUnicodeMath(*this);
1316 // validate the buffer.
1317 LYXERR(Debug::LATEX, " Validating buffer...");
1318 LaTeXFeatures features(*this, params(), runparams);
1320 LYXERR(Debug::LATEX, " Buffer validation done.");
1322 // The starting paragraph of the coming rows is the
1323 // first paragraph of the document. (Asger)
1324 if (output_preamble && runparams.nice) {
1325 os << "%% LyX " << lyx_version << " created this file. "
1326 "For more info, see http://www.lyx.org/.\n"
1327 "%% Do not edit unless you really know what "
1329 d->texrow.newline();
1330 d->texrow.newline();
1332 LYXERR(Debug::INFO, "lyx document header finished");
1334 // Don't move this behind the parent_buffer=0 code below,
1335 // because then the macros will not get the right "redefinition"
1336 // flag as they don't see the parent macros which are output before.
1339 // fold macros if possible, still with parent buffer as the
1340 // macros will be put in the prefix anyway.
1341 updateMacroInstances();
1343 // There are a few differences between nice LaTeX and usual files:
1344 // usual is \batchmode and has a
1345 // special input@path to allow the including of figures
1346 // with either \input or \includegraphics (what figinsets do).
1347 // input@path is set when the actual parameter
1348 // original_path is set. This is done for usual tex-file, but not
1349 // for nice-latex-file. (Matthias 250696)
1350 // Note that input@path is only needed for something the user does
1351 // in the preamble, included .tex files or ERT, files included by
1352 // LyX work without it.
1353 if (output_preamble) {
1354 if (!runparams.nice) {
1355 // code for usual, NOT nice-latex-file
1356 os << "\\batchmode\n"; // changed
1357 // from \nonstopmode
1358 d->texrow.newline();
1360 if (!original_path.empty()) {
1362 // We don't know the encoding of inputpath
1363 docstring const inputpath = from_utf8(support::latex_path(original_path));
1364 docstring uncodable_glyphs;
1365 Encoding const * const enc = runparams.encoding;
1367 for (size_t n = 0; n < inputpath.size(); ++n) {
1368 docstring const glyph =
1369 docstring(1, inputpath[n]);
1370 if (enc->latexChar(inputpath[n], true) != glyph) {
1371 LYXERR0("Uncodable character '"
1373 << "' in input path!");
1374 uncodable_glyphs += glyph;
1379 // warn user if we found uncodable glyphs.
1380 if (!uncodable_glyphs.empty()) {
1381 frontend::Alert::warning(_("Uncodable character in file path"),
1382 support::bformat(_("The path of your document\n"
1384 "contains glyphs that are unknown in the\n"
1385 "current document encoding (namely %2$s).\n"
1386 "This will likely result in incomplete output.\n\n"
1387 "Choose an appropriate document encoding (such as utf8)\n"
1388 "or change the file path name."), inputpath, uncodable_glyphs));
1390 os << "\\makeatletter\n"
1391 << "\\def\\input@path{{"
1392 << inputpath << "/}}\n"
1393 << "\\makeatother\n";
1394 d->texrow.newline();
1395 d->texrow.newline();
1396 d->texrow.newline();
1400 // get parent macros (if this buffer has a parent) which will be
1401 // written at the document begin further down.
1402 MacroSet parentMacros;
1403 listParentMacros(parentMacros, features);
1405 runparams.use_polyglossia = features.usePolyglossia();
1406 // Write the preamble
1407 runparams.use_babel = params().writeLaTeX(os, features,
1409 d->filename.onlyPath());
1411 runparams.use_japanese = features.isRequired("japanese");
1417 os << "\\begin{document}\n";
1418 d->texrow.newline();
1420 // output the parent macros
1421 MacroSet::iterator it = parentMacros.begin();
1422 MacroSet::iterator end = parentMacros.end();
1423 for (; it != end; ++it) {
1424 int num_lines = (*it)->write(os, true);
1425 d->texrow.newlines(num_lines);
1428 } // output_preamble
1430 d->texrow.start(paragraphs().begin()->id(), 0);
1432 LYXERR(Debug::INFO, "preamble finished, now the body.");
1434 // if we are doing a real file with body, even if this is the
1435 // child of some other buffer, let's cut the link here.
1436 // This happens for example if only a child document is printed.
1437 Buffer const * save_parent = 0;
1438 if (output_preamble) {
1439 save_parent = d->parent();
1444 latexParagraphs(*this, text(), os, d->texrow, runparams);
1446 // Restore the parenthood if needed
1447 if (output_preamble)
1448 d->setParent(save_parent);
1450 // add this just in case after all the paragraphs
1452 d->texrow.newline();
1454 if (output_preamble) {
1455 os << "\\end{document}\n";
1456 d->texrow.newline();
1457 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1459 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1461 runparams_in.encoding = runparams.encoding;
1463 // Just to be sure. (Asger)
1464 d->texrow.newline();
1466 //for (int i = 0; i<d->texrow.rows(); i++) {
1468 // if (d->texrow.getIdFromRow(i+1,id,pos) && id>0)
1469 // lyxerr << i+1 << ":" << id << ":" << getParFromID(id).paragraph().asString()<<"\n";
1472 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1473 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1477 bool Buffer::isLatex() const
1479 return params().documentClass().outputType() == LATEX;
1483 bool Buffer::isLiterate() const
1485 return params().documentClass().outputType() == LITERATE;
1489 bool Buffer::isDocBook() const
1491 return params().documentClass().outputType() == DOCBOOK;
1495 void Buffer::makeDocBookFile(FileName const & fname,
1496 OutputParams const & runparams,
1497 bool const body_only) const
1499 LYXERR(Debug::LATEX, "makeDocBookFile...");
1502 if (!openFileWrite(ofs, fname))
1505 writeDocBookSource(ofs, fname.absFileName(), runparams, body_only);
1509 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1513 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1514 OutputParams const & runparams,
1515 bool const only_body) const
1517 LaTeXFeatures features(*this, params(), runparams);
1522 DocumentClass const & tclass = params().documentClass();
1523 string const top_element = tclass.latexname();
1526 if (runparams.flavor == OutputParams::XML)
1527 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1530 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1533 if (! tclass.class_header().empty())
1534 os << from_ascii(tclass.class_header());
1535 else if (runparams.flavor == OutputParams::XML)
1536 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1537 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1539 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1541 docstring preamble = from_utf8(params().preamble);
1542 if (runparams.flavor != OutputParams::XML ) {
1543 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1544 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1545 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1546 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1549 string const name = runparams.nice
1550 ? changeExtension(absFileName(), ".sgml") : fname;
1551 preamble += features.getIncludedFiles(name);
1552 preamble += features.getLyXSGMLEntities();
1554 if (!preamble.empty()) {
1555 os << "\n [ " << preamble << " ]";
1560 string top = top_element;
1562 if (runparams.flavor == OutputParams::XML)
1563 top += params().language->code();
1565 top += params().language->code().substr(0, 2);
1568 if (!params().options.empty()) {
1570 top += params().options;
1573 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1574 << " file was created by LyX " << lyx_version
1575 << "\n See http://www.lyx.org/ for more information -->\n";
1577 params().documentClass().counters().reset();
1581 sgml::openTag(os, top);
1583 docbookParagraphs(text(), *this, os, runparams);
1584 sgml::closeTag(os, top_element);
1588 void Buffer::makeLyXHTMLFile(FileName const & fname,
1589 OutputParams const & runparams,
1590 bool const body_only) const
1592 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1595 if (!openFileWrite(ofs, fname))
1598 writeLyXHTMLSource(ofs, runparams, body_only);
1602 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1606 void Buffer::writeLyXHTMLSource(odocstream & os,
1607 OutputParams const & runparams,
1608 bool const only_body) const
1610 LaTeXFeatures features(*this, params(), runparams);
1612 updateBuffer(UpdateMaster, OutputUpdate);
1613 d->bibinfo_.makeCitationLabels(*this);
1615 updateMacroInstances();
1618 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1619 << "<!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"
1620 // FIXME Language should be set properly.
1621 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
1623 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
1624 // FIXME Presumably need to set this right
1625 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1627 docstring const & doctitle = features.htmlTitle();
1629 << (doctitle.empty() ? from_ascii("LyX Document") : doctitle)
1632 os << "\n<!-- Text Class Preamble -->\n"
1633 << features.getTClassHTMLPreamble()
1634 << "\n<!-- Preamble Snippets -->\n"
1635 << from_utf8(features.getPreambleSnippets());
1637 os << "\n<!-- Layout-provided Styles -->\n";
1638 docstring const styleinfo = features.getTClassHTMLStyles();
1639 if (!styleinfo.empty()) {
1640 os << "<style type='text/css'>\n"
1644 os << "</head>\n<body>\n";
1648 params().documentClass().counters().reset();
1649 xhtmlParagraphs(text(), *this, xs, runparams);
1651 os << "</body>\n</html>\n";
1655 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1656 // Other flags: -wall -v0 -x
1657 int Buffer::runChktex()
1661 // get LaTeX-Filename
1662 FileName const path(temppath());
1663 string const name = addName(path.absFileName(), latexName());
1664 string const org_path = filePath();
1666 PathChanger p(path); // path to LaTeX file
1667 message(_("Running chktex..."));
1669 // Generate the LaTeX file if neccessary
1670 OutputParams runparams(¶ms().encoding());
1671 runparams.flavor = OutputParams::LATEX;
1672 runparams.nice = false;
1673 runparams.linelen = lyxrc.plaintext_linelen;
1674 makeLaTeXFile(FileName(name), org_path, runparams);
1677 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
1678 int const res = chktex.run(terr); // run chktex
1681 Alert::error(_("chktex failure"),
1682 _("Could not run chktex successfully."));
1683 } else if (res > 0) {
1684 ErrorList & errlist = d->errorLists["ChkTeX"];
1686 bufferErrors(terr, errlist);
1697 void Buffer::validate(LaTeXFeatures & features) const
1699 params().validate(features);
1703 for_each(paragraphs().begin(), paragraphs().end(),
1704 bind(&Paragraph::validate, _1, ref(features)));
1706 if (lyxerr.debugging(Debug::LATEX)) {
1707 features.showStruct();
1712 void Buffer::getLabelList(vector<docstring> & list) const
1714 // If this is a child document, use the master's list instead.
1716 masterBuffer()->getLabelList(list);
1721 Toc & toc = d->toc_backend.toc("label");
1722 TocIterator toc_it = toc.begin();
1723 TocIterator end = toc.end();
1724 for (; toc_it != end; ++toc_it) {
1725 if (toc_it->depth() == 0)
1726 list.push_back(toc_it->str());
1731 void Buffer::updateBibfilesCache(UpdateScope scope) const
1733 // FIXME This is probably unnecssary, given where we call this.
1734 // If this is a child document, use the parent's cache instead.
1735 if (parent() && scope != UpdateChildOnly) {
1736 masterBuffer()->updateBibfilesCache();
1740 d->bibfiles_cache_.clear();
1741 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1742 if (it->lyxCode() == BIBTEX_CODE) {
1743 InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
1744 support::FileNameList const bibfiles = inset.getBibFiles();
1745 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1748 } else if (it->lyxCode() == INCLUDE_CODE) {
1749 InsetInclude & inset = static_cast<InsetInclude &>(*it);
1750 Buffer const * const incbuf = inset.getChildBuffer();
1753 support::FileNameList const & bibfiles =
1754 incbuf->getBibfilesCache(UpdateChildOnly);
1755 if (!bibfiles.empty()) {
1756 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1762 d->bibfile_cache_valid_ = true;
1763 d->bibinfo_cache_valid_ = false;
1767 void Buffer::invalidateBibinfoCache() const
1769 d->bibinfo_cache_valid_ = false;
1770 // also invalidate the cache for the parent buffer
1771 Buffer const * const pbuf = d->parent();
1773 pbuf->invalidateBibinfoCache();
1777 void Buffer::invalidateBibfileCache() const
1779 d->bibfile_cache_valid_ = false;
1780 d->bibinfo_cache_valid_ = false;
1781 // also invalidate the cache for the parent buffer
1782 Buffer const * const pbuf = d->parent();
1784 pbuf->invalidateBibfileCache();
1788 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1790 // FIXME This is probably unnecessary, given where we call this.
1791 // If this is a child document, use the master's cache instead.
1792 Buffer const * const pbuf = masterBuffer();
1793 if (pbuf != this && scope != UpdateChildOnly)
1794 return pbuf->getBibfilesCache();
1796 if (!d->bibfile_cache_valid_)
1797 this->updateBibfilesCache(scope);
1799 return d->bibfiles_cache_;
1803 BiblioInfo const & Buffer::masterBibInfo() const
1805 Buffer const * const tmp = masterBuffer();
1807 return tmp->masterBibInfo();
1812 bool Buffer::isBibInfoCacheValid() const
1814 // use the master's cache
1815 Buffer const * const tmp = masterBuffer();
1817 return tmp->isBibInfoCacheValid();
1818 return d->bibinfo_cache_valid_;
1822 void Buffer::checkIfBibInfoCacheIsValid() const
1824 // use the master's cache
1825 Buffer const * const tmp = masterBuffer();
1827 tmp->checkIfBibInfoCacheIsValid();
1831 // compare the cached timestamps with the actual ones.
1832 FileNameList const & bibfiles_cache = getBibfilesCache();
1833 FileNameList::const_iterator ei = bibfiles_cache.begin();
1834 FileNameList::const_iterator en = bibfiles_cache.end();
1835 for (; ei != en; ++ ei) {
1836 time_t lastw = ei->lastModified();
1837 time_t prevw = d->bibfile_status_[*ei];
1838 if (lastw != prevw) {
1839 d->bibinfo_cache_valid_ = false;
1840 d->bibfile_status_[*ei] = lastw;
1846 void Buffer::reloadBibInfoCache() const
1848 // use the master's cache
1849 Buffer const * const tmp = masterBuffer();
1851 tmp->reloadBibInfoCache();
1855 checkIfBibInfoCacheIsValid();
1856 if (d->bibinfo_cache_valid_)
1859 d->bibinfo_.clear();
1861 d->bibinfo_cache_valid_ = true;
1865 void Buffer::collectBibKeys() const
1867 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1868 it->collectBibKeys(it);
1872 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
1874 Buffer const * tmp = masterBuffer();
1875 BiblioInfo & masterbi = (tmp == this) ?
1876 d->bibinfo_ : tmp->d->bibinfo_;
1877 masterbi.mergeBiblioInfo(bi);
1881 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
1883 Buffer const * tmp = masterBuffer();
1884 BiblioInfo & masterbi = (tmp == this) ?
1885 d->bibinfo_ : tmp->d->bibinfo_;
1890 bool Buffer::isDepClean(string const & name) const
1892 DepClean::const_iterator const it = d->dep_clean.find(name);
1893 if (it == d->dep_clean.end())
1899 void Buffer::markDepClean(string const & name)
1901 d->dep_clean[name] = true;
1905 bool Buffer::isExportableFormat(string const & format) const
1907 typedef vector<Format const *> Formats;
1909 formats = exportableFormats(true);
1910 Formats::const_iterator fit = formats.begin();
1911 Formats::const_iterator end = formats.end();
1912 for (; fit != end ; ++fit) {
1913 if ((*fit)->name() == format)
1920 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1923 // FIXME? if there is an Buffer LFUN that can be dispatched even
1924 // if internal, put a switch '(cmd.action)' here.
1930 switch (cmd.action()) {
1932 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1933 flag.setOnOff(isReadonly());
1936 // FIXME: There is need for a command-line import.
1937 //case LFUN_BUFFER_IMPORT:
1939 case LFUN_BUFFER_AUTO_SAVE:
1942 case LFUN_BUFFER_EXPORT_CUSTOM:
1943 // FIXME: Nothing to check here?
1946 case LFUN_BUFFER_EXPORT: {
1947 docstring const arg = cmd.argument();
1948 enable = arg == "custom" || isExportable(to_utf8(arg));
1950 flag.message(bformat(
1951 _("Don't know how to export to format: %1$s"), arg));
1955 case LFUN_BUFFER_CHKTEX:
1956 enable = isLatex() && !lyxrc.chktex_command.empty();
1959 case LFUN_BUILD_PROGRAM:
1960 enable = isExportable("program");
1963 case LFUN_BRANCH_ACTIVATE:
1964 case LFUN_BRANCH_DEACTIVATE: {
1965 BranchList const & branchList = params().branchlist();
1966 docstring const branchName = cmd.argument();
1967 enable = !branchName.empty() && branchList.find(branchName);
1971 case LFUN_BRANCH_ADD:
1972 case LFUN_BRANCHES_RENAME:
1973 case LFUN_BUFFER_PRINT:
1974 // if no Buffer is present, then of course we won't be called!
1977 case LFUN_BUFFER_LANGUAGE:
1978 enable = !isReadonly();
1984 flag.setEnabled(enable);
1989 void Buffer::dispatch(string const & command, DispatchResult & result)
1991 return dispatch(lyxaction.lookupFunc(command), result);
1995 // NOTE We can end up here even if we have no GUI, because we are called
1996 // by LyX::exec to handled command-line requests. So we may need to check
1997 // whether we have a GUI or not. The boolean use_gui holds this information.
1998 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2001 // FIXME? if there is an Buffer LFUN that can be dispatched even
2002 // if internal, put a switch '(cmd.action())' here.
2003 dr.dispatched(false);
2006 string const argument = to_utf8(func.argument());
2007 // We'll set this back to false if need be.
2008 bool dispatched = true;
2009 undo().beginUndoGroup();
2011 switch (func.action()) {
2012 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2013 if (lyxvc().inUse())
2014 lyxvc().toggleReadOnly();
2016 setReadonly(!isReadonly());
2019 case LFUN_BUFFER_EXPORT: {
2020 bool success = doExport(argument, false, false);
2021 dr.setError(!success);
2023 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2028 case LFUN_BUILD_PROGRAM:
2029 doExport("program", true, false);
2032 case LFUN_BUFFER_CHKTEX:
2036 case LFUN_BUFFER_EXPORT_CUSTOM: {
2038 string command = split(argument, format_name, ' ');
2039 Format const * format = formats.getFormat(format_name);
2041 lyxerr << "Format \"" << format_name
2042 << "\" not recognized!"
2047 // The name of the file created by the conversion process
2050 // Output to filename
2051 if (format->name() == "lyx") {
2052 string const latexname = latexName(false);
2053 filename = changeExtension(latexname,
2054 format->extension());
2055 filename = addName(temppath(), filename);
2057 if (!writeFile(FileName(filename)))
2061 doExport(format_name, true, false, filename);
2064 // Substitute $$FName for filename
2065 if (!contains(command, "$$FName"))
2066 command = "( " + command + " ) < $$FName";
2067 command = subst(command, "$$FName", filename);
2069 // Execute the command in the background
2071 call.startscript(Systemcall::DontWait, command);
2075 // FIXME: There is need for a command-line import.
2077 case LFUN_BUFFER_IMPORT:
2082 case LFUN_BUFFER_AUTO_SAVE:
2084 resetAutosaveTimers();
2087 case LFUN_BRANCH_ADD: {
2088 docstring branch_name = func.argument();
2089 if (branch_name.empty()) {
2093 BranchList & branch_list = params().branchlist();
2094 vector<docstring> const branches =
2095 getVectorFromString(branch_name, branch_list.separator());
2097 for (vector<docstring>::const_iterator it = branches.begin();
2098 it != branches.end(); ++it) {
2100 Branch * branch = branch_list.find(branch_name);
2102 LYXERR0("Branch " << branch_name << " already exists.");
2106 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2108 branch_list.add(branch_name);
2109 branch = branch_list.find(branch_name);
2110 string const x11hexname = X11hexname(branch->color());
2111 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2112 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2114 dr.screenUpdate(Update::Force);
2122 case LFUN_BRANCH_ACTIVATE:
2123 case LFUN_BRANCH_DEACTIVATE: {
2124 BranchList & branchList = params().branchlist();
2125 docstring const branchName = func.argument();
2126 // the case without a branch name is handled elsewhere
2127 if (branchName.empty()) {
2131 Branch * branch = branchList.find(branchName);
2133 LYXERR0("Branch " << branchName << " does not exist.");
2135 docstring const msg =
2136 bformat(_("Branch \"%1$s\" does not exist."), branchName);
2139 branch->setSelected(func.action() == LFUN_BRANCH_ACTIVATE);
2141 dr.screenUpdate(Update::Force);
2142 dr.forceBufferUpdate();
2147 case LFUN_BRANCHES_RENAME: {
2148 if (func.argument().empty())
2151 docstring const oldname = from_utf8(func.getArg(0));
2152 docstring const newname = from_utf8(func.getArg(1));
2153 InsetIterator it = inset_iterator_begin(inset());
2154 InsetIterator const end = inset_iterator_end(inset());
2155 bool success = false;
2156 for (; it != end; ++it) {
2157 if (it->lyxCode() == BRANCH_CODE) {
2158 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2159 if (ins.branch() == oldname) {
2160 undo().recordUndo(it);
2161 ins.rename(newname);
2166 if (it->lyxCode() == INCLUDE_CODE) {
2167 // get buffer of external file
2168 InsetInclude const & ins =
2169 static_cast<InsetInclude const &>(*it);
2170 Buffer * child = ins.getChildBuffer();
2173 child->dispatch(func, dr);
2178 dr.screenUpdate(Update::Force);
2179 dr.forceBufferUpdate();
2184 case LFUN_BUFFER_PRINT: {
2185 // we'll assume there's a problem until we succeed
2187 string target = func.getArg(0);
2188 string target_name = func.getArg(1);
2189 string command = func.getArg(2);
2192 || target_name.empty()
2193 || command.empty()) {
2194 LYXERR0("Unable to parse " << func.argument());
2195 docstring const msg =
2196 bformat(_("Unable to parse \"%1$s\""), func.argument());
2200 if (target != "printer" && target != "file") {
2201 LYXERR0("Unrecognized target \"" << target << '"');
2202 docstring const msg =
2203 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2208 bool const update_unincluded =
2209 params().maintain_unincluded_children
2210 && !params().getIncludedChildren().empty();
2211 if (!doExport("dvi", true, update_unincluded)) {
2212 showPrintError(absFileName());
2213 dr.setMessage(_("Error exporting to DVI."));
2217 // Push directory path.
2218 string const path = temppath();
2219 // Prevent the compiler from optimizing away p
2223 // there are three cases here:
2224 // 1. we print to a file
2225 // 2. we print directly to a printer
2226 // 3. we print using a spool command (print to file first)
2229 string const dviname = changeExtension(latexName(true), "dvi");
2231 if (target == "printer") {
2232 if (!lyxrc.print_spool_command.empty()) {
2233 // case 3: print using a spool
2234 string const psname = changeExtension(dviname,".ps");
2235 command += ' ' + lyxrc.print_to_file
2238 + quoteName(dviname);
2240 string command2 = lyxrc.print_spool_command + ' ';
2241 if (target_name != "default") {
2242 command2 += lyxrc.print_spool_printerprefix
2246 command2 += quoteName(psname);
2248 // If successful, then spool command
2249 res = one.startscript(Systemcall::Wait, command);
2252 // If there's no GUI, we have to wait on this command. Otherwise,
2253 // LyX deletes the temporary directory, and with it the spooled
2254 // file, before it can be printed!!
2255 Systemcall::Starttype stype = use_gui ?
2256 Systemcall::DontWait : Systemcall::Wait;
2257 res = one.startscript(stype, command2);
2260 // case 2: print directly to a printer
2261 if (target_name != "default")
2262 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2264 Systemcall::Starttype stype = use_gui ?
2265 Systemcall::DontWait : Systemcall::Wait;
2266 res = one.startscript(stype, command + quoteName(dviname));
2270 // case 1: print to a file
2271 FileName const filename(makeAbsPath(target_name, filePath()));
2272 FileName const dvifile(makeAbsPath(dviname, path));
2273 if (filename.exists()) {
2274 docstring text = bformat(
2275 _("The file %1$s already exists.\n\n"
2276 "Do you want to overwrite that file?"),
2277 makeDisplayPath(filename.absFileName()));
2278 if (Alert::prompt(_("Overwrite file?"),
2279 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2282 command += ' ' + lyxrc.print_to_file
2283 + quoteName(filename.toFilesystemEncoding())
2285 + quoteName(dvifile.toFilesystemEncoding());
2287 Systemcall::Starttype stype = use_gui ?
2288 Systemcall::DontWait : Systemcall::Wait;
2289 res = one.startscript(stype, command);
2295 dr.setMessage(_("Error running external commands."));
2296 showPrintError(absFileName());
2301 case LFUN_BUFFER_LANGUAGE: {
2302 Language const * oldL = params().language;
2303 Language const * newL = languages.getLanguage(argument);
2304 if (!newL || oldL == newL)
2306 if (oldL->rightToLeft() == newL->rightToLeft() && !isMultiLingual()) {
2307 changeLanguage(oldL, newL);
2308 dr.forceBufferUpdate();
2317 dr.dispatched(dispatched);
2318 undo().endUndoGroup();
2322 void Buffer::changeLanguage(Language const * from, Language const * to)
2324 LASSERT(from, /**/);
2327 for_each(par_iterator_begin(),
2329 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2333 bool Buffer::isMultiLingual() const
2335 ParConstIterator end = par_iterator_end();
2336 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2337 if (it->isMultiLingual(params()))
2344 std::set<Language const *> Buffer::getLanguages() const
2346 std::set<Language const *> languages;
2347 getLanguages(languages);
2352 void Buffer::getLanguages(std::set<Language const *> & languages) const
2354 ParConstIterator end = par_iterator_end();
2355 // add the buffer language, even if it's not actively used
2356 languages.insert(language());
2357 // iterate over the paragraphs
2358 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2359 it->getLanguages(languages);
2361 ListOfBuffers clist = getDescendents();
2362 ListOfBuffers::const_iterator cit = clist.begin();
2363 ListOfBuffers::const_iterator const cen = clist.end();
2364 for (; cit != cen; ++cit)
2365 (*cit)->getLanguages(languages);
2369 DocIterator Buffer::getParFromID(int const id) const
2371 Buffer * buf = const_cast<Buffer *>(this);
2373 // John says this is called with id == -1 from undo
2374 lyxerr << "getParFromID(), id: " << id << endl;
2375 return doc_iterator_end(buf);
2378 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2379 if (it.paragraph().id() == id)
2382 return doc_iterator_end(buf);
2386 bool Buffer::hasParWithID(int const id) const
2388 return !getParFromID(id).atEnd();
2392 ParIterator Buffer::par_iterator_begin()
2394 return ParIterator(doc_iterator_begin(this));
2398 ParIterator Buffer::par_iterator_end()
2400 return ParIterator(doc_iterator_end(this));
2404 ParConstIterator Buffer::par_iterator_begin() const
2406 return ParConstIterator(doc_iterator_begin(this));
2410 ParConstIterator Buffer::par_iterator_end() const
2412 return ParConstIterator(doc_iterator_end(this));
2416 Language const * Buffer::language() const
2418 return params().language;
2422 docstring const Buffer::B_(string const & l10n) const
2424 return params().B_(l10n);
2428 bool Buffer::isClean() const
2430 return d->lyx_clean;
2434 bool Buffer::isExternallyModified(CheckMethod method) const
2436 LASSERT(d->filename.exists(), /**/);
2437 // if method == timestamp, check timestamp before checksum
2438 return (method == checksum_method
2439 || d->timestamp_ != d->filename.lastModified())
2440 && d->checksum_ != d->filename.checksum();
2444 void Buffer::saveCheckSum() const
2446 FileName const & file = d->filename;
2447 if (file.exists()) {
2448 d->timestamp_ = file.lastModified();
2449 d->checksum_ = file.checksum();
2451 // in the case of save to a new file.
2458 void Buffer::markClean() const
2460 if (!d->lyx_clean) {
2461 d->lyx_clean = true;
2464 // if the .lyx file has been saved, we don't need an
2466 d->bak_clean = true;
2467 d->undo_.markDirty();
2471 void Buffer::setUnnamed(bool flag)
2477 bool Buffer::isUnnamed() const
2484 /// Don't check unnamed, here: isInternal() is used in
2485 /// newBuffer(), where the unnamed flag has not been set by anyone
2486 /// yet. Also, for an internal buffer, there should be no need for
2487 /// retrieving fileName() nor for checking if it is unnamed or not.
2488 bool Buffer::isInternal() const
2490 return fileName().extension() == "internal";
2494 void Buffer::markDirty()
2497 d->lyx_clean = false;
2500 d->bak_clean = false;
2502 DepClean::iterator it = d->dep_clean.begin();
2503 DepClean::const_iterator const end = d->dep_clean.end();
2505 for (; it != end; ++it)
2510 FileName Buffer::fileName() const
2516 string Buffer::absFileName() const
2518 return d->filename.absFileName();
2522 string Buffer::filePath() const
2524 return d->filename.onlyPath().absFileName() + "/";
2528 bool Buffer::isReadonly() const
2530 return d->read_only;
2534 void Buffer::setParent(Buffer const * buffer)
2536 // Avoids recursive include.
2537 d->setParent(buffer == this ? 0 : buffer);
2542 Buffer const * Buffer::parent() const
2548 ListOfBuffers Buffer::allRelatives() const
2550 ListOfBuffers lb = masterBuffer()->getDescendents();
2551 lb.push_front(const_cast<Buffer *>(this));
2556 Buffer const * Buffer::masterBuffer() const
2558 // FIXME Should be make sure we are not in some kind
2559 // of recursive include? A -> B -> A will crash this.
2560 Buffer const * const pbuf = d->parent();
2564 return pbuf->masterBuffer();
2568 bool Buffer::isChild(Buffer * child) const
2570 return d->children_positions.find(child) != d->children_positions.end();
2574 DocIterator Buffer::firstChildPosition(Buffer const * child)
2576 Impl::BufferPositionMap::iterator it;
2577 it = d->children_positions.find(child);
2578 if (it == d->children_positions.end())
2579 return DocIterator(this);
2584 bool Buffer::hasChildren() const
2586 return !d->children_positions.empty();
2590 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
2592 // loop over children
2593 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2594 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2595 for (; it != end; ++it) {
2596 Buffer * child = const_cast<Buffer *>(it->first);
2598 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
2599 if (bit != clist.end())
2601 clist.push_back(child);
2603 // there might be grandchildren
2604 child->collectChildren(clist, true);
2609 ListOfBuffers Buffer::getChildren() const
2612 collectChildren(v, false);
2617 ListOfBuffers Buffer::getDescendents() const
2620 collectChildren(v, true);
2625 template<typename M>
2626 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
2631 typename M::const_iterator it = m.lower_bound(x);
2632 if (it == m.begin())
2640 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
2641 DocIterator const & pos) const
2643 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2645 // if paragraphs have no macro context set, pos will be empty
2649 // we haven't found anything yet
2650 DocIterator bestPos = owner_->par_iterator_begin();
2651 MacroData const * bestData = 0;
2653 // find macro definitions for name
2654 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
2655 if (nameIt != macros.end()) {
2656 // find last definition in front of pos or at pos itself
2657 PositionScopeMacroMap::const_iterator it
2658 = greatest_below(nameIt->second, pos);
2659 if (it != nameIt->second.end()) {
2661 // scope ends behind pos?
2662 if (pos < it->second.first) {
2663 // Looks good, remember this. If there
2664 // is no external macro behind this,
2665 // we found the right one already.
2666 bestPos = it->first;
2667 bestData = &it->second.second;
2671 // try previous macro if there is one
2672 if (it == nameIt->second.begin())
2679 // find macros in included files
2680 PositionScopeBufferMap::const_iterator it
2681 = greatest_below(position_to_children, pos);
2682 if (it == position_to_children.end())
2683 // no children before
2687 // do we know something better (i.e. later) already?
2688 if (it->first < bestPos )
2691 // scope ends behind pos?
2692 if (pos < it->second.first) {
2693 // look for macro in external file
2695 MacroData const * data
2696 = it->second.second->getMacro(name, false);
2699 bestPos = it->first;
2705 // try previous file if there is one
2706 if (it == position_to_children.begin())
2711 // return the best macro we have found
2716 MacroData const * Buffer::getMacro(docstring const & name,
2717 DocIterator const & pos, bool global) const
2722 // query buffer macros
2723 MacroData const * data = d->getBufferMacro(name, pos);
2727 // If there is a master buffer, query that
2728 Buffer const * const pbuf = d->parent();
2730 d->macro_lock = true;
2731 MacroData const * macro = pbuf->getMacro(
2732 name, *this, false);
2733 d->macro_lock = false;
2739 data = MacroTable::globalMacros().get(name);
2748 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2750 // set scope end behind the last paragraph
2751 DocIterator scope = par_iterator_begin();
2752 scope.pit() = scope.lastpit() + 1;
2754 return getMacro(name, scope, global);
2758 MacroData const * Buffer::getMacro(docstring const & name,
2759 Buffer const & child, bool global) const
2761 // look where the child buffer is included first
2762 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2763 if (it == d->children_positions.end())
2766 // check for macros at the inclusion position
2767 return getMacro(name, it->second, global);
2771 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
2773 pit_type const lastpit = it.lastpit();
2775 // look for macros in each paragraph
2776 while (it.pit() <= lastpit) {
2777 Paragraph & par = it.paragraph();
2779 // iterate over the insets of the current paragraph
2780 InsetList const & insets = par.insetList();
2781 InsetList::const_iterator iit = insets.begin();
2782 InsetList::const_iterator end = insets.end();
2783 for (; iit != end; ++iit) {
2784 it.pos() = iit->pos;
2786 // is it a nested text inset?
2787 if (iit->inset->asInsetText()) {
2788 // Inset needs its own scope?
2789 InsetText const * itext = iit->inset->asInsetText();
2790 bool newScope = itext->isMacroScope();
2792 // scope which ends just behind the inset
2793 DocIterator insetScope = it;
2796 // collect macros in inset
2797 it.push_back(CursorSlice(*iit->inset));
2798 updateMacros(it, newScope ? insetScope : scope);
2803 if (iit->inset->asInsetTabular()) {
2804 CursorSlice slice(*iit->inset);
2805 size_t const numcells = slice.nargs();
2806 for (; slice.idx() < numcells; slice.forwardIdx()) {
2807 it.push_back(slice);
2808 updateMacros(it, scope);
2814 // is it an external file?
2815 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2816 // get buffer of external file
2817 InsetInclude const & inset =
2818 static_cast<InsetInclude const &>(*iit->inset);
2820 Buffer * child = inset.getChildBuffer();
2825 // register its position, but only when it is
2826 // included first in the buffer
2827 if (children_positions.find(child) ==
2828 children_positions.end())
2829 children_positions[child] = it;
2831 // register child with its scope
2832 position_to_children[it] = Impl::ScopeBuffer(scope, child);
2836 InsetMath * im = iit->inset->asInsetMath();
2837 if (doing_export && im) {
2838 InsetMathHull * hull = im->asHullInset();
2840 hull->recordLocation(it);
2843 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2847 MathMacroTemplate & macroTemplate =
2848 *iit->inset->asInsetMath()->asMacroTemplate();
2849 MacroContext mc(owner_, it);
2850 macroTemplate.updateToContext(mc);
2853 bool valid = macroTemplate.validMacro();
2854 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2855 // then the BufferView's cursor will be invalid in
2856 // some cases which leads to crashes.
2861 // FIXME (Abdel), I don't understandt why we pass 'it' here
2862 // instead of 'macroTemplate' defined above... is this correct?
2863 macros[macroTemplate.name()][it] =
2864 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
2874 void Buffer::updateMacros() const
2879 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2881 // start with empty table
2883 d->children_positions.clear();
2884 d->position_to_children.clear();
2886 // Iterate over buffer, starting with first paragraph
2887 // The scope must be bigger than any lookup DocIterator
2888 // later. For the global lookup, lastpit+1 is used, hence
2889 // we use lastpit+2 here.
2890 DocIterator it = par_iterator_begin();
2891 DocIterator outerScope = it;
2892 outerScope.pit() = outerScope.lastpit() + 2;
2893 d->updateMacros(it, outerScope);
2897 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
2899 InsetIterator it = inset_iterator_begin(inset());
2900 InsetIterator const end = inset_iterator_end(inset());
2901 for (; it != end; ++it) {
2902 if (it->lyxCode() == BRANCH_CODE) {
2903 InsetBranch & br = static_cast<InsetBranch &>(*it);
2904 docstring const name = br.branch();
2905 if (!from_master && !params().branchlist().find(name))
2906 result.push_back(name);
2907 else if (from_master && !masterBuffer()->params().branchlist().find(name))
2908 result.push_back(name);
2911 if (it->lyxCode() == INCLUDE_CODE) {
2912 // get buffer of external file
2913 InsetInclude const & ins =
2914 static_cast<InsetInclude const &>(*it);
2915 Buffer * child = ins.getChildBuffer();
2918 child->getUsedBranches(result, true);
2921 // remove duplicates
2926 void Buffer::updateMacroInstances() const
2928 LYXERR(Debug::MACROS, "updateMacroInstances for "
2929 << d->filename.onlyFileName());
2930 DocIterator it = doc_iterator_begin(this);
2932 DocIterator const end = doc_iterator_end(this);
2933 for (; it != end; it.forwardInset()) {
2934 // look for MathData cells in InsetMathNest insets
2935 InsetMath * minset = it.nextInset()->asInsetMath();
2939 // update macro in all cells of the InsetMathNest
2940 DocIterator::idx_type n = minset->nargs();
2941 MacroContext mc = MacroContext(this, it);
2942 for (DocIterator::idx_type i = 0; i < n; ++i) {
2943 MathData & data = minset->cell(i);
2944 data.updateMacros(0, mc);
2950 void Buffer::listMacroNames(MacroNameSet & macros) const
2955 d->macro_lock = true;
2957 // loop over macro names
2958 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2959 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2960 for (; nameIt != nameEnd; ++nameIt)
2961 macros.insert(nameIt->first);
2963 // loop over children
2964 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2965 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2966 for (; it != end; ++it)
2967 it->first->listMacroNames(macros);
2970 Buffer const * const pbuf = d->parent();
2972 pbuf->listMacroNames(macros);
2974 d->macro_lock = false;
2978 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2980 Buffer const * const pbuf = d->parent();
2985 pbuf->listMacroNames(names);
2988 MacroNameSet::iterator it = names.begin();
2989 MacroNameSet::iterator end = names.end();
2990 for (; it != end; ++it) {
2992 MacroData const * data =
2993 pbuf->getMacro(*it, *this, false);
2995 macros.insert(data);
2997 // we cannot access the original MathMacroTemplate anymore
2998 // here to calls validate method. So we do its work here manually.
2999 // FIXME: somehow make the template accessible here.
3000 if (data->optionals() > 0)
3001 features.require("xargs");
3007 Buffer::References & Buffer::references(docstring const & label)
3010 return const_cast<Buffer *>(masterBuffer())->references(label);
3012 RefCache::iterator it = d->ref_cache_.find(label);
3013 if (it != d->ref_cache_.end())
3014 return it->second.second;
3016 static InsetLabel const * dummy_il = 0;
3017 static References const dummy_refs;
3018 it = d->ref_cache_.insert(
3019 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3020 return it->second.second;
3024 Buffer::References const & Buffer::references(docstring const & label) const
3026 return const_cast<Buffer *>(this)->references(label);
3030 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3032 masterBuffer()->d->ref_cache_[label].first = il;
3036 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3038 return masterBuffer()->d->ref_cache_[label].first;
3042 void Buffer::clearReferenceCache() const
3045 d->ref_cache_.clear();
3049 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
3052 //FIXME: This does not work for child documents yet.
3053 LASSERT(code == CITE_CODE, /**/);
3055 reloadBibInfoCache();
3057 // Check if the label 'from' appears more than once
3058 BiblioInfo const & keys = masterBibInfo();
3059 BiblioInfo::const_iterator bit = keys.begin();
3060 BiblioInfo::const_iterator bend = keys.end();
3061 vector<docstring> labels;
3063 for (; bit != bend; ++bit)
3065 labels.push_back(bit->first);
3067 if (count(labels.begin(), labels.end(), from) > 1)
3070 string const paramName = "key";
3071 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3072 if (it->lyxCode() == code) {
3073 InsetCommand * inset = it->asInsetCommand();
3076 docstring const oldValue = inset->getParam(paramName);
3077 if (oldValue == from)
3078 inset->setParam(paramName, to);
3084 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
3085 pit_type par_end, bool full_source) const
3087 OutputParams runparams(¶ms().encoding());
3088 runparams.nice = true;
3089 runparams.flavor = params().useNonTeXFonts ?
3090 OutputParams::XETEX : OutputParams::LATEX;
3091 runparams.linelen = lyxrc.plaintext_linelen;
3092 // No side effect of file copying and image conversion
3093 runparams.dryrun = true;
3096 os << "% " << _("Preview source code") << "\n\n";
3098 d->texrow.newline();
3099 d->texrow.newline();
3101 writeDocBookSource(os, absFileName(), runparams, false);
3103 // latex or literate
3104 writeLaTeXSource(os, string(), runparams, true, true);
3106 runparams.par_begin = par_begin;
3107 runparams.par_end = par_end;
3108 if (par_begin + 1 == par_end) {
3110 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3114 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3115 convert<docstring>(par_begin),
3116 convert<docstring>(par_end - 1))
3123 // output paragraphs
3125 docbookParagraphs(text(), *this, os, runparams);
3127 // latex or literate
3128 latexParagraphs(*this, text(), os, texrow, runparams);
3133 ErrorList & Buffer::errorList(string const & type) const
3135 static ErrorList emptyErrorList;
3136 map<string, ErrorList>::iterator it = d->errorLists.find(type);
3137 if (it == d->errorLists.end())
3138 return emptyErrorList;
3144 void Buffer::updateTocItem(std::string const & type,
3145 DocIterator const & dit) const
3148 d->gui_->updateTocItem(type, dit);
3152 void Buffer::structureChanged() const
3155 d->gui_->structureChanged();
3159 void Buffer::errors(string const & err, bool from_master) const
3162 d->gui_->errors(err, from_master);
3166 void Buffer::message(docstring const & msg) const
3169 d->gui_->message(msg);
3173 void Buffer::setBusy(bool on) const
3176 d->gui_->setBusy(on);
3180 void Buffer::updateTitles() const
3183 d->wa_->updateTitles();
3187 void Buffer::resetAutosaveTimers() const
3190 d->gui_->resetAutosaveTimers();
3194 bool Buffer::hasGuiDelegate() const
3200 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3209 class AutoSaveBuffer : public ForkedProcess {
3212 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3213 : buffer_(buffer), fname_(fname) {}
3215 virtual shared_ptr<ForkedProcess> clone() const
3217 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3222 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3223 from_utf8(fname_.absFileName())));
3224 return run(DontWait);
3228 virtual int generateChild();
3230 Buffer const & buffer_;
3235 int AutoSaveBuffer::generateChild()
3237 #if defined(__APPLE__)
3238 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3239 * We should use something else like threads.
3241 * Since I do not know how to determine at run time what is the OS X
3242 * version, I just disable forking altogether for now (JMarc)
3244 pid_t const pid = -1;
3246 // tmp_ret will be located (usually) in /tmp
3247 // will that be a problem?
3248 // Note that this calls ForkedCalls::fork(), so it's
3249 // ok cross-platform.
3250 pid_t const pid = fork();
3251 // If you want to debug the autosave
3252 // you should set pid to -1, and comment out the fork.
3253 if (pid != 0 && pid != -1)
3257 // pid = -1 signifies that lyx was unable
3258 // to fork. But we will do the save
3260 bool failed = false;
3261 FileName const tmp_ret = FileName::tempName("lyxauto");
3262 if (!tmp_ret.empty()) {
3263 buffer_.writeFile(tmp_ret);
3264 // assume successful write of tmp_ret
3265 if (!tmp_ret.moveTo(fname_))
3271 // failed to write/rename tmp_ret so try writing direct
3272 if (!buffer_.writeFile(fname_)) {
3273 // It is dangerous to do this in the child,
3274 // but safe in the parent, so...
3275 if (pid == -1) // emit message signal.
3276 buffer_.message(_("Autosave failed!"));
3280 if (pid == 0) // we are the child so...
3289 FileName Buffer::getEmergencyFileName() const
3291 return FileName(d->filename.absFileName() + ".emergency");
3295 FileName Buffer::getAutosaveFileName() const
3297 // if the document is unnamed try to save in the backup dir, else
3298 // in the default document path, and as a last try in the filePath,
3299 // which will most often be the temporary directory
3302 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3303 : lyxrc.backupdir_path;
3304 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3307 string const fname = "#" + d->filename.onlyFileName() + "#";
3309 return makeAbsPath(fname, fpath);
3313 void Buffer::removeAutosaveFile() const
3315 FileName const f = getAutosaveFileName();
3321 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3323 FileName const newauto = getAutosaveFileName();
3325 if (newauto != oldauto && oldauto.exists())
3326 if (!oldauto.moveTo(newauto))
3327 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3331 bool Buffer::autoSave() const
3333 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
3334 if (buf->d->bak_clean || isReadonly())
3337 message(_("Autosaving current document..."));
3338 buf->d->bak_clean = true;
3340 FileName const fname = getAutosaveFileName();
3341 if (d->cloned_buffer_) {
3342 // If this buffer is cloned, we assume that
3343 // we are running in a separate thread already.
3344 FileName const tmp_ret = FileName::tempName("lyxauto");
3345 if (!tmp_ret.empty()) {
3347 // assume successful write of tmp_ret
3348 if (tmp_ret.moveTo(fname))
3351 // failed to write/rename tmp_ret so try writing direct
3352 return writeFile(fname);
3354 /// This function is deprecated as the frontend needs to take care
3355 /// of cloning the buffer and autosaving it in another thread. It
3356 /// is still here to allow (QT_VERSION < 0x040400).
3357 AutoSaveBuffer autosave(*this, fname);
3364 string Buffer::bufferFormat() const
3366 string format = params().documentClass().outputFormat();
3367 if (format == "latex") {
3368 if (params().useNonTeXFonts)
3370 if (params().encoding().package() == Encoding::japanese)
3377 string Buffer::getDefaultOutputFormat() const
3379 if (!params().default_output_format.empty()
3380 && params().default_output_format != "default")
3381 return params().default_output_format;
3382 typedef vector<Format const *> Formats;
3383 Formats formats = exportableFormats(true);
3386 || params().useNonTeXFonts
3387 || params().encoding().package() == Encoding::japanese) {
3388 if (formats.empty())
3390 // return the first we find
3391 return formats.front()->name();
3393 return lyxrc.default_view_format;
3398 // helper class, to guarantee this gets reset properly
3399 class MarkAsExporting {
3401 MarkAsExporting(Buffer const * buf) : buf_(buf)
3403 LASSERT(buf_, /* */);
3404 buf_->setExportStatus(true);
3408 buf_->setExportStatus(false);
3411 Buffer const * const buf_;
3416 void Buffer::setExportStatus(bool e) const
3418 d->doing_export = e;
3422 bool Buffer::isExporting() const
3424 return d->doing_export;
3428 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3429 bool includeall, string & result_file) const
3431 MarkAsExporting exporting(this);
3432 string backend_format;
3433 OutputParams runparams(¶ms().encoding());
3434 runparams.flavor = OutputParams::LATEX;
3435 runparams.linelen = lyxrc.plaintext_linelen;
3436 runparams.includeall = includeall;
3437 vector<string> backs = backends();
3438 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3439 // Get shortest path to format
3440 Graph::EdgePath path;
3441 for (vector<string>::const_iterator it = backs.begin();
3442 it != backs.end(); ++it) {
3443 Graph::EdgePath p = theConverters().getPath(*it, format);
3444 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3445 backend_format = *it;
3450 if (!put_in_tempdir) {
3451 // Only show this alert if this is an export to a non-temporary
3452 // file (not for previewing).
3453 Alert::error(_("Couldn't export file"), bformat(
3454 _("No information for exporting the format %1$s."),
3455 formats.prettyName(format)));
3459 runparams.flavor = theConverters().getFlavor(path);
3462 backend_format = format;
3463 // FIXME: Don't hardcode format names here, but use a flag
3464 if (backend_format == "pdflatex")
3465 runparams.flavor = OutputParams::PDFLATEX;
3466 else if (backend_format == "luatex")
3467 runparams.flavor = OutputParams::LUATEX;
3468 else if (backend_format == "xetex")
3469 runparams.flavor = OutputParams::XETEX;
3472 string filename = latexName(false);
3473 filename = addName(temppath(), filename);
3474 filename = changeExtension(filename,
3475 formats.extension(backend_format));
3478 updateMacroInstances();
3480 // Plain text backend
3481 if (backend_format == "text") {
3482 runparams.flavor = OutputParams::TEXT;
3483 writePlaintextFile(*this, FileName(filename), runparams);
3486 else if (backend_format == "xhtml") {
3487 runparams.flavor = OutputParams::HTML;
3488 switch (params().html_math_output) {
3489 case BufferParams::MathML:
3490 runparams.math_flavor = OutputParams::MathAsMathML;
3492 case BufferParams::HTML:
3493 runparams.math_flavor = OutputParams::MathAsHTML;
3495 case BufferParams::Images:
3496 runparams.math_flavor = OutputParams::MathAsImages;
3498 case BufferParams::LaTeX:
3499 runparams.math_flavor = OutputParams::MathAsLaTeX;
3502 makeLyXHTMLFile(FileName(filename), runparams);
3503 } else if (backend_format == "lyx")
3504 writeFile(FileName(filename));
3506 else if (isDocBook()) {
3507 runparams.nice = !put_in_tempdir;
3508 makeDocBookFile(FileName(filename), runparams);
3511 else if (backend_format == format) {
3512 runparams.nice = true;
3513 if (!makeLaTeXFile(FileName(filename), string(), runparams))
3515 } else if (!lyxrc.tex_allows_spaces
3516 && contains(filePath(), ' ')) {
3517 Alert::error(_("File name error"),
3518 _("The directory path to the document cannot contain spaces."));
3521 runparams.nice = false;
3522 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
3526 string const error_type = (format == "program")
3527 ? "Build" : bufferFormat();
3528 ErrorList & error_list = d->errorLists[error_type];
3529 string const ext = formats.extension(format);
3530 FileName const tmp_result_file(changeExtension(filename, ext));
3531 bool const success = theConverters().convert(this, FileName(filename),
3532 tmp_result_file, FileName(absFileName()), backend_format, format,
3535 // Emit the signal to show the error list or copy it back to the
3536 // cloned Buffer so that it cab be emitted afterwards.
3537 if (format != backend_format) {
3538 if (d->cloned_buffer_) {
3539 d->cloned_buffer_->d->errorLists[error_type] =
3540 d->errorLists[error_type];
3543 // also to the children, in case of master-buffer-view
3544 ListOfBuffers clist = getDescendents();
3545 ListOfBuffers::const_iterator cit = clist.begin();
3546 ListOfBuffers::const_iterator const cen = clist.end();
3547 for (; cit != cen; ++cit) {
3548 if (d->cloned_buffer_) {
3549 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
3550 (*cit)->d->errorLists[error_type];
3552 (*cit)->errors(error_type, true);
3556 if (d->cloned_buffer_) {
3557 // Enable reverse dvi or pdf to work by copying back the texrow
3558 // object to the cloned buffer.
3559 // FIXME: There is a possibility of concurrent access to texrow
3560 // here from the main GUI thread that should be securized.
3561 d->cloned_buffer_->d->texrow = d->texrow;
3562 string const error_type = bufferFormat();
3563 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
3569 if (put_in_tempdir) {
3570 result_file = tmp_result_file.absFileName();
3574 result_file = changeExtension(d->exportFileName().absFileName(), ext);
3575 // We need to copy referenced files (e. g. included graphics
3576 // if format == "dvi") to the result dir.
3577 vector<ExportedFile> const files =
3578 runparams.exportdata->externalFiles(format);
3579 string const dest = onlyPath(result_file);
3580 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
3581 : force_overwrite == ALL_FILES;
3582 CopyStatus status = use_force ? FORCE : SUCCESS;
3584 vector<ExportedFile>::const_iterator it = files.begin();
3585 vector<ExportedFile>::const_iterator const en = files.end();
3586 for (; it != en && status != CANCEL; ++it) {
3587 string const fmt = formats.getFormatFromFile(it->sourceName);
3588 status = copyFile(fmt, it->sourceName,
3589 makeAbsPath(it->exportName, dest),
3590 it->exportName, status == FORCE);
3593 if (status == CANCEL) {
3594 message(_("Document export cancelled."));
3595 } else if (tmp_result_file.exists()) {
3596 // Finally copy the main file
3597 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
3598 : force_overwrite != NO_FILES;
3599 if (status == SUCCESS && use_force)
3601 status = copyFile(format, tmp_result_file,
3602 FileName(result_file), result_file,
3604 message(bformat(_("Document exported as %1$s "
3606 formats.prettyName(format),
3607 makeDisplayPath(result_file)));
3609 // This must be a dummy converter like fax (bug 1888)
3610 message(bformat(_("Document exported as %1$s"),
3611 formats.prettyName(format)));
3618 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3619 bool includeall) const
3622 // (1) export with all included children (omit \includeonly)
3623 if (includeall && !doExport(format, put_in_tempdir, true, result_file))
3625 // (2) export with included children only
3626 return doExport(format, put_in_tempdir, false, result_file);
3630 bool Buffer::preview(string const & format, bool includeall) const
3632 MarkAsExporting exporting(this);
3634 // (1) export with all included children (omit \includeonly)
3635 if (includeall && !doExport(format, true, true))
3637 // (2) export with included children only
3638 if (!doExport(format, true, false, result_file))
3640 return formats.view(*this, FileName(result_file), format);
3644 bool Buffer::isExportable(string const & format) const
3646 vector<string> backs = backends();
3647 for (vector<string>::const_iterator it = backs.begin();
3648 it != backs.end(); ++it)
3649 if (theConverters().isReachable(*it, format))
3655 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
3657 vector<string> const backs = backends();
3658 vector<Format const *> result =
3659 theConverters().getReachable(backs[0], only_viewable, true);
3660 for (vector<string>::const_iterator it = backs.begin() + 1;
3661 it != backs.end(); ++it) {
3662 vector<Format const *> r =
3663 theConverters().getReachable(*it, only_viewable, false);
3664 result.insert(result.end(), r.begin(), r.end());
3670 vector<string> Buffer::backends() const
3673 v.push_back(bufferFormat());
3674 // FIXME: Don't hardcode format names here, but use a flag
3675 if (v.back() == "latex") {
3676 v.push_back("pdflatex");
3677 v.push_back("luatex");
3678 v.push_back("xetex");
3679 } else if (v.back() == "xetex")
3680 v.push_back("luatex");
3681 v.push_back("xhtml");
3682 v.push_back("text");
3688 Buffer::ReadStatus Buffer::extractFromVC()
3690 bool const found = LyXVC::file_not_found_hook(d->filename);
3692 return ReadFileNotFound;
3693 if (!d->filename.isReadableFile())
3699 Buffer::ReadStatus Buffer::loadEmergency()
3701 FileName const emergencyFile = getEmergencyFileName();
3702 if (!emergencyFile.exists()
3703 || emergencyFile.lastModified() <= d->filename.lastModified())
3704 return ReadFileNotFound;
3706 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
3707 docstring const text = bformat(_("An emergency save of the document "
3708 "%1$s exists.\n\nRecover emergency save?"), file);
3710 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
3711 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
3717 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
3718 bool const success = (ret_llf == ReadSuccess);
3721 Alert::warning(_("File is read-only"),
3722 bformat(_("An emergency file is succesfully loaded, "
3723 "but the original file %1$s is marked read-only. "
3724 "Please make sure to save the document as a different "
3725 "file."), from_utf8(d->filename.absFileName())));
3728 str = _("Document was successfully recovered.");
3730 str = _("Document was NOT successfully recovered.");
3731 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3732 makeDisplayPath(emergencyFile.absFileName()));
3734 int const del_emerg =
3735 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3736 _("&Remove"), _("&Keep"));
3737 if (del_emerg == 0) {
3738 emergencyFile.removeFile();
3740 Alert::warning(_("Emergency file deleted"),
3741 _("Do not forget to save your file now!"), true);
3743 return success ? ReadSuccess : ReadEmergencyFailure;
3746 int const del_emerg =
3747 Alert::prompt(_("Delete emergency file?"),
3748 _("Remove emergency file now?"), 1, 1,
3749 _("&Remove"), _("&Keep"));
3751 emergencyFile.removeFile();
3752 return ReadOriginal;
3762 Buffer::ReadStatus Buffer::loadAutosave()
3764 // Now check if autosave file is newer.
3765 FileName const autosaveFile = getAutosaveFileName();
3766 if (!autosaveFile.exists()
3767 || autosaveFile.lastModified() <= d->filename.lastModified())
3768 return ReadFileNotFound;
3770 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
3771 docstring const text = bformat(_("The backup of the document %1$s "
3772 "is newer.\n\nLoad the backup instead?"), file);
3773 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
3774 _("&Load backup"), _("Load &original"), _("&Cancel"));
3779 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
3780 // the file is not saved if we load the autosave file.
3781 if (ret_llf == ReadSuccess) {
3783 Alert::warning(_("File is read-only"),
3784 bformat(_("A backup file is succesfully loaded, "
3785 "but the original file %1$s is marked read-only. "
3786 "Please make sure to save the document as a "
3788 from_utf8(d->filename.absFileName())));
3793 return ReadAutosaveFailure;
3796 // Here we delete the autosave
3797 autosaveFile.removeFile();
3798 return ReadOriginal;
3806 Buffer::ReadStatus Buffer::loadLyXFile()
3808 if (!d->filename.isReadableFile()) {
3809 ReadStatus const ret_rvc = extractFromVC();
3810 if (ret_rvc != ReadSuccess)
3814 ReadStatus const ret_re = loadEmergency();
3815 if (ret_re == ReadSuccess || ret_re == ReadCancel)
3818 ReadStatus const ret_ra = loadAutosave();
3819 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
3822 return loadThisLyXFile(d->filename);
3826 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
3828 return readFile(fn);
3832 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3834 TeXErrors::Errors::const_iterator cit = terr.begin();
3835 TeXErrors::Errors::const_iterator end = terr.end();
3837 for (; cit != end; ++cit) {
3840 int errorRow = cit->error_in_line;
3841 bool found = d->texrow.getIdFromRow(errorRow, id_start,
3847 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
3848 } while (found && id_start == id_end && pos_start == pos_end);
3850 errorList.push_back(ErrorItem(cit->error_desc,
3851 cit->error_text, id_start, pos_start, pos_end));
3856 void Buffer::setBuffersForInsets() const
3858 inset().setBuffer(const_cast<Buffer &>(*this));
3862 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
3864 // Use the master text class also for child documents
3865 Buffer const * const master = masterBuffer();
3866 DocumentClass const & textclass = master->params().documentClass();
3868 // do this only if we are the top-level Buffer
3870 checkIfBibInfoCacheIsValid();
3872 // keep the buffers to be children in this set. If the call from the
3873 // master comes back we can see which of them were actually seen (i.e.
3874 // via an InsetInclude). The remaining ones in the set need still be updated.
3875 static std::set<Buffer const *> bufToUpdate;
3876 if (scope == UpdateMaster) {
3877 // If this is a child document start with the master
3878 if (master != this) {
3879 bufToUpdate.insert(this);
3880 master->updateBuffer(UpdateMaster, utype);
3881 // Do this here in case the master has no gui associated with it. Then,
3882 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3883 if (!master->d->gui_)
3886 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3887 if (bufToUpdate.find(this) == bufToUpdate.end())
3891 // start over the counters in the master
3892 textclass.counters().reset();
3895 // update will be done below for this buffer
3896 bufToUpdate.erase(this);
3898 // update all caches
3899 clearReferenceCache();
3902 Buffer & cbuf = const_cast<Buffer &>(*this);
3904 LASSERT(!text().paragraphs().empty(), /**/);
3907 ParIterator parit = cbuf.par_iterator_begin();
3908 updateBuffer(parit, utype);
3911 // TocBackend update will be done later.
3914 cbuf.tocBackend().update();
3915 if (scope == UpdateMaster)
3916 cbuf.structureChanged();
3920 static depth_type getDepth(DocIterator const & it)
3922 depth_type depth = 0;
3923 for (size_t i = 0 ; i < it.depth() ; ++i)
3924 if (!it[i].inset().inMathed())
3925 depth += it[i].paragraph().getDepth() + 1;
3926 // remove 1 since the outer inset does not count
3930 static depth_type getItemDepth(ParIterator const & it)
3932 Paragraph const & par = *it;
3933 LabelType const labeltype = par.layout().labeltype;
3935 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3938 // this will hold the lowest depth encountered up to now.
3939 depth_type min_depth = getDepth(it);
3940 ParIterator prev_it = it;
3943 --prev_it.top().pit();
3945 // start of nested inset: go to outer par
3947 if (prev_it.empty()) {
3948 // start of document: nothing to do
3953 // We search for the first paragraph with same label
3954 // that is not more deeply nested.
3955 Paragraph & prev_par = *prev_it;
3956 depth_type const prev_depth = getDepth(prev_it);
3957 if (labeltype == prev_par.layout().labeltype) {
3958 if (prev_depth < min_depth)
3959 return prev_par.itemdepth + 1;
3960 if (prev_depth == min_depth)
3961 return prev_par.itemdepth;
3963 min_depth = min(min_depth, prev_depth);
3964 // small optimization: if we are at depth 0, we won't
3965 // find anything else
3966 if (prev_depth == 0)
3972 static bool needEnumCounterReset(ParIterator const & it)
3974 Paragraph const & par = *it;
3975 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3976 depth_type const cur_depth = par.getDepth();
3977 ParIterator prev_it = it;
3978 while (prev_it.pit()) {
3979 --prev_it.top().pit();
3980 Paragraph const & prev_par = *prev_it;
3981 if (prev_par.getDepth() <= cur_depth)
3982 return prev_par.layout().labeltype != LABEL_ENUMERATE;
3984 // start of nested inset: reset
3989 // set the label of a paragraph. This includes the counters.
3990 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
3992 BufferParams const & bp = owner_->masterBuffer()->params();
3993 DocumentClass const & textclass = bp.documentClass();
3994 Paragraph & par = it.paragraph();
3995 Layout const & layout = par.layout();
3996 Counters & counters = textclass.counters();
3998 if (par.params().startOfAppendix()) {
3999 // FIXME: only the counter corresponding to toplevel
4000 // sectioning should be reset
4002 counters.appendix(true);
4004 par.params().appendix(counters.appendix());
4006 // Compute the item depth of the paragraph
4007 par.itemdepth = getItemDepth(it);
4009 if (layout.margintype == MARGIN_MANUAL
4010 || layout.latextype == LATEX_BIB_ENVIRONMENT) {
4011 if (par.params().labelWidthString().empty())
4012 par.params().labelWidthString(par.expandLabel(layout, bp));
4014 par.params().labelWidthString(docstring());
4017 switch(layout.labeltype) {
4019 if (layout.toclevel <= bp.secnumdepth
4020 && (layout.latextype != LATEX_ENVIRONMENT
4021 || it.text()->isFirstInSequence(it.pit()))) {
4022 if (counters.hasCounter(layout.counter))
4023 counters.step(layout.counter, utype);
4024 par.params().labelString(par.expandLabel(layout, bp));
4026 par.params().labelString(docstring());
4029 case LABEL_ITEMIZE: {
4030 // At some point of time we should do something more
4031 // clever here, like:
4032 // par.params().labelString(
4033 // bp.user_defined_bullet(par.itemdepth).getText());
4034 // for now, use a simple hardcoded label
4035 docstring itemlabel;
4036 switch (par.itemdepth) {
4038 itemlabel = char_type(0x2022);
4041 itemlabel = char_type(0x2013);
4044 itemlabel = char_type(0x2217);
4047 itemlabel = char_type(0x2219); // or 0x00b7
4050 par.params().labelString(itemlabel);
4054 case LABEL_ENUMERATE: {
4055 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4057 switch (par.itemdepth) {
4066 enumcounter += "iv";
4069 // not a valid enumdepth...
4073 // Maybe we have to reset the enumeration counter.
4074 if (needEnumCounterReset(it))
4075 counters.reset(enumcounter);
4076 counters.step(enumcounter, utype);
4078 string const & lang = par.getParLanguage(bp)->code();
4079 par.params().labelString(counters.theCounter(enumcounter, lang));
4084 case LABEL_SENSITIVE: {
4085 string const & type = counters.current_float();
4086 docstring full_label;
4088 full_label = owner_->B_("Senseless!!! ");
4090 docstring name = owner_->B_(textclass.floats().getType(type).name());
4091 if (counters.hasCounter(from_utf8(type))) {
4092 string const & lang = par.getParLanguage(bp)->code();
4093 counters.step(from_utf8(type), utype);
4094 full_label = bformat(from_ascii("%1$s %2$s:"),
4096 counters.theCounter(from_utf8(type), lang));
4098 full_label = bformat(from_ascii("%1$s #:"), name);
4100 par.params().labelString(full_label);
4104 case LABEL_NO_LABEL:
4105 par.params().labelString(docstring());
4109 case LABEL_TOP_ENVIRONMENT:
4110 case LABEL_CENTERED_TOP_ENVIRONMENT:
4113 par.params().labelString(par.expandLabel(layout, bp));
4119 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4121 LASSERT(parit.pit() == 0, /**/);
4123 // Set the position of the text in the buffer to be able
4124 // to resolve macros in it.
4125 parit.text()->setMacrocontextPosition(parit);
4127 depth_type maxdepth = 0;
4128 pit_type const lastpit = parit.lastpit();
4129 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4130 // reduce depth if necessary
4131 parit->params().depth(min(parit->params().depth(), maxdepth));
4132 maxdepth = parit->getMaxDepthAfter();
4134 if (utype == OutputUpdate) {
4135 // track the active counters
4136 // we have to do this for the master buffer, since the local
4137 // buffer isn't tracking anything.
4138 masterBuffer()->params().documentClass().counters().
4139 setActiveLayout(parit->layout());
4142 // set the counter for this paragraph
4143 d->setLabel(parit, utype);
4146 InsetList::const_iterator iit = parit->insetList().begin();
4147 InsetList::const_iterator end = parit->insetList().end();
4148 for (; iit != end; ++iit) {
4149 parit.pos() = iit->pos;
4150 iit->inset->updateBuffer(parit, utype);
4156 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4157 WordLangTuple & word_lang, docstring_list & suggestions) const
4161 suggestions.clear();
4162 word_lang = WordLangTuple();
4163 // OK, we start from here.
4164 DocIterator const end = doc_iterator_end(this);
4165 for (; from != end; from.forwardPos()) {
4166 // We are only interested in text so remove the math CursorSlice.
4167 while (from.inMathed()) {
4171 // If from is at the end of the document (which is possible
4172 // when leaving the mathed) LyX will crash later.
4176 from.paragraph().spellCheck();
4177 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4178 if (SpellChecker::misspelled(res)) {
4183 // Do not increase progress when from == to, otherwise the word
4184 // count will be wrong.
4194 Buffer::ReadStatus Buffer::reload()
4197 // c.f. bug http://www.lyx.org/trac/ticket/6587
4198 removeAutosaveFile();
4199 // e.g., read-only status could have changed due to version control
4200 d->filename.refresh();
4201 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4203 ReadStatus const status = loadLyXFile();
4204 if (status == ReadSuccess) {
4209 message(bformat(_("Document %1$s reloaded."), disp_fn));
4211 message(bformat(_("Could not reload document %1$s."), disp_fn));
4221 bool Buffer::saveAs(FileName const & fn)
4223 FileName const old_name = fileName();
4224 FileName const old_auto = getAutosaveFileName();
4225 bool const old_unnamed = isUnnamed();
4232 // bring the autosave file with us, just in case.
4233 moveAutosaveFile(old_auto);
4234 // validate version control data and
4235 // correct buffer title
4236 lyxvc().file_found_hook(fileName());
4238 // the file has now been saved to the new location.
4239 // we need to check that the locations of child buffers
4241 checkChildBuffers();
4245 // reset the old filename and unnamed state
4246 setFileName(old_name);
4247 setUnnamed(old_unnamed);
4253 // FIXME We could do better here, but it is complicated. What would be
4254 // nice is to offer either (a) to save the child buffer to an appropriate
4255 // location, so that it would "move with the master", or else (b) to update
4256 // the InsetInclude so that it pointed to the same file. But (a) is a bit
4257 // complicated, because the code for this lives in GuiView.
4258 void Buffer::checkChildBuffers()
4260 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4261 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4262 for (; it != en; ++it) {
4263 DocIterator dit = it->second;
4264 Buffer * cbuf = const_cast<Buffer *>(it->first);
4265 if (!cbuf || !theBufferList().isLoaded(cbuf))
4267 Inset * inset = dit.nextInset();
4268 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4269 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4270 docstring const & incfile = inset_inc->getParam("filename");
4271 string oldloc = cbuf->absFileName();
4272 string newloc = makeAbsPath(to_utf8(incfile),
4273 onlyPath(absFileName())).absFileName();
4274 if (oldloc == newloc)
4276 // the location of the child file is incorrect.
4277 Alert::warning(_("Included File Invalid"),
4278 bformat(_("Saving this document to a new location has made the file:\n"
4280 "inaccessible. You will need to update the included filename."),
4281 from_utf8(oldloc)));
4283 inset_inc->setChildBuffer(0);
4285 // invalidate cache of children
4286 d->children_positions.clear();
4287 d->position_to_children.clear();