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 "graphics/PreviewLoader.h"
82 #include "frontends/alert.h"
83 #include "frontends/Delegates.h"
84 #include "frontends/WorkAreaManager.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;
120 using namespace lyx::graphics;
124 namespace Alert = frontend::Alert;
125 namespace os = support::os;
129 int const LYX_FORMAT = LYX_FORMAT_LYX;
131 typedef map<string, bool> DepClean;
132 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
134 void showPrintError(string const & name)
136 docstring str = bformat(_("Could not print the document %1$s.\n"
137 "Check that your printer is set up correctly."),
138 makeDisplayPath(name, 50));
139 Alert::error(_("Print document failed"), str);
148 Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
152 delete preview_loader_;
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_;
260 /// Indicates whether the bibinfo has changed since the last time
261 /// we ran updateBuffer(), i.e., whether citation labels may need
263 mutable bool cite_labels_valid_;
265 mutable RefCache ref_cache_;
267 /// our Text that should be wrapped in an InsetText
271 PreviewLoader * preview_loader_;
273 /// This is here to force the test to be done whenever parent_buffer
275 Buffer const * parent() const {
276 // if parent_buffer is not loaded, then it has been unloaded,
277 // which means that parent_buffer is an invalid pointer. So we
278 // set it to null in that case.
279 // however, the BufferList doesn't know about cloned buffers, so
280 // they will always be regarded as unloaded. in that case, we hope
282 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
284 return parent_buffer;
288 void setParent(Buffer const * pb) {
289 if (parent_buffer == pb)
292 if (!cloned_buffer_ && parent_buffer && pb)
293 LYXERR0("Warning: a buffer should not have two parents!");
295 if (!cloned_buffer_ && parent_buffer) {
296 parent_buffer->invalidateBibfileCache();
297 parent_buffer->invalidateBibinfoCache();
301 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
302 /// This one is useful for preview detached in a thread.
303 Buffer const * cloned_buffer_;
304 /// are we in the process of exporting this buffer?
305 mutable bool doing_export;
308 /// So we can force access via the accessors.
309 mutable Buffer const * parent_buffer;
314 /// Creates the per buffer temporary directory
315 static FileName createBufferTmpDir()
318 // We are in our own directory. Why bother to mangle name?
319 // In fact I wrote this code to circumvent a problematic behaviour
320 // (bug?) of EMX mkstemp().
321 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
322 convert<string>(count++));
324 if (!tmpfl.createDirectory(0777)) {
325 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
326 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
327 from_utf8(tmpfl.absFileName())));
333 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
334 Buffer const * cloned_buffer)
335 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
336 read_only(readonly_), filename(file), file_fully_loaded(false),
337 toc_backend(owner), macro_lock(false), timestamp_(0), checksum_(0),
338 wa_(0), gui_(0), undo_(*owner), bibinfo_cache_valid_(false),
339 bibfile_cache_valid_(false), cite_labels_valid_(false),
340 preview_loader_(0), cloned_buffer_(cloned_buffer),
341 doing_export(false), parent_buffer(0)
343 if (!cloned_buffer_) {
344 temppath = createBufferTmpDir();
345 lyxvc.setBuffer(owner_);
347 wa_ = new frontend::WorkAreaManager;
350 temppath = cloned_buffer_->d->temppath;
351 file_fully_loaded = true;
352 params = cloned_buffer_->d->params;
353 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
354 bibinfo_ = cloned_buffer_->d->bibinfo_;
355 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
356 bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
357 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
358 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
362 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
363 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
365 LYXERR(Debug::INFO, "Buffer::Buffer()");
367 d->inset = new InsetText(*cloned_buffer->d->inset);
368 d->inset->setBuffer(*this);
369 // FIXME: optimize this loop somewhat, maybe by creating a new
370 // general recursive Inset::setId().
371 DocIterator it = doc_iterator_begin(this);
372 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
373 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
374 it.paragraph().setId(cloned_it.paragraph().id());
376 d->inset = new InsetText(this);
377 d->inset->setAutoBreakRows(true);
378 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
384 LYXERR(Debug::INFO, "Buffer::~Buffer()");
385 // here the buffer should take care that it is
386 // saved properly, before it goes into the void.
388 // GuiView already destroyed
392 // No need to do additional cleanups for internal buffer.
397 // loop over children
398 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
399 Impl::BufferPositionMap::iterator end = d->children_positions.end();
400 for (; it != end; ++it) {
401 Buffer * child = const_cast<Buffer *>(it->first);
402 if (d->cloned_buffer_)
404 // The child buffer might have been closed already.
405 else if (theBufferList().isLoaded(child))
406 theBufferList().releaseChild(this, child);
410 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
411 msg += emergencyWrite();
412 Alert::warning(_("Attempting to close changed document!"), msg);
415 // clear references to children in macro tables
416 d->children_positions.clear();
417 d->position_to_children.clear();
419 if (!d->cloned_buffer_ && !d->temppath.destroyDirectory()) {
420 Alert::warning(_("Could not remove temporary directory"),
421 bformat(_("Could not remove the temporary directory %1$s"),
422 from_utf8(d->temppath.absFileName())));
432 Buffer * Buffer::clone() const
435 masterBuffer()->clone(bufmap);
436 BufferMap::iterator it = bufmap.find(this);
437 LASSERT(it != bufmap.end(), return 0);
442 void Buffer::clone(BufferMap & bufmap) const
444 // have we already been cloned?
445 if (bufmap.find(this) != bufmap.end())
448 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
449 bufmap[this] = buffer_clone;
450 buffer_clone->d->macro_lock = true;
451 buffer_clone->d->children_positions.clear();
452 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
453 // math macro caches need to be rethought and simplified.
454 // I am not sure wether we should handle Buffer cloning here or in BufferList.
455 // Right now BufferList knows nothing about buffer clones.
456 Impl::PositionScopeBufferMap::iterator it = d->position_to_children.begin();
457 Impl::PositionScopeBufferMap::iterator end = d->position_to_children.end();
458 for (; it != end; ++it) {
459 DocIterator dit = it->first.clone(buffer_clone);
460 dit.setBuffer(buffer_clone);
461 Buffer * child = const_cast<Buffer *>(it->second.second);
463 child->clone(bufmap);
464 BufferMap::iterator const bit = bufmap.find(child);
465 LASSERT(bit != bufmap.end(), continue);
466 Buffer * child_clone = bit->second;
468 Inset * inset = dit.nextInset();
469 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
470 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
471 inset_inc->setChildBuffer(child_clone);
472 child_clone->d->setParent(buffer_clone);
473 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
474 buffer_clone->setChild(dit, child_clone);
476 buffer_clone->d->macro_lock = false;
481 bool Buffer::isClone() const
483 return d->cloned_buffer_;
487 void Buffer::changed(bool update_metrics) const
490 d->wa_->redrawAll(update_metrics);
494 frontend::WorkAreaManager & Buffer::workAreaManager() const
496 LASSERT(d->wa_, /**/);
501 Text & Buffer::text() const
503 return d->inset->text();
507 Inset & Buffer::inset() const
513 BufferParams & Buffer::params()
519 BufferParams const & Buffer::params() const
525 ParagraphList & Buffer::paragraphs()
527 return text().paragraphs();
531 ParagraphList const & Buffer::paragraphs() const
533 return text().paragraphs();
537 LyXVC & Buffer::lyxvc()
543 LyXVC const & Buffer::lyxvc() const
549 string const Buffer::temppath() const
551 return d->temppath.absFileName();
555 TexRow & Buffer::texrow()
561 TexRow const & Buffer::texrow() const
567 TocBackend & Buffer::tocBackend() const
569 return d->toc_backend;
573 Undo & Buffer::undo()
579 void Buffer::setChild(DocIterator const & dit, Buffer * child)
581 d->children_positions[child] = dit;
585 string Buffer::latexName(bool const no_path) const
587 FileName latex_name =
588 makeLatexName(d->exportFileName());
589 return no_path ? latex_name.onlyFileName()
590 : latex_name.absFileName();
594 FileName Buffer::Impl::exportFileName() const
596 docstring const branch_suffix =
597 params.branchlist().getFileNameSuffix();
598 if (branch_suffix.empty())
601 string const name = filename.onlyFileNameWithoutExt()
602 + to_utf8(branch_suffix);
603 FileName res(filename.onlyPath().absFileName() + "/" + name);
604 res.changeExtension(filename.extension());
610 string Buffer::logName(LogType * type) const
612 string const filename = latexName(false);
614 if (filename.empty()) {
620 string const path = temppath();
622 FileName const fname(addName(temppath(),
623 onlyFileName(changeExtension(filename,
626 // FIXME: how do we know this is the name of the build log?
627 FileName const bname(
628 addName(path, onlyFileName(
629 changeExtension(filename,
630 formats.extension(params().bufferFormat()) + ".out"))));
632 // Also consider the master buffer log file
633 FileName masterfname = fname;
635 if (masterBuffer() != this) {
636 string const mlogfile = masterBuffer()->logName(&mtype);
637 masterfname = FileName(mlogfile);
640 // If no Latex log or Build log is newer, show Build log
641 if (bname.exists() &&
642 ((!fname.exists() && !masterfname.exists())
643 || (fname.lastModified() < bname.lastModified()
644 && masterfname.lastModified() < bname.lastModified()))) {
645 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
648 return bname.absFileName();
649 // If we have a newer master file log or only a master log, show this
650 } else if (fname != masterfname
651 && (!fname.exists() && (masterfname.exists()
652 || fname.lastModified() < masterfname.lastModified()))) {
653 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
656 return masterfname.absFileName();
658 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
661 return fname.absFileName();
665 void Buffer::setReadonly(bool const flag)
667 if (d->read_only != flag) {
674 void Buffer::setFileName(FileName const & fname)
677 setReadonly(d->filename.isReadOnly());
683 int Buffer::readHeader(Lexer & lex)
685 int unknown_tokens = 0;
687 int begin_header_line = -1;
689 // Initialize parameters that may be/go lacking in header:
690 params().branchlist().clear();
691 params().preamble.erase();
692 params().options.erase();
693 params().master.erase();
694 params().float_placement.erase();
695 params().paperwidth.erase();
696 params().paperheight.erase();
697 params().leftmargin.erase();
698 params().rightmargin.erase();
699 params().topmargin.erase();
700 params().bottommargin.erase();
701 params().headheight.erase();
702 params().headsep.erase();
703 params().footskip.erase();
704 params().columnsep.erase();
705 params().fonts_cjk.erase();
706 params().listings_params.clear();
707 params().clearLayoutModules();
708 params().clearRemovedModules();
709 params().clearIncludedChildren();
710 params().pdfoptions().clear();
711 params().indiceslist().clear();
712 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
713 params().isbackgroundcolor = false;
714 params().fontcolor = RGBColor(0, 0, 0);
715 params().isfontcolor = false;
716 params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
717 params().boxbgcolor = RGBColor(0xFF, 0, 0);
718 params().html_latex_start.clear();
719 params().html_latex_end.clear();
720 params().html_math_img_scale = 1.0;
721 params().output_sync_macro.erase();
723 for (int i = 0; i < 4; ++i) {
724 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
725 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
728 ErrorList & errorList = d->errorLists["Parse"];
737 if (token == "\\end_header")
741 if (token == "\\begin_header") {
742 begin_header_line = line;
746 LYXERR(Debug::PARSER, "Handling document header token: `"
749 string unknown = params().readToken(lex, token, d->filename.onlyPath());
750 if (!unknown.empty()) {
751 if (unknown[0] != '\\' && token == "\\textclass") {
752 Alert::warning(_("Unknown document class"),
753 bformat(_("Using the default document class, because the "
754 "class %1$s is unknown."), from_utf8(unknown)));
757 docstring const s = bformat(_("Unknown token: "
761 errorList.push_back(ErrorItem(_("Document header error"),
766 if (begin_header_line) {
767 docstring const s = _("\\begin_header is missing");
768 errorList.push_back(ErrorItem(_("Document header error"),
772 params().makeDocumentClass();
774 return unknown_tokens;
779 // changed to be public and have one parameter
780 // Returns true if "\end_document" is not read (Asger)
781 bool Buffer::readDocument(Lexer & lex)
783 ErrorList & errorList = d->errorLists["Parse"];
786 // remove dummy empty par
787 paragraphs().clear();
789 if (!lex.checkFor("\\begin_document")) {
790 docstring const s = _("\\begin_document is missing");
791 errorList.push_back(ErrorItem(_("Document header error"),
797 if (params().outputChanges) {
798 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
799 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
800 LaTeXFeatures::isAvailable("xcolor");
802 if (!dvipost && !xcolorulem) {
803 Alert::warning(_("Changes not shown in LaTeX output"),
804 _("Changes will not be highlighted in LaTeX output, "
805 "because neither dvipost nor xcolor/ulem are installed.\n"
806 "Please install these packages or redefine "
807 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
808 } else if (!xcolorulem) {
809 Alert::warning(_("Changes not shown in LaTeX output"),
810 _("Changes will not be highlighted in LaTeX output "
811 "when using pdflatex, because xcolor and ulem are not installed.\n"
812 "Please install both packages or redefine "
813 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
817 if (!params().master.empty()) {
818 FileName const master_file = makeAbsPath(params().master,
819 onlyPath(absFileName()));
820 if (isLyXFileName(master_file.absFileName())) {
822 checkAndLoadLyXFile(master_file, true);
824 // necessary e.g. after a reload
825 // to re-register the child (bug 5873)
826 // FIXME: clean up updateMacros (here, only
827 // child registering is needed).
828 master->updateMacros();
829 // set master as master buffer, but only
830 // if we are a real child
831 if (master->isChild(this))
833 // if the master is not fully loaded
834 // it is probably just loading this
835 // child. No warning needed then.
836 else if (master->isFullyLoaded())
837 LYXERR0("The master '"
839 << "' assigned to this document ("
841 << ") does not include "
842 "this document. Ignoring the master assignment.");
847 // assure we have a default index
848 params().indiceslist().addDefault(B_("Index"));
851 bool const res = text().read(lex, errorList, d->inset);
853 // inform parent buffer about local macros
855 Buffer const * pbuf = parent();
856 UserMacroSet::const_iterator cit = usermacros.begin();
857 UserMacroSet::const_iterator end = usermacros.end();
858 for (; cit != end; ++cit)
859 pbuf->usermacros.insert(*cit);
863 updateMacroInstances(InternalUpdate);
868 bool Buffer::readString(string const & s)
870 params().compressed = false;
875 FileName const fn = FileName::tempName("Buffer_readString");
878 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
879 if (ret_plf != ReadSuccess)
882 if (file_format != LYX_FORMAT) {
883 // We need to call lyx2lyx, so write the input to a file
884 ofstream os(fn.toFilesystemEncoding().c_str());
888 return readFile(fn) == ReadSuccess;
891 if (readDocument(lex))
897 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
901 if (!lex.setFile(fname)) {
902 Alert::error(_("File Not Found"),
903 bformat(_("Unable to open file `%1$s'."),
904 from_utf8(fn.absFileName())));
905 return ReadFileNotFound;
909 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
910 if (ret_plf != ReadSuccess)
913 if (file_format != LYX_FORMAT) {
915 ReadStatus const ret_clf = convertLyXFormat(fn, tmpFile, file_format);
916 if (ret_clf != ReadSuccess)
918 return readFile(tmpFile);
921 // FIXME: InsetInfo needs to know whether the file is under VCS
922 // during the parse process, so this has to be done before.
923 lyxvc().file_found_hook(d->filename);
925 if (readDocument(lex)) {
926 Alert::error(_("Document format failure"),
927 bformat(_("%1$s ended unexpectedly, which means"
928 " that it is probably corrupted."),
929 from_utf8(fn.absFileName())));
930 return ReadDocumentFailure;
933 d->file_fully_loaded = true;
934 d->read_only = !d->filename.isWritable();
935 params().compressed = d->filename.isZippedFile();
941 bool Buffer::isFullyLoaded() const
943 return d->file_fully_loaded;
947 void Buffer::setFullyLoaded(bool value)
949 d->file_fully_loaded = value;
953 PreviewLoader * Buffer::loader() const
955 if (lyxrc.preview == LyXRC::PREVIEW_OFF)
957 if (!d->preview_loader_)
958 d->preview_loader_ = new PreviewLoader(*this);
959 return d->preview_loader_;
963 void Buffer::removePreviews() const
965 delete d->preview_loader_;
966 d->preview_loader_ = 0;
970 void Buffer::updatePreviews() const
972 PreviewLoader * ploader = loader();
976 InsetIterator it = inset_iterator_begin(*d->inset);
977 InsetIterator const end = inset_iterator_end(*d->inset);
978 for (; it != end; ++it)
979 it->addPreview(it, *ploader);
981 ploader->startLoading();
985 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
986 FileName const & fn, int & file_format) const
988 if(!lex.checkFor("\\lyxformat")) {
989 Alert::error(_("Document format failure"),
990 bformat(_("%1$s is not a readable LyX document."),
991 from_utf8(fn.absFileName())));
992 return ReadNoLyXFormat;
998 // LyX formats 217 and earlier were written as 2.17. This corresponds
999 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1000 // these cases. See also: www.lyx.org/trac/changeset/1313.
1001 size_t dot = tmp_format.find_first_of(".,");
1002 if (dot != string::npos)
1003 tmp_format.erase(dot, 1);
1005 file_format = convert<int>(tmp_format);
1010 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1011 FileName & tmpfile, int from_format)
1013 tmpfile = FileName::tempName("Buffer_convertLyXFormat");
1014 if(tmpfile.empty()) {
1015 Alert::error(_("Conversion failed"),
1016 bformat(_("%1$s is from a different"
1017 " version of LyX, but a temporary"
1018 " file for converting it could"
1019 " not be created."),
1020 from_utf8(fn.absFileName())));
1021 return LyX2LyXNoTempFile;
1024 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1025 if (lyx2lyx.empty()) {
1026 Alert::error(_("Conversion script not found"),
1027 bformat(_("%1$s is from a different"
1028 " version of LyX, but the"
1029 " conversion script lyx2lyx"
1030 " could not be found."),
1031 from_utf8(fn.absFileName())));
1032 return LyX2LyXNotFound;
1036 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1037 ostringstream command;
1038 command << os::python()
1039 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1040 << " -t " << convert<string>(LYX_FORMAT)
1041 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
1042 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1043 string const command_str = command.str();
1045 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1047 cmd_ret const ret = runCommand(command_str);
1048 if (ret.first != 0) {
1049 if (from_format < LYX_FORMAT) {
1050 Alert::error(_("Conversion script failed"),
1051 bformat(_("%1$s is from an older version"
1052 " of LyX and the lyx2lyx script"
1053 " failed to convert it."),
1054 from_utf8(fn.absFileName())));
1055 return LyX2LyXOlderFormat;
1057 Alert::error(_("Conversion script failed"),
1058 bformat(_("%1$s is from a newer version"
1059 " of LyX and the lyx2lyx script"
1060 " failed to convert it."),
1061 from_utf8(fn.absFileName())));
1062 return LyX2LyXNewerFormat;
1069 // Should probably be moved to somewhere else: BufferView? GuiView?
1070 bool Buffer::save() const
1072 docstring const file = makeDisplayPath(absFileName(), 20);
1073 d->filename.refresh();
1075 // check the read-only status before moving the file as a backup
1076 if (d->filename.exists()) {
1077 bool const read_only = !d->filename.isWritable();
1079 Alert::warning(_("File is read-only"),
1080 bformat(_("The file %1$s cannot be written because it "
1081 "is marked as read-only."), file));
1086 // ask if the disk file has been externally modified (use checksum method)
1087 if (fileName().exists() && isExternallyModified(checksum_method)) {
1089 bformat(_("Document %1$s has been externally modified. "
1090 "Are you sure you want to overwrite this file?"), file);
1091 int const ret = Alert::prompt(_("Overwrite modified file?"),
1092 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1097 // We don't need autosaves in the immediate future. (Asger)
1098 resetAutosaveTimers();
1100 FileName backupName;
1101 bool madeBackup = false;
1103 // make a backup if the file already exists
1104 if (lyxrc.make_backup && fileName().exists()) {
1105 backupName = FileName(absFileName() + '~');
1106 if (!lyxrc.backupdir_path.empty()) {
1107 string const mangledName =
1108 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1109 backupName = FileName(addName(lyxrc.backupdir_path,
1113 // Except file is symlink do not copy because of #6587.
1114 // Hard links have bad luck.
1115 if (fileName().isSymLink())
1116 madeBackup = fileName().copyTo(backupName);
1118 madeBackup = fileName().moveTo(backupName);
1121 Alert::error(_("Backup failure"),
1122 bformat(_("Cannot create backup file %1$s.\n"
1123 "Please check whether the directory exists and is writable."),
1124 from_utf8(backupName.absFileName())));
1125 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1129 if (writeFile(d->filename)) {
1133 // Saving failed, so backup is not backup
1135 backupName.moveTo(d->filename);
1141 bool Buffer::writeFile(FileName const & fname) const
1143 // FIXME Do we need to do these here? I don't think writing
1144 // the LyX file depends upon it. (RGH)
1146 // updateMacroInstances();
1148 if (d->read_only && fname == d->filename)
1151 bool retval = false;
1153 docstring const str = bformat(_("Saving document %1$s..."),
1154 makeDisplayPath(fname.absFileName()));
1157 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1159 if (params().compressed) {
1160 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1161 retval = ofs && write(ofs);
1163 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1164 retval = ofs && write(ofs);
1168 message(str + _(" could not write file!"));
1173 // removeAutosaveFile();
1176 message(str + _(" done."));
1182 docstring Buffer::emergencyWrite()
1184 // No need to save if the buffer has not changed.
1188 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1190 docstring user_message = bformat(
1191 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1193 // We try to save three places:
1194 // 1) Same place as document. Unless it is an unnamed doc.
1196 string s = absFileName();
1199 if (writeFile(FileName(s))) {
1201 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1202 return user_message;
1204 user_message += " " + _("Save failed! Trying again...\n");
1208 // 2) In HOME directory.
1209 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1211 lyxerr << ' ' << s << endl;
1212 if (writeFile(FileName(s))) {
1214 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1215 return user_message;
1218 user_message += " " + _("Save failed! Trying yet again...\n");
1220 // 3) In "/tmp" directory.
1221 // MakeAbsPath to prepend the current
1222 // drive letter on OS/2
1223 s = addName(package().temp_dir().absFileName(), absFileName());
1225 lyxerr << ' ' << s << endl;
1226 if (writeFile(FileName(s))) {
1228 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1229 return user_message;
1232 user_message += " " + _("Save failed! Bummer. Document is lost.");
1235 return user_message;
1239 bool Buffer::write(ostream & ofs) const
1242 // Use the standard "C" locale for file output.
1243 ofs.imbue(locale::classic());
1246 // The top of the file should not be written by params().
1248 // write out a comment in the top of the file
1249 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1250 << " created this file. For more info see http://www.lyx.org/\n"
1251 << "\\lyxformat " << LYX_FORMAT << "\n"
1252 << "\\begin_document\n";
1254 /// For each author, set 'used' to true if there is a change
1255 /// by this author in the document; otherwise set it to 'false'.
1256 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1257 AuthorList::Authors::const_iterator a_end = params().authors().end();
1258 for (; a_it != a_end; ++a_it)
1259 a_it->setUsed(false);
1261 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1262 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1263 for ( ; it != end; ++it)
1264 it->checkAuthors(params().authors());
1266 // now write out the buffer parameters.
1267 ofs << "\\begin_header\n";
1268 params().writeFile(ofs);
1269 ofs << "\\end_header\n";
1272 ofs << "\n\\begin_body\n";
1274 ofs << "\n\\end_body\n";
1276 // Write marker that shows file is complete
1277 ofs << "\\end_document" << endl;
1279 // Shouldn't really be needed....
1282 // how to check if close went ok?
1283 // Following is an attempt... (BE 20001011)
1285 // good() returns false if any error occured, including some
1286 // formatting error.
1287 // bad() returns true if something bad happened in the buffer,
1288 // which should include file system full errors.
1293 lyxerr << "File was not closed properly." << endl;
1300 bool Buffer::makeLaTeXFile(FileName const & fname,
1301 string const & original_path,
1302 OutputParams const & runparams_in,
1303 bool output_preamble, bool output_body) const
1305 OutputParams runparams = runparams_in;
1307 // This is necessary for LuaTeX/XeTeX with tex fonts.
1308 // See FIXME in BufferParams::encoding()
1309 if (runparams.isFullUnicode())
1310 runparams.encoding = encodings.fromLyXName("utf8-plain");
1312 string const encoding = runparams.encoding->iconvName();
1313 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1316 try { ofs.reset(encoding); }
1317 catch (iconv_codecvt_facet_exception & e) {
1318 lyxerr << "Caught iconv exception: " << e.what() << endl;
1319 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1320 "verify that the support software for your encoding (%1$s) is "
1321 "properly installed"), from_ascii(encoding)));
1324 if (!openFileWrite(ofs, fname))
1327 //TexStream ts(ofs.rdbuf(), &texrow());
1328 ErrorList & errorList = d->errorLists["Export"];
1330 bool failed_export = false;
1331 otexstream os(ofs, d->texrow);
1333 // make sure we are ready to export
1334 // this needs to be done before we validate
1335 // FIXME Do we need to do this all the time? I.e., in children
1336 // of a master we are exporting?
1338 updateMacroInstances(OutputUpdate);
1341 os.texrow().reset();
1342 writeLaTeXSource(os, original_path,
1343 runparams, output_preamble, output_body);
1345 catch (EncodingException & e) {
1346 odocstringstream ods;
1347 ods.put(e.failed_char);
1349 oss << "0x" << hex << e.failed_char << dec;
1350 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1351 " (code point %2$s)"),
1352 ods.str(), from_utf8(oss.str()));
1353 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1354 "representable in the chosen encoding.\n"
1355 "Changing the document encoding to utf8 could help."),
1356 e.par_id, e.pos, e.pos + 1));
1357 failed_export = true;
1359 catch (iconv_codecvt_facet_exception & e) {
1360 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1361 _(e.what()), -1, 0, 0));
1362 failed_export = true;
1364 catch (exception const & e) {
1365 errorList.push_back(ErrorItem(_("conversion failed"),
1366 _(e.what()), -1, 0, 0));
1367 failed_export = true;
1370 lyxerr << "Caught some really weird exception..." << endl;
1376 failed_export = true;
1377 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1381 return !failed_export;
1385 void Buffer::writeLaTeXSource(otexstream & os,
1386 string const & original_path,
1387 OutputParams const & runparams_in,
1388 bool const output_preamble, bool const output_body) const
1390 // The child documents, if any, shall be already loaded at this point.
1392 OutputParams runparams = runparams_in;
1394 // Classify the unicode characters appearing in math insets
1395 Encodings::initUnicodeMath(*this);
1397 // validate the buffer.
1398 LYXERR(Debug::LATEX, " Validating buffer...");
1399 LaTeXFeatures features(*this, params(), runparams);
1401 LYXERR(Debug::LATEX, " Buffer validation done.");
1403 // The starting paragraph of the coming rows is the
1404 // first paragraph of the document. (Asger)
1405 if (output_preamble && runparams.nice) {
1406 os << "%% LyX " << lyx_version << " created this file. "
1407 "For more info, see http://www.lyx.org/.\n"
1408 "%% Do not edit unless you really know what "
1411 LYXERR(Debug::INFO, "lyx document header finished");
1413 // There are a few differences between nice LaTeX and usual files:
1414 // usual files have \batchmode and special input@path to allow
1415 // inclusion of figures specified by an explicitly relative path
1416 // (i.e., a path starting with './' or '../') with either \input or
1417 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1418 // input@path is set when the actual parameter original_path is set.
1419 // This is done for usual tex-file, but not for nice-latex-file.
1420 // (Matthias 250696)
1421 // Note that input@path is only needed for something the user does
1422 // in the preamble, included .tex files or ERT, files included by
1423 // LyX work without it.
1424 if (output_preamble) {
1425 if (!runparams.nice) {
1426 // code for usual, NOT nice-latex-file
1427 os << "\\batchmode\n"; // changed from \nonstopmode
1429 if (!original_path.empty()) {
1431 // We don't know the encoding of inputpath
1432 docstring const inputpath = from_utf8(original_path);
1433 docstring uncodable_glyphs;
1434 Encoding const * const enc = runparams.encoding;
1436 for (size_t n = 0; n < inputpath.size(); ++n) {
1437 docstring const glyph =
1438 docstring(1, inputpath[n]);
1439 if (enc->latexChar(inputpath[n], true) != glyph) {
1440 LYXERR0("Uncodable character '"
1442 << "' in input path!");
1443 uncodable_glyphs += glyph;
1448 // warn user if we found uncodable glyphs.
1449 if (!uncodable_glyphs.empty()) {
1450 frontend::Alert::warning(
1451 _("Uncodable character in file path"),
1453 _("The path of your document\n"
1455 "contains glyphs that are unknown "
1456 "in the current document encoding "
1457 "(namely %2$s). This may result in "
1458 "incomplete output, unless "
1459 "TEXINPUTS contains the document "
1460 "directory and you don't use "
1461 "explicitly relative paths (i.e., "
1462 "paths starting with './' or "
1463 "'../') in the preamble or in ERT."
1464 "\n\nIn case of problems, choose "
1465 "an appropriate document encoding\n"
1466 "(such as utf8) or change the "
1468 inputpath, uncodable_glyphs));
1471 support::latex_path(original_path);
1472 if (contains(docdir, '#')) {
1473 docdir = subst(docdir, "#", "\\#");
1474 os << "\\catcode`\\#=11"
1475 "\\def\\#{#}\\catcode`\\#=6\n";
1477 if (contains(docdir, '%')) {
1478 docdir = subst(docdir, "%", "\\%");
1479 os << "\\catcode`\\%=11"
1480 "\\def\\%{%}\\catcode`\\%=14\n";
1482 os << "\\makeatletter\n"
1483 << "\\def\\input@path{{"
1484 << docdir << "/}}\n"
1485 << "\\makeatother\n";
1489 // get parent macros (if this buffer has a parent) which will be
1490 // written at the document begin further down.
1491 MacroSet parentMacros;
1492 listParentMacros(parentMacros, features);
1494 runparams.use_polyglossia = features.usePolyglossia();
1495 // Write the preamble
1496 runparams.use_babel = params().writeLaTeX(os, features,
1497 d->filename.onlyPath());
1499 runparams.use_japanese = features.isRequired("japanese");
1505 os << "\\begin{document}\n";
1507 // output the parent macros
1508 MacroSet::iterator it = parentMacros.begin();
1509 MacroSet::iterator end = parentMacros.end();
1510 for (; it != end; ++it) {
1511 int num_lines = (*it)->write(os.os(), true);
1512 os.texrow().newlines(num_lines);
1515 } // output_preamble
1517 os.texrow().start(paragraphs().begin()->id(), 0);
1519 LYXERR(Debug::INFO, "preamble finished, now the body.");
1521 // if we are doing a real file with body, even if this is the
1522 // child of some other buffer, let's cut the link here.
1523 // This happens for example if only a child document is printed.
1524 Buffer const * save_parent = 0;
1525 if (output_preamble) {
1526 save_parent = d->parent();
1531 latexParagraphs(*this, text(), os, runparams);
1533 // Restore the parenthood if needed
1534 if (output_preamble)
1535 d->setParent(save_parent);
1537 // add this just in case after all the paragraphs
1540 if (output_preamble) {
1541 os << "\\end{document}\n";
1542 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1544 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1546 runparams_in.encoding = runparams.encoding;
1548 // Just to be sure. (Asger)
1549 os.texrow().newline();
1551 //for (int i = 0; i<d->texrow.rows(); i++) {
1553 // if (d->texrow.getIdFromRow(i+1,id,pos) && id>0)
1554 // lyxerr << i+1 << ":" << id << ":" << getParFromID(id).paragraph().asString()<<"\n";
1557 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1558 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
1562 void Buffer::makeDocBookFile(FileName const & fname,
1563 OutputParams const & runparams,
1564 bool const body_only) const
1566 LYXERR(Debug::LATEX, "makeDocBookFile...");
1569 if (!openFileWrite(ofs, fname))
1572 // make sure we are ready to export
1573 // this needs to be done before we validate
1575 updateMacroInstances(OutputUpdate);
1577 writeDocBookSource(ofs, fname.absFileName(), runparams, body_only);
1581 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1585 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1586 OutputParams const & runparams,
1587 bool const only_body) const
1589 LaTeXFeatures features(*this, params(), runparams);
1594 DocumentClass const & tclass = params().documentClass();
1595 string const top_element = tclass.latexname();
1598 if (runparams.flavor == OutputParams::XML)
1599 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1602 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1605 if (! tclass.class_header().empty())
1606 os << from_ascii(tclass.class_header());
1607 else if (runparams.flavor == OutputParams::XML)
1608 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1609 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1611 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1613 docstring preamble = from_utf8(params().preamble);
1614 if (runparams.flavor != OutputParams::XML ) {
1615 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1616 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1617 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1618 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1621 string const name = runparams.nice
1622 ? changeExtension(absFileName(), ".sgml") : fname;
1623 preamble += features.getIncludedFiles(name);
1624 preamble += features.getLyXSGMLEntities();
1626 if (!preamble.empty()) {
1627 os << "\n [ " << preamble << " ]";
1632 string top = top_element;
1634 if (runparams.flavor == OutputParams::XML)
1635 top += params().language->code();
1637 top += params().language->code().substr(0, 2);
1640 if (!params().options.empty()) {
1642 top += params().options;
1645 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1646 << " file was created by LyX " << lyx_version
1647 << "\n See http://www.lyx.org/ for more information -->\n";
1649 params().documentClass().counters().reset();
1651 sgml::openTag(os, top);
1653 docbookParagraphs(text(), *this, os, runparams);
1654 sgml::closeTag(os, top_element);
1658 void Buffer::makeLyXHTMLFile(FileName const & fname,
1659 OutputParams const & runparams) const
1661 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1664 if (!openFileWrite(ofs, fname))
1667 // make sure we are ready to export
1668 // this has to be done before we validate
1669 updateBuffer(UpdateMaster, OutputUpdate);
1670 updateMacroInstances(OutputUpdate);
1672 writeLyXHTMLSource(ofs, runparams);
1676 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1680 void Buffer::writeLyXHTMLSource(odocstream & os,
1681 OutputParams const & runparams,
1682 bool const only_body) const
1684 LaTeXFeatures features(*this, params(), runparams);
1686 d->bibinfo_.makeCitationLabels(*this);
1689 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1690 << "<!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"
1691 // FIXME Language should be set properly.
1692 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
1694 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
1695 // FIXME Presumably need to set this right
1696 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1698 docstring const & doctitle = features.htmlTitle();
1700 << (doctitle.empty() ? from_ascii("LyX Document") : doctitle)
1703 os << "\n<!-- Text Class Preamble -->\n"
1704 << features.getTClassHTMLPreamble()
1705 << "\n<!-- Preamble Snippets -->\n"
1706 << from_utf8(features.getPreambleSnippets());
1708 os << "\n<!-- Layout-provided Styles -->\n";
1709 docstring const styleinfo = features.getTClassHTMLStyles();
1710 if (!styleinfo.empty()) {
1711 os << "<style type='text/css'>\n"
1716 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
1717 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
1718 if (needfg || needbg) {
1719 os << "<style type='text/css'>\nbody {\n";
1722 << from_ascii(X11hexname(params().fontcolor))
1725 os << " background-color: "
1726 << from_ascii(X11hexname(params().backgroundcolor))
1728 os << "}\n</style>\n";
1730 os << "</head>\n<body>\n";
1734 params().documentClass().counters().reset();
1735 xhtmlParagraphs(text(), *this, xs, runparams);
1737 os << "</body>\n</html>\n";
1741 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1742 // Other flags: -wall -v0 -x
1743 int Buffer::runChktex()
1747 // get LaTeX-Filename
1748 FileName const path(temppath());
1749 string const name = addName(path.absFileName(), latexName());
1750 string const org_path = filePath();
1752 PathChanger p(path); // path to LaTeX file
1753 message(_("Running chktex..."));
1755 // Generate the LaTeX file if neccessary
1756 OutputParams runparams(¶ms().encoding());
1757 runparams.flavor = OutputParams::LATEX;
1758 runparams.nice = false;
1759 runparams.linelen = lyxrc.plaintext_linelen;
1760 makeLaTeXFile(FileName(name), org_path, runparams);
1763 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
1764 int const res = chktex.run(terr); // run chktex
1767 Alert::error(_("chktex failure"),
1768 _("Could not run chktex successfully."));
1769 } else if (res > 0) {
1770 ErrorList & errlist = d->errorLists["ChkTeX"];
1772 bufferErrors(terr, errlist);
1783 void Buffer::validate(LaTeXFeatures & features) const
1785 params().validate(features);
1787 for_each(paragraphs().begin(), paragraphs().end(),
1788 bind(&Paragraph::validate, _1, ref(features)));
1790 if (lyxerr.debugging(Debug::LATEX)) {
1791 features.showStruct();
1796 void Buffer::getLabelList(vector<docstring> & list) const
1798 // If this is a child document, use the master's list instead.
1800 masterBuffer()->getLabelList(list);
1805 Toc & toc = d->toc_backend.toc("label");
1806 TocIterator toc_it = toc.begin();
1807 TocIterator end = toc.end();
1808 for (; toc_it != end; ++toc_it) {
1809 if (toc_it->depth() == 0)
1810 list.push_back(toc_it->str());
1815 void Buffer::updateBibfilesCache(UpdateScope scope) const
1817 // FIXME This is probably unnecssary, given where we call this.
1818 // If this is a child document, use the parent's cache instead.
1819 if (parent() && scope != UpdateChildOnly) {
1820 masterBuffer()->updateBibfilesCache();
1824 d->bibfiles_cache_.clear();
1825 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1826 if (it->lyxCode() == BIBTEX_CODE) {
1827 InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
1828 support::FileNameList const bibfiles = inset.getBibFiles();
1829 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1832 } else if (it->lyxCode() == INCLUDE_CODE) {
1833 InsetInclude & inset = static_cast<InsetInclude &>(*it);
1834 Buffer const * const incbuf = inset.getChildBuffer();
1837 support::FileNameList const & bibfiles =
1838 incbuf->getBibfilesCache(UpdateChildOnly);
1839 if (!bibfiles.empty()) {
1840 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1846 d->bibfile_cache_valid_ = true;
1847 d->bibinfo_cache_valid_ = false;
1848 d->cite_labels_valid_ = false;
1852 void Buffer::invalidateBibinfoCache() const
1854 d->bibinfo_cache_valid_ = false;
1855 d->cite_labels_valid_ = false;
1856 // also invalidate the cache for the parent buffer
1857 Buffer const * const pbuf = d->parent();
1859 pbuf->invalidateBibinfoCache();
1863 void Buffer::invalidateBibfileCache() const
1865 d->bibfile_cache_valid_ = false;
1866 d->bibinfo_cache_valid_ = false;
1867 d->cite_labels_valid_ = false;
1868 // also invalidate the cache for the parent buffer
1869 Buffer const * const pbuf = d->parent();
1871 pbuf->invalidateBibfileCache();
1875 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1877 // FIXME This is probably unnecessary, given where we call this.
1878 // If this is a child document, use the master's cache instead.
1879 Buffer const * const pbuf = masterBuffer();
1880 if (pbuf != this && scope != UpdateChildOnly)
1881 return pbuf->getBibfilesCache();
1883 if (!d->bibfile_cache_valid_)
1884 this->updateBibfilesCache(scope);
1886 return d->bibfiles_cache_;
1890 BiblioInfo const & Buffer::masterBibInfo() const
1892 Buffer const * const tmp = masterBuffer();
1894 return tmp->masterBibInfo();
1899 void Buffer::checkIfBibInfoCacheIsValid() const
1901 // use the master's cache
1902 Buffer const * const tmp = masterBuffer();
1904 tmp->checkIfBibInfoCacheIsValid();
1908 // compare the cached timestamps with the actual ones.
1909 FileNameList const & bibfiles_cache = getBibfilesCache();
1910 FileNameList::const_iterator ei = bibfiles_cache.begin();
1911 FileNameList::const_iterator en = bibfiles_cache.end();
1912 for (; ei != en; ++ ei) {
1913 time_t lastw = ei->lastModified();
1914 time_t prevw = d->bibfile_status_[*ei];
1915 if (lastw != prevw) {
1916 d->bibinfo_cache_valid_ = false;
1917 d->cite_labels_valid_ = false;
1918 d->bibfile_status_[*ei] = lastw;
1924 void Buffer::reloadBibInfoCache() const
1926 // use the master's cache
1927 Buffer const * const tmp = masterBuffer();
1929 tmp->reloadBibInfoCache();
1933 checkIfBibInfoCacheIsValid();
1934 if (d->bibinfo_cache_valid_)
1937 d->bibinfo_.clear();
1939 d->bibinfo_cache_valid_ = true;
1943 void Buffer::collectBibKeys() const
1945 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1946 it->collectBibKeys(it);
1950 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
1952 Buffer const * tmp = masterBuffer();
1953 BiblioInfo & masterbi = (tmp == this) ?
1954 d->bibinfo_ : tmp->d->bibinfo_;
1955 masterbi.mergeBiblioInfo(bi);
1959 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
1961 Buffer const * tmp = masterBuffer();
1962 BiblioInfo & masterbi = (tmp == this) ?
1963 d->bibinfo_ : tmp->d->bibinfo_;
1968 bool Buffer::citeLabelsValid() const
1970 return masterBuffer()->d->cite_labels_valid_;
1974 bool Buffer::isDepClean(string const & name) const
1976 DepClean::const_iterator const it = d->dep_clean.find(name);
1977 if (it == d->dep_clean.end())
1983 void Buffer::markDepClean(string const & name)
1985 d->dep_clean[name] = true;
1989 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1992 // FIXME? if there is an Buffer LFUN that can be dispatched even
1993 // if internal, put a switch '(cmd.action)' here.
1999 switch (cmd.action()) {
2001 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2002 flag.setOnOff(isReadonly());
2005 // FIXME: There is need for a command-line import.
2006 //case LFUN_BUFFER_IMPORT:
2008 case LFUN_BUFFER_AUTO_SAVE:
2011 case LFUN_BUFFER_EXPORT_CUSTOM:
2012 // FIXME: Nothing to check here?
2015 case LFUN_BUFFER_EXPORT: {
2016 docstring const arg = cmd.argument();
2017 if (arg == "custom") {
2021 string format = to_utf8(arg);
2022 size_t pos = format.find(' ');
2023 if (pos != string::npos)
2024 format = format.substr(0, pos);
2025 enable = params().isExportable(format);
2027 flag.message(bformat(
2028 _("Don't know how to export to format: %1$s"), arg));
2032 case LFUN_BUFFER_CHKTEX:
2033 enable = params().isLatex() && !lyxrc.chktex_command.empty();
2036 case LFUN_BUILD_PROGRAM:
2037 enable = params().isExportable("program");
2040 case LFUN_BRANCH_ACTIVATE:
2041 case LFUN_BRANCH_DEACTIVATE: {
2042 BranchList const & branchList = params().branchlist();
2043 docstring const branchName = cmd.argument();
2044 enable = !branchName.empty() && branchList.find(branchName);
2048 case LFUN_BRANCH_ADD:
2049 case LFUN_BRANCHES_RENAME:
2050 case LFUN_BUFFER_PRINT:
2051 // if no Buffer is present, then of course we won't be called!
2054 case LFUN_BUFFER_LANGUAGE:
2055 enable = !isReadonly();
2061 flag.setEnabled(enable);
2066 void Buffer::dispatch(string const & command, DispatchResult & result)
2068 return dispatch(lyxaction.lookupFunc(command), result);
2072 // NOTE We can end up here even if we have no GUI, because we are called
2073 // by LyX::exec to handled command-line requests. So we may need to check
2074 // whether we have a GUI or not. The boolean use_gui holds this information.
2075 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2078 // FIXME? if there is an Buffer LFUN that can be dispatched even
2079 // if internal, put a switch '(cmd.action())' here.
2080 dr.dispatched(false);
2083 string const argument = to_utf8(func.argument());
2084 // We'll set this back to false if need be.
2085 bool dispatched = true;
2086 undo().beginUndoGroup();
2088 switch (func.action()) {
2089 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2090 if (lyxvc().inUse())
2091 lyxvc().toggleReadOnly();
2093 setReadonly(!isReadonly());
2096 case LFUN_BUFFER_EXPORT: {
2097 bool success = doExport(argument, false, false);
2098 dr.setError(!success);
2100 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2105 case LFUN_BUILD_PROGRAM:
2106 doExport("program", true, false);
2109 case LFUN_BUFFER_CHKTEX:
2113 case LFUN_BUFFER_EXPORT_CUSTOM: {
2115 string command = split(argument, format_name, ' ');
2116 Format const * format = formats.getFormat(format_name);
2118 lyxerr << "Format \"" << format_name
2119 << "\" not recognized!"
2124 // The name of the file created by the conversion process
2127 // Output to filename
2128 if (format->name() == "lyx") {
2129 string const latexname = latexName(false);
2130 filename = changeExtension(latexname,
2131 format->extension());
2132 filename = addName(temppath(), filename);
2134 if (!writeFile(FileName(filename)))
2138 doExport(format_name, true, false, filename);
2141 // Substitute $$FName for filename
2142 if (!contains(command, "$$FName"))
2143 command = "( " + command + " ) < $$FName";
2144 command = subst(command, "$$FName", filename);
2146 // Execute the command in the background
2148 call.startscript(Systemcall::DontWait, command, filePath());
2152 // FIXME: There is need for a command-line import.
2154 case LFUN_BUFFER_IMPORT:
2159 case LFUN_BUFFER_AUTO_SAVE:
2161 resetAutosaveTimers();
2164 case LFUN_BRANCH_ADD: {
2165 docstring branch_name = func.argument();
2166 if (branch_name.empty()) {
2170 BranchList & branch_list = params().branchlist();
2171 vector<docstring> const branches =
2172 getVectorFromString(branch_name, branch_list.separator());
2174 for (vector<docstring>::const_iterator it = branches.begin();
2175 it != branches.end(); ++it) {
2177 Branch * branch = branch_list.find(branch_name);
2179 LYXERR0("Branch " << branch_name << " already exists.");
2183 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2185 branch_list.add(branch_name);
2186 branch = branch_list.find(branch_name);
2187 string const x11hexname = X11hexname(branch->color());
2188 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2189 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2191 dr.screenUpdate(Update::Force);
2199 case LFUN_BRANCH_ACTIVATE:
2200 case LFUN_BRANCH_DEACTIVATE: {
2201 BranchList & branchList = params().branchlist();
2202 docstring const branchName = func.argument();
2203 // the case without a branch name is handled elsewhere
2204 if (branchName.empty()) {
2208 Branch * branch = branchList.find(branchName);
2210 LYXERR0("Branch " << branchName << " does not exist.");
2212 docstring const msg =
2213 bformat(_("Branch \"%1$s\" does not exist."), branchName);
2216 branch->setSelected(func.action() == LFUN_BRANCH_ACTIVATE);
2218 dr.screenUpdate(Update::Force);
2219 dr.forceBufferUpdate();
2224 case LFUN_BRANCHES_RENAME: {
2225 if (func.argument().empty())
2228 docstring const oldname = from_utf8(func.getArg(0));
2229 docstring const newname = from_utf8(func.getArg(1));
2230 InsetIterator it = inset_iterator_begin(inset());
2231 InsetIterator const end = inset_iterator_end(inset());
2232 bool success = false;
2233 for (; it != end; ++it) {
2234 if (it->lyxCode() == BRANCH_CODE) {
2235 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2236 if (ins.branch() == oldname) {
2237 undo().recordUndo(it);
2238 ins.rename(newname);
2243 if (it->lyxCode() == INCLUDE_CODE) {
2244 // get buffer of external file
2245 InsetInclude const & ins =
2246 static_cast<InsetInclude const &>(*it);
2247 Buffer * child = ins.getChildBuffer();
2250 child->dispatch(func, dr);
2255 dr.screenUpdate(Update::Force);
2256 dr.forceBufferUpdate();
2261 case LFUN_BUFFER_PRINT: {
2262 // we'll assume there's a problem until we succeed
2264 string target = func.getArg(0);
2265 string target_name = func.getArg(1);
2266 string command = func.getArg(2);
2269 || target_name.empty()
2270 || command.empty()) {
2271 LYXERR0("Unable to parse " << func.argument());
2272 docstring const msg =
2273 bformat(_("Unable to parse \"%1$s\""), func.argument());
2277 if (target != "printer" && target != "file") {
2278 LYXERR0("Unrecognized target \"" << target << '"');
2279 docstring const msg =
2280 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2285 bool const update_unincluded =
2286 params().maintain_unincluded_children
2287 && !params().getIncludedChildren().empty();
2288 if (!doExport("dvi", true, update_unincluded)) {
2289 showPrintError(absFileName());
2290 dr.setMessage(_("Error exporting to DVI."));
2294 // Push directory path.
2295 string const path = temppath();
2296 // Prevent the compiler from optimizing away p
2300 // there are three cases here:
2301 // 1. we print to a file
2302 // 2. we print directly to a printer
2303 // 3. we print using a spool command (print to file first)
2306 string const dviname = changeExtension(latexName(true), "dvi");
2308 if (target == "printer") {
2309 if (!lyxrc.print_spool_command.empty()) {
2310 // case 3: print using a spool
2311 string const psname = changeExtension(dviname,".ps");
2312 command += ' ' + lyxrc.print_to_file
2315 + quoteName(dviname);
2317 string command2 = lyxrc.print_spool_command + ' ';
2318 if (target_name != "default") {
2319 command2 += lyxrc.print_spool_printerprefix
2323 command2 += quoteName(psname);
2325 // If successful, then spool command
2326 res = one.startscript(Systemcall::Wait, command,
2330 // If there's no GUI, we have to wait on this command. Otherwise,
2331 // LyX deletes the temporary directory, and with it the spooled
2332 // file, before it can be printed!!
2333 Systemcall::Starttype stype = use_gui ?
2334 Systemcall::DontWait : Systemcall::Wait;
2335 res = one.startscript(stype, command2,
2339 // case 2: print directly to a printer
2340 if (target_name != "default")
2341 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2343 Systemcall::Starttype stype = use_gui ?
2344 Systemcall::DontWait : Systemcall::Wait;
2345 res = one.startscript(stype, command +
2346 quoteName(dviname), filePath());
2350 // case 1: print to a file
2351 FileName const filename(makeAbsPath(target_name, filePath()));
2352 FileName const dvifile(makeAbsPath(dviname, path));
2353 if (filename.exists()) {
2354 docstring text = bformat(
2355 _("The file %1$s already exists.\n\n"
2356 "Do you want to overwrite that file?"),
2357 makeDisplayPath(filename.absFileName()));
2358 if (Alert::prompt(_("Overwrite file?"),
2359 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2362 command += ' ' + lyxrc.print_to_file
2363 + quoteName(filename.toFilesystemEncoding())
2365 + quoteName(dvifile.toFilesystemEncoding());
2367 Systemcall::Starttype stype = use_gui ?
2368 Systemcall::DontWait : Systemcall::Wait;
2369 res = one.startscript(stype, command, filePath());
2375 dr.setMessage(_("Error running external commands."));
2376 showPrintError(absFileName());
2385 dr.dispatched(dispatched);
2386 undo().endUndoGroup();
2390 void Buffer::changeLanguage(Language const * from, Language const * to)
2392 LASSERT(from, /**/);
2395 for_each(par_iterator_begin(),
2397 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2401 bool Buffer::isMultiLingual() const
2403 ParConstIterator end = par_iterator_end();
2404 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2405 if (it->isMultiLingual(params()))
2412 std::set<Language const *> Buffer::getLanguages() const
2414 std::set<Language const *> languages;
2415 getLanguages(languages);
2420 void Buffer::getLanguages(std::set<Language const *> & languages) const
2422 ParConstIterator end = par_iterator_end();
2423 // add the buffer language, even if it's not actively used
2424 languages.insert(language());
2425 // iterate over the paragraphs
2426 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2427 it->getLanguages(languages);
2429 ListOfBuffers clist = getDescendents();
2430 ListOfBuffers::const_iterator cit = clist.begin();
2431 ListOfBuffers::const_iterator const cen = clist.end();
2432 for (; cit != cen; ++cit)
2433 (*cit)->getLanguages(languages);
2437 DocIterator Buffer::getParFromID(int const id) const
2439 Buffer * buf = const_cast<Buffer *>(this);
2441 // John says this is called with id == -1 from undo
2442 lyxerr << "getParFromID(), id: " << id << endl;
2443 return doc_iterator_end(buf);
2446 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2447 if (it.paragraph().id() == id)
2450 return doc_iterator_end(buf);
2454 bool Buffer::hasParWithID(int const id) const
2456 return !getParFromID(id).atEnd();
2460 ParIterator Buffer::par_iterator_begin()
2462 return ParIterator(doc_iterator_begin(this));
2466 ParIterator Buffer::par_iterator_end()
2468 return ParIterator(doc_iterator_end(this));
2472 ParConstIterator Buffer::par_iterator_begin() const
2474 return ParConstIterator(doc_iterator_begin(this));
2478 ParConstIterator Buffer::par_iterator_end() const
2480 return ParConstIterator(doc_iterator_end(this));
2484 Language const * Buffer::language() const
2486 return params().language;
2490 docstring const Buffer::B_(string const & l10n) const
2492 return params().B_(l10n);
2496 bool Buffer::isClean() const
2498 return d->lyx_clean;
2502 bool Buffer::isExternallyModified(CheckMethod method) const
2504 LASSERT(d->filename.exists(), /**/);
2505 // if method == timestamp, check timestamp before checksum
2506 return (method == checksum_method
2507 || d->timestamp_ != d->filename.lastModified())
2508 && d->checksum_ != d->filename.checksum();
2512 void Buffer::saveCheckSum() const
2514 FileName const & file = d->filename;
2517 if (file.exists()) {
2518 d->timestamp_ = file.lastModified();
2519 d->checksum_ = file.checksum();
2521 // in the case of save to a new file.
2528 void Buffer::markClean() const
2530 if (!d->lyx_clean) {
2531 d->lyx_clean = true;
2534 // if the .lyx file has been saved, we don't need an
2536 d->bak_clean = true;
2537 d->undo_.markDirty();
2541 void Buffer::setUnnamed(bool flag)
2547 bool Buffer::isUnnamed() const
2554 /// Don't check unnamed, here: isInternal() is used in
2555 /// newBuffer(), where the unnamed flag has not been set by anyone
2556 /// yet. Also, for an internal buffer, there should be no need for
2557 /// retrieving fileName() nor for checking if it is unnamed or not.
2558 bool Buffer::isInternal() const
2560 return fileName().extension() == "internal";
2564 void Buffer::markDirty()
2567 d->lyx_clean = false;
2570 d->bak_clean = false;
2572 DepClean::iterator it = d->dep_clean.begin();
2573 DepClean::const_iterator const end = d->dep_clean.end();
2575 for (; it != end; ++it)
2580 FileName Buffer::fileName() const
2586 string Buffer::absFileName() const
2588 return d->filename.absFileName();
2592 string Buffer::filePath() const
2594 return d->filename.onlyPath().absFileName() + "/";
2598 bool Buffer::isReadonly() const
2600 return d->read_only;
2604 void Buffer::setParent(Buffer const * buffer)
2606 // Avoids recursive include.
2607 d->setParent(buffer == this ? 0 : buffer);
2612 Buffer const * Buffer::parent() const
2618 ListOfBuffers Buffer::allRelatives() const
2620 ListOfBuffers lb = masterBuffer()->getDescendents();
2621 lb.push_front(const_cast<Buffer *>(masterBuffer()));
2626 Buffer const * Buffer::masterBuffer() const
2628 // FIXME Should be make sure we are not in some kind
2629 // of recursive include? A -> B -> A will crash this.
2630 Buffer const * const pbuf = d->parent();
2634 return pbuf->masterBuffer();
2638 bool Buffer::isChild(Buffer * child) const
2640 return d->children_positions.find(child) != d->children_positions.end();
2644 DocIterator Buffer::firstChildPosition(Buffer const * child)
2646 Impl::BufferPositionMap::iterator it;
2647 it = d->children_positions.find(child);
2648 if (it == d->children_positions.end())
2649 return DocIterator(this);
2654 bool Buffer::hasChildren() const
2656 return !d->children_positions.empty();
2660 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
2662 // loop over children
2663 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2664 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2665 for (; it != end; ++it) {
2666 Buffer * child = const_cast<Buffer *>(it->first);
2668 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
2669 if (bit != clist.end())
2671 clist.push_back(child);
2673 // there might be grandchildren
2674 child->collectChildren(clist, true);
2679 ListOfBuffers Buffer::getChildren() const
2682 collectChildren(v, false);
2683 // Make sure we have not included ourselves.
2684 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
2685 if (bit != v.end()) {
2686 LYXERR0("Recursive include detected in `" << fileName() << "'.");
2693 ListOfBuffers Buffer::getDescendents() const
2696 collectChildren(v, true);
2697 // Make sure we have not included ourselves.
2698 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
2699 if (bit != v.end()) {
2700 LYXERR0("Recursive include detected in `" << fileName() << "'.");
2707 template<typename M>
2708 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
2713 typename M::const_iterator it = m.lower_bound(x);
2714 if (it == m.begin())
2722 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
2723 DocIterator const & pos) const
2725 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2727 // if paragraphs have no macro context set, pos will be empty
2731 // we haven't found anything yet
2732 DocIterator bestPos = owner_->par_iterator_begin();
2733 MacroData const * bestData = 0;
2735 // find macro definitions for name
2736 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
2737 if (nameIt != macros.end()) {
2738 // find last definition in front of pos or at pos itself
2739 PositionScopeMacroMap::const_iterator it
2740 = greatest_below(nameIt->second, pos);
2741 if (it != nameIt->second.end()) {
2743 // scope ends behind pos?
2744 if (pos < it->second.first) {
2745 // Looks good, remember this. If there
2746 // is no external macro behind this,
2747 // we found the right one already.
2748 bestPos = it->first;
2749 bestData = &it->second.second;
2753 // try previous macro if there is one
2754 if (it == nameIt->second.begin())
2761 // find macros in included files
2762 PositionScopeBufferMap::const_iterator it
2763 = greatest_below(position_to_children, pos);
2764 if (it == position_to_children.end())
2765 // no children before
2769 // do we know something better (i.e. later) already?
2770 if (it->first < bestPos )
2773 // scope ends behind pos?
2774 if (pos < it->second.first
2775 && (cloned_buffer_ ||
2776 theBufferList().isLoaded(it->second.second))) {
2777 // look for macro in external file
2779 MacroData const * data
2780 = it->second.second->getMacro(name, false);
2783 bestPos = it->first;
2789 // try previous file if there is one
2790 if (it == position_to_children.begin())
2795 // return the best macro we have found
2800 MacroData const * Buffer::getMacro(docstring const & name,
2801 DocIterator const & pos, bool global) const
2806 // query buffer macros
2807 MacroData const * data = d->getBufferMacro(name, pos);
2811 // If there is a master buffer, query that
2812 Buffer const * const pbuf = d->parent();
2814 d->macro_lock = true;
2815 MacroData const * macro = pbuf->getMacro(
2816 name, *this, false);
2817 d->macro_lock = false;
2823 data = MacroTable::globalMacros().get(name);
2832 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2834 // set scope end behind the last paragraph
2835 DocIterator scope = par_iterator_begin();
2836 scope.pit() = scope.lastpit() + 1;
2838 return getMacro(name, scope, global);
2842 MacroData const * Buffer::getMacro(docstring const & name,
2843 Buffer const & child, bool global) const
2845 // look where the child buffer is included first
2846 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2847 if (it == d->children_positions.end())
2850 // check for macros at the inclusion position
2851 return getMacro(name, it->second, global);
2855 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
2857 pit_type const lastpit = it.lastpit();
2859 // look for macros in each paragraph
2860 while (it.pit() <= lastpit) {
2861 Paragraph & par = it.paragraph();
2863 // iterate over the insets of the current paragraph
2864 InsetList const & insets = par.insetList();
2865 InsetList::const_iterator iit = insets.begin();
2866 InsetList::const_iterator end = insets.end();
2867 for (; iit != end; ++iit) {
2868 it.pos() = iit->pos;
2870 // is it a nested text inset?
2871 if (iit->inset->asInsetText()) {
2872 // Inset needs its own scope?
2873 InsetText const * itext = iit->inset->asInsetText();
2874 bool newScope = itext->isMacroScope();
2876 // scope which ends just behind the inset
2877 DocIterator insetScope = it;
2880 // collect macros in inset
2881 it.push_back(CursorSlice(*iit->inset));
2882 updateMacros(it, newScope ? insetScope : scope);
2887 if (iit->inset->asInsetTabular()) {
2888 CursorSlice slice(*iit->inset);
2889 size_t const numcells = slice.nargs();
2890 for (; slice.idx() < numcells; slice.forwardIdx()) {
2891 it.push_back(slice);
2892 updateMacros(it, scope);
2898 // is it an external file?
2899 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2900 // get buffer of external file
2901 InsetInclude const & inset =
2902 static_cast<InsetInclude const &>(*iit->inset);
2904 Buffer * child = inset.getChildBuffer();
2909 // register its position, but only when it is
2910 // included first in the buffer
2911 if (children_positions.find(child) ==
2912 children_positions.end())
2913 children_positions[child] = it;
2915 // register child with its scope
2916 position_to_children[it] = Impl::ScopeBuffer(scope, child);
2920 InsetMath * im = iit->inset->asInsetMath();
2921 if (doing_export && im) {
2922 InsetMathHull * hull = im->asHullInset();
2924 hull->recordLocation(it);
2927 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2931 MathMacroTemplate & macroTemplate =
2932 *iit->inset->asInsetMath()->asMacroTemplate();
2933 MacroContext mc(owner_, it);
2934 macroTemplate.updateToContext(mc);
2937 bool valid = macroTemplate.validMacro();
2938 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2939 // then the BufferView's cursor will be invalid in
2940 // some cases which leads to crashes.
2945 // FIXME (Abdel), I don't understandt why we pass 'it' here
2946 // instead of 'macroTemplate' defined above... is this correct?
2947 macros[macroTemplate.name()][it] =
2948 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
2958 void Buffer::updateMacros() const
2963 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2965 // start with empty table
2967 d->children_positions.clear();
2968 d->position_to_children.clear();
2970 // Iterate over buffer, starting with first paragraph
2971 // The scope must be bigger than any lookup DocIterator
2972 // later. For the global lookup, lastpit+1 is used, hence
2973 // we use lastpit+2 here.
2974 DocIterator it = par_iterator_begin();
2975 DocIterator outerScope = it;
2976 outerScope.pit() = outerScope.lastpit() + 2;
2977 d->updateMacros(it, outerScope);
2981 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
2983 InsetIterator it = inset_iterator_begin(inset());
2984 InsetIterator const end = inset_iterator_end(inset());
2985 for (; it != end; ++it) {
2986 if (it->lyxCode() == BRANCH_CODE) {
2987 InsetBranch & br = static_cast<InsetBranch &>(*it);
2988 docstring const name = br.branch();
2989 if (!from_master && !params().branchlist().find(name))
2990 result.push_back(name);
2991 else if (from_master && !masterBuffer()->params().branchlist().find(name))
2992 result.push_back(name);
2995 if (it->lyxCode() == INCLUDE_CODE) {
2996 // get buffer of external file
2997 InsetInclude const & ins =
2998 static_cast<InsetInclude const &>(*it);
2999 Buffer * child = ins.getChildBuffer();
3002 child->getUsedBranches(result, true);
3005 // remove duplicates
3010 void Buffer::updateMacroInstances(UpdateType utype) const
3012 LYXERR(Debug::MACROS, "updateMacroInstances for "
3013 << d->filename.onlyFileName());
3014 DocIterator it = doc_iterator_begin(this);
3016 DocIterator const end = doc_iterator_end(this);
3017 for (; it != end; it.forwardInset()) {
3018 // look for MathData cells in InsetMathNest insets
3019 InsetMath * minset = it.nextInset()->asInsetMath();
3023 // update macro in all cells of the InsetMathNest
3024 DocIterator::idx_type n = minset->nargs();
3025 MacroContext mc = MacroContext(this, it);
3026 for (DocIterator::idx_type i = 0; i < n; ++i) {
3027 MathData & data = minset->cell(i);
3028 data.updateMacros(0, mc, utype);
3034 void Buffer::listMacroNames(MacroNameSet & macros) const
3039 d->macro_lock = true;
3041 // loop over macro names
3042 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3043 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3044 for (; nameIt != nameEnd; ++nameIt)
3045 macros.insert(nameIt->first);
3047 // loop over children
3048 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3049 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3050 for (; it != end; ++it)
3051 it->first->listMacroNames(macros);
3054 Buffer const * const pbuf = d->parent();
3056 pbuf->listMacroNames(macros);
3058 d->macro_lock = false;
3062 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3064 Buffer const * const pbuf = d->parent();
3069 pbuf->listMacroNames(names);
3072 MacroNameSet::iterator it = names.begin();
3073 MacroNameSet::iterator end = names.end();
3074 for (; it != end; ++it) {
3076 MacroData const * data =
3077 pbuf->getMacro(*it, *this, false);
3079 macros.insert(data);
3081 // we cannot access the original MathMacroTemplate anymore
3082 // here to calls validate method. So we do its work here manually.
3083 // FIXME: somehow make the template accessible here.
3084 if (data->optionals() > 0)
3085 features.require("xargs");
3091 Buffer::References & Buffer::references(docstring const & label)
3094 return const_cast<Buffer *>(masterBuffer())->references(label);
3096 RefCache::iterator it = d->ref_cache_.find(label);
3097 if (it != d->ref_cache_.end())
3098 return it->second.second;
3100 static InsetLabel const * dummy_il = 0;
3101 static References const dummy_refs;
3102 it = d->ref_cache_.insert(
3103 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3104 return it->second.second;
3108 Buffer::References const & Buffer::references(docstring const & label) const
3110 return const_cast<Buffer *>(this)->references(label);
3114 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3116 masterBuffer()->d->ref_cache_[label].first = il;
3120 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3122 return masterBuffer()->d->ref_cache_[label].first;
3126 void Buffer::clearReferenceCache() const
3129 d->ref_cache_.clear();
3133 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
3136 //FIXME: This does not work for child documents yet.
3137 LASSERT(code == CITE_CODE, /**/);
3139 reloadBibInfoCache();
3141 // Check if the label 'from' appears more than once
3142 BiblioInfo const & keys = masterBibInfo();
3143 BiblioInfo::const_iterator bit = keys.begin();
3144 BiblioInfo::const_iterator bend = keys.end();
3145 vector<docstring> labels;
3147 for (; bit != bend; ++bit)
3149 labels.push_back(bit->first);
3151 if (count(labels.begin(), labels.end(), from) > 1)
3154 string const paramName = "key";
3155 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3156 if (it->lyxCode() == code) {
3157 InsetCommand * inset = it->asInsetCommand();
3160 docstring const oldValue = inset->getParam(paramName);
3161 if (oldValue == from)
3162 inset->setParam(paramName, to);
3168 void Buffer::getSourceCode(odocstream & os, string const format,
3169 pit_type par_begin, pit_type par_end,
3170 bool full_source) const
3172 OutputParams runparams(¶ms().encoding());
3173 runparams.nice = true;
3174 runparams.flavor = params().getOutputFlavor(format);
3175 runparams.linelen = lyxrc.plaintext_linelen;
3176 // No side effect of file copying and image conversion
3177 runparams.dryrun = true;
3180 os << "% " << _("Preview source code") << "\n\n";
3182 d->texrow.newline();
3183 d->texrow.newline();
3184 if (params().isDocBook())
3185 writeDocBookSource(os, absFileName(), runparams, false);
3186 else if (runparams.flavor == OutputParams::HTML)
3187 writeLyXHTMLSource(os, runparams, false);
3189 // latex or literate
3190 otexstream ots(os, d->texrow);
3191 writeLaTeXSource(ots, string(), runparams, true, true);
3194 runparams.par_begin = par_begin;
3195 runparams.par_end = par_end;
3196 if (par_begin + 1 == par_end) {
3198 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3202 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3203 convert<docstring>(par_begin),
3204 convert<docstring>(par_end - 1))
3211 // output paragraphs
3212 if (params().isDocBook())
3213 docbookParagraphs(text(), *this, os, runparams);
3214 else if (runparams.flavor == OutputParams::HTML) {
3216 xhtmlParagraphs(text(), *this, xs, runparams);
3218 // latex or literate
3219 otexstream ots(os, texrow);
3220 latexParagraphs(*this, text(), ots, runparams);
3226 ErrorList & Buffer::errorList(string const & type) const
3228 return d->errorLists[type];
3232 void Buffer::updateTocItem(std::string const & type,
3233 DocIterator const & dit) const
3236 d->gui_->updateTocItem(type, dit);
3240 void Buffer::structureChanged() const
3243 d->gui_->structureChanged();
3247 void Buffer::errors(string const & err, bool from_master) const
3250 d->gui_->errors(err, from_master);
3254 void Buffer::message(docstring const & msg) const
3257 d->gui_->message(msg);
3261 void Buffer::setBusy(bool on) const
3264 d->gui_->setBusy(on);
3268 void Buffer::updateTitles() const
3271 d->wa_->updateTitles();
3275 void Buffer::resetAutosaveTimers() const
3278 d->gui_->resetAutosaveTimers();
3282 bool Buffer::hasGuiDelegate() const
3288 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3297 class AutoSaveBuffer : public ForkedProcess {
3300 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3301 : buffer_(buffer), fname_(fname) {}
3303 virtual shared_ptr<ForkedProcess> clone() const
3305 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3310 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3311 from_utf8(fname_.absFileName())));
3312 return run(DontWait);
3316 virtual int generateChild();
3318 Buffer const & buffer_;
3323 int AutoSaveBuffer::generateChild()
3325 #if defined(__APPLE__)
3326 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3327 * We should use something else like threads.
3329 * Since I do not know how to determine at run time what is the OS X
3330 * version, I just disable forking altogether for now (JMarc)
3332 pid_t const pid = -1;
3334 // tmp_ret will be located (usually) in /tmp
3335 // will that be a problem?
3336 // Note that this calls ForkedCalls::fork(), so it's
3337 // ok cross-platform.
3338 pid_t const pid = fork();
3339 // If you want to debug the autosave
3340 // you should set pid to -1, and comment out the fork.
3341 if (pid != 0 && pid != -1)
3345 // pid = -1 signifies that lyx was unable
3346 // to fork. But we will do the save
3348 bool failed = false;
3349 FileName const tmp_ret = FileName::tempName("lyxauto");
3350 if (!tmp_ret.empty()) {
3351 buffer_.writeFile(tmp_ret);
3352 // assume successful write of tmp_ret
3353 if (!tmp_ret.moveTo(fname_))
3359 // failed to write/rename tmp_ret so try writing direct
3360 if (!buffer_.writeFile(fname_)) {
3361 // It is dangerous to do this in the child,
3362 // but safe in the parent, so...
3363 if (pid == -1) // emit message signal.
3364 buffer_.message(_("Autosave failed!"));
3368 if (pid == 0) // we are the child so...
3377 FileName Buffer::getEmergencyFileName() const
3379 return FileName(d->filename.absFileName() + ".emergency");
3383 FileName Buffer::getAutosaveFileName() const
3385 // if the document is unnamed try to save in the backup dir, else
3386 // in the default document path, and as a last try in the filePath,
3387 // which will most often be the temporary directory
3390 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3391 : lyxrc.backupdir_path;
3392 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3395 string const fname = "#" + d->filename.onlyFileName() + "#";
3397 return makeAbsPath(fname, fpath);
3401 void Buffer::removeAutosaveFile() const
3403 FileName const f = getAutosaveFileName();
3409 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3411 FileName const newauto = getAutosaveFileName();
3413 if (newauto != oldauto && oldauto.exists())
3414 if (!oldauto.moveTo(newauto))
3415 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3419 bool Buffer::autoSave() const
3421 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
3422 if (buf->d->bak_clean || isReadonly())
3425 message(_("Autosaving current document..."));
3426 buf->d->bak_clean = true;
3428 FileName const fname = getAutosaveFileName();
3429 if (d->cloned_buffer_) {
3430 // If this buffer is cloned, we assume that
3431 // we are running in a separate thread already.
3432 FileName const tmp_ret = FileName::tempName("lyxauto");
3433 if (!tmp_ret.empty()) {
3435 // assume successful write of tmp_ret
3436 if (tmp_ret.moveTo(fname))
3439 // failed to write/rename tmp_ret so try writing direct
3440 return writeFile(fname);
3442 /// This function is deprecated as the frontend needs to take care
3443 /// of cloning the buffer and autosaving it in another thread. It
3444 /// is still here to allow (QT_VERSION < 0x040400).
3445 AutoSaveBuffer autosave(*this, fname);
3453 // helper class, to guarantee this gets reset properly
3454 class MarkAsExporting {
3456 MarkAsExporting(Buffer const * buf) : buf_(buf)
3458 LASSERT(buf_, /* */);
3459 buf_->setExportStatus(true);
3463 buf_->setExportStatus(false);
3466 Buffer const * const buf_;
3471 void Buffer::setExportStatus(bool e) const
3473 d->doing_export = e;
3474 ListOfBuffers clist = getDescendents();
3475 ListOfBuffers::const_iterator cit = clist.begin();
3476 ListOfBuffers::const_iterator const cen = clist.end();
3477 for (; cit != cen; ++cit)
3478 (*cit)->d->doing_export = e;
3482 bool Buffer::isExporting() const
3484 return d->doing_export;
3488 bool Buffer::doExport(string const & target, bool put_in_tempdir,
3489 bool includeall, string & result_file) const
3491 LYXERR(Debug::FILES, "target=" << target << ", result_file=" << result_file);
3492 OutputParams runparams(¶ms().encoding());
3493 string format = target;
3494 string dest_filename;
3495 size_t pos = target.find(' ');
3496 if (pos != string::npos) {
3497 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
3498 format = target.substr(0, pos);
3499 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
3500 FileName(dest_filename).onlyPath().createPath();
3501 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
3503 MarkAsExporting exporting(this);
3504 string backend_format;
3505 runparams.flavor = OutputParams::LATEX;
3506 runparams.linelen = lyxrc.plaintext_linelen;
3507 runparams.includeall = includeall;
3508 vector<string> backs = params().backends();
3509 Converters converters = theConverters();
3510 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3511 // Get shortest path to format
3512 converters.buildGraph();
3513 Graph::EdgePath path;
3514 for (vector<string>::const_iterator it = backs.begin();
3515 it != backs.end(); ++it) {
3516 Graph::EdgePath p = converters.getPath(*it, format);
3517 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3518 backend_format = *it;
3523 if (!put_in_tempdir) {
3524 // Only show this alert if this is an export to a non-temporary
3525 // file (not for previewing).
3526 Alert::error(_("Couldn't export file"), bformat(
3527 _("No information for exporting the format %1$s."),
3528 formats.prettyName(format)));
3532 runparams.flavor = converters.getFlavor(path);
3535 backend_format = format;
3536 LYXERR(Debug::FILES, "backend_format=" << backend_format);
3537 // FIXME: Don't hardcode format names here, but use a flag
3538 if (backend_format == "pdflatex")
3539 runparams.flavor = OutputParams::PDFLATEX;
3540 else if (backend_format == "luatex")
3541 runparams.flavor = OutputParams::LUATEX;
3542 else if (backend_format == "dviluatex")
3543 runparams.flavor = OutputParams::DVILUATEX;
3544 else if (backend_format == "xetex")
3545 runparams.flavor = OutputParams::XETEX;
3548 string filename = latexName(false);
3549 filename = addName(temppath(), filename);
3550 filename = changeExtension(filename,
3551 formats.extension(backend_format));
3552 LYXERR(Debug::FILES, "filename=" << filename);
3554 // Plain text backend
3555 if (backend_format == "text") {
3556 runparams.flavor = OutputParams::TEXT;
3557 writePlaintextFile(*this, FileName(filename), runparams);
3560 else if (backend_format == "xhtml") {
3561 runparams.flavor = OutputParams::HTML;
3562 switch (params().html_math_output) {
3563 case BufferParams::MathML:
3564 runparams.math_flavor = OutputParams::MathAsMathML;
3566 case BufferParams::HTML:
3567 runparams.math_flavor = OutputParams::MathAsHTML;
3569 case BufferParams::Images:
3570 runparams.math_flavor = OutputParams::MathAsImages;
3572 case BufferParams::LaTeX:
3573 runparams.math_flavor = OutputParams::MathAsLaTeX;
3576 makeLyXHTMLFile(FileName(filename), runparams);
3577 } else if (backend_format == "lyx")
3578 writeFile(FileName(filename));
3580 else if (params().isDocBook()) {
3581 runparams.nice = !put_in_tempdir;
3582 makeDocBookFile(FileName(filename), runparams);
3585 else if (backend_format == format) {
3586 runparams.nice = true;
3587 if (!makeLaTeXFile(FileName(filename), string(), runparams)) {
3588 if (d->cloned_buffer_) {
3589 d->cloned_buffer_->d->errorLists["Export"] =
3590 d->errorLists["Export"];
3594 } else if (!lyxrc.tex_allows_spaces
3595 && contains(filePath(), ' ')) {
3596 Alert::error(_("File name error"),
3597 _("The directory path to the document cannot contain spaces."));
3600 runparams.nice = false;
3601 if (!makeLaTeXFile(FileName(filename), filePath(), runparams)) {
3602 if (d->cloned_buffer_) {
3603 d->cloned_buffer_->d->errorLists["Export"] =
3604 d->errorLists["Export"];
3610 string const error_type = (format == "program")
3611 ? "Build" : params().bufferFormat();
3612 ErrorList & error_list = d->errorLists[error_type];
3613 string const ext = formats.extension(format);
3614 FileName const tmp_result_file(changeExtension(filename, ext));
3615 bool const success = converters.convert(this, FileName(filename),
3616 tmp_result_file, FileName(absFileName()), backend_format, format,
3619 // Emit the signal to show the error list or copy it back to the
3620 // cloned Buffer so that it can be emitted afterwards.
3621 if (format != backend_format) {
3622 if (d->cloned_buffer_) {
3623 d->cloned_buffer_->d->errorLists[error_type] =
3624 d->errorLists[error_type];
3627 // also to the children, in case of master-buffer-view
3628 ListOfBuffers clist = getDescendents();
3629 ListOfBuffers::const_iterator cit = clist.begin();
3630 ListOfBuffers::const_iterator const cen = clist.end();
3631 for (; cit != cen; ++cit) {
3632 if (d->cloned_buffer_) {
3633 // Enable reverse search by copying back the
3634 // texrow object to the cloned buffer.
3635 // FIXME: this is not thread safe.
3636 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
3637 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
3638 (*cit)->d->errorLists[error_type];
3640 (*cit)->errors(error_type, true);
3644 if (d->cloned_buffer_) {
3645 // Enable reverse dvi or pdf to work by copying back the texrow
3646 // object to the cloned buffer.
3647 // FIXME: There is a possibility of concurrent access to texrow
3648 // here from the main GUI thread that should be securized.
3649 d->cloned_buffer_->d->texrow = d->texrow;
3650 string const error_type = params().bufferFormat();
3651 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
3657 if (put_in_tempdir) {
3658 result_file = tmp_result_file.absFileName();
3662 if (dest_filename.empty())
3663 result_file = changeExtension(d->exportFileName().absFileName(), ext);
3665 result_file = dest_filename;
3666 // We need to copy referenced files (e. g. included graphics
3667 // if format == "dvi") to the result dir.
3668 vector<ExportedFile> const files =
3669 runparams.exportdata->externalFiles(format);
3670 string const dest = runparams.export_folder.empty() ?
3671 onlyPath(result_file) : runparams.export_folder;
3672 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
3673 : force_overwrite == ALL_FILES;
3674 CopyStatus status = use_force ? FORCE : SUCCESS;
3676 vector<ExportedFile>::const_iterator it = files.begin();
3677 vector<ExportedFile>::const_iterator const en = files.end();
3678 for (; it != en && status != CANCEL; ++it) {
3679 string const fmt = formats.getFormatFromFile(it->sourceName);
3680 string fixedName = it->exportName;
3681 if (!runparams.export_folder.empty()) {
3682 // Relative pathnames starting with ../ will be sanitized
3683 // if exporting to a different folder
3684 while (fixedName.substr(0, 3) == "../")
3685 fixedName = fixedName.substr(3, fixedName.length() - 3);
3687 FileName fixedFileName = makeAbsPath(fixedName, dest);
3688 fixedFileName.onlyPath().createPath();
3689 status = copyFile(fmt, it->sourceName,
3691 it->exportName, status == FORCE,
3692 runparams.export_folder.empty());
3695 if (status == CANCEL) {
3696 message(_("Document export cancelled."));
3697 } else if (tmp_result_file.exists()) {
3698 // Finally copy the main file
3699 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
3700 : force_overwrite != NO_FILES;
3701 if (status == SUCCESS && use_force)
3703 status = copyFile(format, tmp_result_file,
3704 FileName(result_file), result_file,
3706 message(bformat(_("Document exported as %1$s "
3708 formats.prettyName(format),
3709 makeDisplayPath(result_file)));
3711 // This must be a dummy converter like fax (bug 1888)
3712 message(bformat(_("Document exported as %1$s"),
3713 formats.prettyName(format)));
3720 bool Buffer::doExport(string const & target, bool put_in_tempdir,
3721 bool includeall) const
3724 // (1) export with all included children (omit \includeonly)
3725 if (includeall && !doExport(target, put_in_tempdir, true, result_file))
3727 // (2) export with included children only
3728 return doExport(target, put_in_tempdir, false, result_file);
3732 bool Buffer::preview(string const & format, bool includeall) const
3734 MarkAsExporting exporting(this);
3736 // (1) export with all included children (omit \includeonly)
3737 if (includeall && !doExport(format, true, true))
3739 // (2) export with included children only
3740 if (!doExport(format, true, false, result_file))
3742 return formats.view(*this, FileName(result_file), format);
3746 Buffer::ReadStatus Buffer::extractFromVC()
3748 bool const found = LyXVC::file_not_found_hook(d->filename);
3750 return ReadFileNotFound;
3751 if (!d->filename.isReadableFile())
3757 Buffer::ReadStatus Buffer::loadEmergency()
3759 FileName const emergencyFile = getEmergencyFileName();
3760 if (!emergencyFile.exists()
3761 || emergencyFile.lastModified() <= d->filename.lastModified())
3762 return ReadFileNotFound;
3764 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
3765 docstring const text = bformat(_("An emergency save of the document "
3766 "%1$s exists.\n\nRecover emergency save?"), file);
3768 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
3769 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
3775 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
3776 bool const success = (ret_llf == ReadSuccess);
3779 Alert::warning(_("File is read-only"),
3780 bformat(_("An emergency file is successfully loaded, "
3781 "but the original file %1$s is marked read-only. "
3782 "Please make sure to save the document as a different "
3783 "file."), from_utf8(d->filename.absFileName())));
3786 str = _("Document was successfully recovered.");
3788 str = _("Document was NOT successfully recovered.");
3789 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3790 makeDisplayPath(emergencyFile.absFileName()));
3792 int const del_emerg =
3793 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3794 _("&Remove"), _("&Keep"));
3795 if (del_emerg == 0) {
3796 emergencyFile.removeFile();
3798 Alert::warning(_("Emergency file deleted"),
3799 _("Do not forget to save your file now!"), true);
3801 return success ? ReadSuccess : ReadEmergencyFailure;
3804 int const del_emerg =
3805 Alert::prompt(_("Delete emergency file?"),
3806 _("Remove emergency file now?"), 1, 1,
3807 _("&Remove"), _("&Keep"));
3809 emergencyFile.removeFile();
3810 return ReadOriginal;
3820 Buffer::ReadStatus Buffer::loadAutosave()
3822 // Now check if autosave file is newer.
3823 FileName const autosaveFile = getAutosaveFileName();
3824 if (!autosaveFile.exists()
3825 || autosaveFile.lastModified() <= d->filename.lastModified())
3826 return ReadFileNotFound;
3828 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
3829 docstring const text = bformat(_("The backup of the document %1$s "
3830 "is newer.\n\nLoad the backup instead?"), file);
3831 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
3832 _("&Load backup"), _("Load &original"), _("&Cancel"));
3837 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
3838 // the file is not saved if we load the autosave file.
3839 if (ret_llf == ReadSuccess) {
3841 Alert::warning(_("File is read-only"),
3842 bformat(_("A backup file is successfully loaded, "
3843 "but the original file %1$s is marked read-only. "
3844 "Please make sure to save the document as a "
3846 from_utf8(d->filename.absFileName())));
3851 return ReadAutosaveFailure;
3854 // Here we delete the autosave
3855 autosaveFile.removeFile();
3856 return ReadOriginal;
3864 Buffer::ReadStatus Buffer::loadLyXFile()
3866 if (!d->filename.isReadableFile()) {
3867 ReadStatus const ret_rvc = extractFromVC();
3868 if (ret_rvc != ReadSuccess)
3872 ReadStatus const ret_re = loadEmergency();
3873 if (ret_re == ReadSuccess || ret_re == ReadCancel)
3876 ReadStatus const ret_ra = loadAutosave();
3877 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
3880 return loadThisLyXFile(d->filename);
3884 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
3886 return readFile(fn);
3890 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3892 TeXErrors::Errors::const_iterator it = terr.begin();
3893 TeXErrors::Errors::const_iterator end = terr.end();
3894 ListOfBuffers clist = getDescendents();
3895 ListOfBuffers::const_iterator cen = clist.end();
3897 for (; it != end; ++it) {
3900 int errorRow = it->error_in_line;
3901 Buffer const * buf = 0;
3903 if (it->child_name.empty())
3904 p->texrow.getIdFromRow(errorRow, id_start, pos_start);
3906 // The error occurred in a child
3907 ListOfBuffers::const_iterator cit = clist.begin();
3908 for (; cit != cen; ++cit) {
3909 string const child_name =
3910 DocFileName(changeExtension(
3911 (*cit)->absFileName(), "tex")).
3913 if (it->child_name != child_name)
3915 (*cit)->d->texrow.getIdFromRow(errorRow,
3916 id_start, pos_start);
3917 if (id_start != -1) {
3918 buf = d->cloned_buffer_
3919 ? (*cit)->d->cloned_buffer_->d->owner_
3920 : (*cit)->d->owner_;
3931 found = p->texrow.getIdFromRow(errorRow, id_end, pos_end);
3932 } while (found && id_start == id_end && pos_start == pos_end);
3934 if (id_start != id_end) {
3935 // Next registered position is outside the inset where
3936 // the error occurred, so signal end-of-paragraph
3940 errorList.push_back(ErrorItem(it->error_desc,
3941 it->error_text, id_start, pos_start, pos_end, buf));
3946 void Buffer::setBuffersForInsets() const
3948 inset().setBuffer(const_cast<Buffer &>(*this));
3952 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
3954 // Use the master text class also for child documents
3955 Buffer const * const master = masterBuffer();
3956 DocumentClass const & textclass = master->params().documentClass();
3958 // do this only if we are the top-level Buffer
3960 reloadBibInfoCache();
3962 // keep the buffers to be children in this set. If the call from the
3963 // master comes back we can see which of them were actually seen (i.e.
3964 // via an InsetInclude). The remaining ones in the set need still be updated.
3965 static std::set<Buffer const *> bufToUpdate;
3966 if (scope == UpdateMaster) {
3967 // If this is a child document start with the master
3968 if (master != this) {
3969 bufToUpdate.insert(this);
3970 master->updateBuffer(UpdateMaster, utype);
3971 // Do this here in case the master has no gui associated with it. Then,
3972 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3973 if (!master->d->gui_)
3976 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3977 if (bufToUpdate.find(this) == bufToUpdate.end())
3981 // start over the counters in the master
3982 textclass.counters().reset();
3985 // update will be done below for this buffer
3986 bufToUpdate.erase(this);
3988 // update all caches
3989 clearReferenceCache();
3992 Buffer & cbuf = const_cast<Buffer &>(*this);
3994 LASSERT(!text().paragraphs().empty(), /**/);
3997 ParIterator parit = cbuf.par_iterator_begin();
3998 updateBuffer(parit, utype);
4001 // TocBackend update will be done later.
4004 d->bibinfo_cache_valid_ = true;
4005 d->cite_labels_valid_ = true;
4006 cbuf.tocBackend().update();
4007 if (scope == UpdateMaster)
4008 cbuf.structureChanged();
4012 static depth_type getDepth(DocIterator const & it)
4014 depth_type depth = 0;
4015 for (size_t i = 0 ; i < it.depth() ; ++i)
4016 if (!it[i].inset().inMathed())
4017 depth += it[i].paragraph().getDepth() + 1;
4018 // remove 1 since the outer inset does not count
4022 static depth_type getItemDepth(ParIterator const & it)
4024 Paragraph const & par = *it;
4025 LabelType const labeltype = par.layout().labeltype;
4027 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4030 // this will hold the lowest depth encountered up to now.
4031 depth_type min_depth = getDepth(it);
4032 ParIterator prev_it = it;
4035 --prev_it.top().pit();
4037 // start of nested inset: go to outer par
4039 if (prev_it.empty()) {
4040 // start of document: nothing to do
4045 // We search for the first paragraph with same label
4046 // that is not more deeply nested.
4047 Paragraph & prev_par = *prev_it;
4048 depth_type const prev_depth = getDepth(prev_it);
4049 if (labeltype == prev_par.layout().labeltype) {
4050 if (prev_depth < min_depth)
4051 return prev_par.itemdepth + 1;
4052 if (prev_depth == min_depth)
4053 return prev_par.itemdepth;
4055 min_depth = min(min_depth, prev_depth);
4056 // small optimization: if we are at depth 0, we won't
4057 // find anything else
4058 if (prev_depth == 0)
4064 static bool needEnumCounterReset(ParIterator const & it)
4066 Paragraph const & par = *it;
4067 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
4068 depth_type const cur_depth = par.getDepth();
4069 ParIterator prev_it = it;
4070 while (prev_it.pit()) {
4071 --prev_it.top().pit();
4072 Paragraph const & prev_par = *prev_it;
4073 if (prev_par.getDepth() <= cur_depth)
4074 return prev_par.layout().labeltype != LABEL_ENUMERATE;
4076 // start of nested inset: reset
4081 // set the label of a paragraph. This includes the counters.
4082 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4084 BufferParams const & bp = owner_->masterBuffer()->params();
4085 DocumentClass const & textclass = bp.documentClass();
4086 Paragraph & par = it.paragraph();
4087 Layout const & layout = par.layout();
4088 Counters & counters = textclass.counters();
4090 if (par.params().startOfAppendix()) {
4091 // FIXME: only the counter corresponding to toplevel
4092 // sectioning should be reset
4094 counters.appendix(true);
4096 par.params().appendix(counters.appendix());
4098 // Compute the item depth of the paragraph
4099 par.itemdepth = getItemDepth(it);
4101 if (layout.margintype == MARGIN_MANUAL) {
4102 if (par.params().labelWidthString().empty())
4103 par.params().labelWidthString(par.expandLabel(layout, bp));
4104 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4105 // we do not need to do anything here, since the empty case is
4106 // handled during export.
4108 par.params().labelWidthString(docstring());
4111 switch(layout.labeltype) {
4113 if (layout.toclevel <= bp.secnumdepth
4114 && (layout.latextype != LATEX_ENVIRONMENT
4115 || it.text()->isFirstInSequence(it.pit()))) {
4116 if (counters.hasCounter(layout.counter))
4117 counters.step(layout.counter, utype);
4118 par.params().labelString(par.expandLabel(layout, bp));
4120 par.params().labelString(docstring());
4123 case LABEL_ITEMIZE: {
4124 // At some point of time we should do something more
4125 // clever here, like:
4126 // par.params().labelString(
4127 // bp.user_defined_bullet(par.itemdepth).getText());
4128 // for now, use a simple hardcoded label
4129 docstring itemlabel;
4130 switch (par.itemdepth) {
4132 itemlabel = char_type(0x2022);
4135 itemlabel = char_type(0x2013);
4138 itemlabel = char_type(0x2217);
4141 itemlabel = char_type(0x2219); // or 0x00b7
4144 par.params().labelString(itemlabel);
4148 case LABEL_ENUMERATE: {
4149 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4151 switch (par.itemdepth) {
4160 enumcounter += "iv";
4163 // not a valid enumdepth...
4167 // Maybe we have to reset the enumeration counter.
4168 if (needEnumCounterReset(it))
4169 counters.reset(enumcounter);
4170 counters.step(enumcounter, utype);
4172 string const & lang = par.getParLanguage(bp)->code();
4173 par.params().labelString(counters.theCounter(enumcounter, lang));
4178 case LABEL_SENSITIVE: {
4179 string const & type = counters.current_float();
4180 docstring full_label;
4182 full_label = owner_->B_("Senseless!!! ");
4184 docstring name = owner_->B_(textclass.floats().getType(type).name());
4185 if (counters.hasCounter(from_utf8(type))) {
4186 string const & lang = par.getParLanguage(bp)->code();
4187 counters.step(from_utf8(type), utype);
4188 full_label = bformat(from_ascii("%1$s %2$s:"),
4190 counters.theCounter(from_utf8(type), lang));
4192 full_label = bformat(from_ascii("%1$s #:"), name);
4194 par.params().labelString(full_label);
4198 case LABEL_NO_LABEL:
4199 par.params().labelString(docstring());
4203 case LABEL_TOP_ENVIRONMENT:
4204 case LABEL_CENTERED_TOP_ENVIRONMENT:
4207 par.params().labelString(par.expandLabel(layout, bp));
4213 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4215 LASSERT(parit.pit() == 0, /**/);
4217 // Set the position of the text in the buffer to be able
4218 // to resolve macros in it.
4219 parit.text()->setMacrocontextPosition(parit);
4221 depth_type maxdepth = 0;
4222 pit_type const lastpit = parit.lastpit();
4223 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4224 // reduce depth if necessary
4225 parit->params().depth(min(parit->params().depth(), maxdepth));
4226 maxdepth = parit->getMaxDepthAfter();
4228 if (utype == OutputUpdate) {
4229 // track the active counters
4230 // we have to do this for the master buffer, since the local
4231 // buffer isn't tracking anything.
4232 masterBuffer()->params().documentClass().counters().
4233 setActiveLayout(parit->layout());
4236 // set the counter for this paragraph
4237 d->setLabel(parit, utype);
4240 InsetList::const_iterator iit = parit->insetList().begin();
4241 InsetList::const_iterator end = parit->insetList().end();
4242 for (; iit != end; ++iit) {
4243 parit.pos() = iit->pos;
4244 iit->inset->updateBuffer(parit, utype);
4250 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4251 WordLangTuple & word_lang, docstring_list & suggestions) const
4255 suggestions.clear();
4256 word_lang = WordLangTuple();
4257 bool const to_end = to.empty();
4258 DocIterator const end = to_end ? doc_iterator_end(this) : to;
4259 // OK, we start from here.
4260 for (; from != end; from.forwardPos()) {
4261 // We are only interested in text so remove the math CursorSlice.
4262 while (from.inMathed()) {
4266 // If from is at the end of the document (which is possible
4267 // when leaving the mathed) LyX will crash later otherwise.
4268 if (from.atEnd() || (!to_end && from >= end))
4271 from.paragraph().spellCheck();
4272 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4273 if (SpellChecker::misspelled(res)) {
4278 // Do not increase progress when from == to, otherwise the word
4279 // count will be wrong.
4289 Buffer::ReadStatus Buffer::reload()
4292 // c.f. bug http://www.lyx.org/trac/ticket/6587
4293 removeAutosaveFile();
4294 // e.g., read-only status could have changed due to version control
4295 d->filename.refresh();
4296 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4298 ReadStatus const status = loadLyXFile();
4299 if (status == ReadSuccess) {
4304 message(bformat(_("Document %1$s reloaded."), disp_fn));
4307 message(bformat(_("Could not reload document %1$s."), disp_fn));
4317 bool Buffer::saveAs(FileName const & fn)
4319 FileName const old_name = fileName();
4320 FileName const old_auto = getAutosaveFileName();
4321 bool const old_unnamed = isUnnamed();
4328 // bring the autosave file with us, just in case.
4329 moveAutosaveFile(old_auto);
4330 // validate version control data and
4331 // correct buffer title
4332 lyxvc().file_found_hook(fileName());
4334 // the file has now been saved to the new location.
4335 // we need to check that the locations of child buffers
4337 checkChildBuffers();
4341 // reset the old filename and unnamed state
4342 setFileName(old_name);
4343 setUnnamed(old_unnamed);
4349 // FIXME We could do better here, but it is complicated. What would be
4350 // nice is to offer either (a) to save the child buffer to an appropriate
4351 // location, so that it would "move with the master", or else (b) to update
4352 // the InsetInclude so that it pointed to the same file. But (a) is a bit
4353 // complicated, because the code for this lives in GuiView.
4354 void Buffer::checkChildBuffers()
4356 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4357 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4358 for (; it != en; ++it) {
4359 DocIterator dit = it->second;
4360 Buffer * cbuf = const_cast<Buffer *>(it->first);
4361 if (!cbuf || !theBufferList().isLoaded(cbuf))
4363 Inset * inset = dit.nextInset();
4364 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4365 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4366 docstring const & incfile = inset_inc->getParam("filename");
4367 string oldloc = cbuf->absFileName();
4368 string newloc = makeAbsPath(to_utf8(incfile),
4369 onlyPath(absFileName())).absFileName();
4370 if (oldloc == newloc)
4372 // the location of the child file is incorrect.
4373 Alert::warning(_("Included File Invalid"),
4374 bformat(_("Saving this document to a new location has made the file:\n"
4376 "inaccessible. You will need to update the included filename."),
4377 from_utf8(oldloc)));
4379 inset_inc->setChildBuffer(0);
4381 // invalidate cache of children
4382 d->children_positions.clear();
4383 d->position_to_children.clear();