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_;
359 unnamed = cloned_buffer_->d->unnamed;
363 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
364 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
366 LYXERR(Debug::INFO, "Buffer::Buffer()");
368 d->inset = new InsetText(*cloned_buffer->d->inset);
369 d->inset->setBuffer(*this);
370 // FIXME: optimize this loop somewhat, maybe by creating a new
371 // general recursive Inset::setId().
372 DocIterator it = doc_iterator_begin(this);
373 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
374 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
375 it.paragraph().setId(cloned_it.paragraph().id());
377 d->inset = new InsetText(this);
378 d->inset->setAutoBreakRows(true);
379 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
385 LYXERR(Debug::INFO, "Buffer::~Buffer()");
386 // here the buffer should take care that it is
387 // saved properly, before it goes into the void.
389 // GuiView already destroyed
393 // No need to do additional cleanups for internal buffer.
398 // loop over children
399 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
400 Impl::BufferPositionMap::iterator end = d->children_positions.end();
401 for (; it != end; ++it) {
402 Buffer * child = const_cast<Buffer *>(it->first);
403 if (d->cloned_buffer_)
405 // The child buffer might have been closed already.
406 else if (theBufferList().isLoaded(child))
407 theBufferList().releaseChild(this, child);
411 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
412 msg += emergencyWrite();
413 Alert::warning(_("Attempting to close changed document!"), msg);
416 // clear references to children in macro tables
417 d->children_positions.clear();
418 d->position_to_children.clear();
420 if (!d->cloned_buffer_ && !d->temppath.destroyDirectory()) {
421 Alert::warning(_("Could not remove temporary directory"),
422 bformat(_("Could not remove the temporary directory %1$s"),
423 from_utf8(d->temppath.absFileName())));
433 Buffer * Buffer::clone() const
436 masterBuffer()->clone(bufmap);
437 BufferMap::iterator it = bufmap.find(this);
438 LASSERT(it != bufmap.end(), return 0);
443 void Buffer::clone(BufferMap & bufmap) const
445 // have we already been cloned?
446 if (bufmap.find(this) != bufmap.end())
449 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
450 bufmap[this] = buffer_clone;
451 buffer_clone->d->macro_lock = true;
452 buffer_clone->d->children_positions.clear();
453 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
454 // math macro caches need to be rethought and simplified.
455 // I am not sure wether we should handle Buffer cloning here or in BufferList.
456 // Right now BufferList knows nothing about buffer clones.
457 Impl::PositionScopeBufferMap::iterator it = d->position_to_children.begin();
458 Impl::PositionScopeBufferMap::iterator end = d->position_to_children.end();
459 for (; it != end; ++it) {
460 DocIterator dit = it->first.clone(buffer_clone);
461 dit.setBuffer(buffer_clone);
462 Buffer * child = const_cast<Buffer *>(it->second.second);
464 child->clone(bufmap);
465 BufferMap::iterator const bit = bufmap.find(child);
466 LASSERT(bit != bufmap.end(), continue);
467 Buffer * child_clone = bit->second;
469 Inset * inset = dit.nextInset();
470 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
471 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
472 inset_inc->setChildBuffer(child_clone);
473 child_clone->d->setParent(buffer_clone);
474 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
475 buffer_clone->setChild(dit, child_clone);
477 buffer_clone->d->macro_lock = false;
482 bool Buffer::isClone() const
484 return d->cloned_buffer_;
488 void Buffer::changed(bool update_metrics) const
491 d->wa_->redrawAll(update_metrics);
495 frontend::WorkAreaManager & Buffer::workAreaManager() const
497 LASSERT(d->wa_, /**/);
502 Text & Buffer::text() const
504 return d->inset->text();
508 Inset & Buffer::inset() const
514 BufferParams & Buffer::params()
520 BufferParams const & Buffer::params() const
526 ParagraphList & Buffer::paragraphs()
528 return text().paragraphs();
532 ParagraphList const & Buffer::paragraphs() const
534 return text().paragraphs();
538 LyXVC & Buffer::lyxvc()
544 LyXVC const & Buffer::lyxvc() const
550 string const Buffer::temppath() const
552 return d->temppath.absFileName();
556 TexRow & Buffer::texrow()
562 TexRow const & Buffer::texrow() const
568 TocBackend & Buffer::tocBackend() const
570 return d->toc_backend;
574 Undo & Buffer::undo()
580 void Buffer::setChild(DocIterator const & dit, Buffer * child)
582 d->children_positions[child] = dit;
586 string Buffer::latexName(bool const no_path) const
588 FileName latex_name =
589 makeLatexName(d->exportFileName());
590 return no_path ? latex_name.onlyFileName()
591 : latex_name.absFileName();
595 FileName Buffer::Impl::exportFileName() const
597 docstring const branch_suffix =
598 params.branchlist().getFileNameSuffix();
599 if (branch_suffix.empty())
602 string const name = filename.onlyFileNameWithoutExt()
603 + to_utf8(branch_suffix);
604 FileName res(filename.onlyPath().absFileName() + "/" + name);
605 res.changeExtension(filename.extension());
611 string Buffer::logName(LogType * type) const
613 string const filename = latexName(false);
615 if (filename.empty()) {
621 string const path = temppath();
623 FileName const fname(addName(temppath(),
624 onlyFileName(changeExtension(filename,
627 // FIXME: how do we know this is the name of the build log?
628 FileName const bname(
629 addName(path, onlyFileName(
630 changeExtension(filename,
631 formats.extension(params().bufferFormat()) + ".out"))));
633 // Also consider the master buffer log file
634 FileName masterfname = fname;
636 if (masterBuffer() != this) {
637 string const mlogfile = masterBuffer()->logName(&mtype);
638 masterfname = FileName(mlogfile);
641 // If no Latex log or Build log is newer, show Build log
642 if (bname.exists() &&
643 ((!fname.exists() && !masterfname.exists())
644 || (fname.lastModified() < bname.lastModified()
645 && masterfname.lastModified() < bname.lastModified()))) {
646 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
649 return bname.absFileName();
650 // If we have a newer master file log or only a master log, show this
651 } else if (fname != masterfname
652 && (!fname.exists() && (masterfname.exists()
653 || fname.lastModified() < masterfname.lastModified()))) {
654 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
657 return masterfname.absFileName();
659 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
662 return fname.absFileName();
666 void Buffer::setReadonly(bool const flag)
668 if (d->read_only != flag) {
675 void Buffer::setFileName(FileName const & fname)
678 setReadonly(d->filename.isReadOnly());
684 int Buffer::readHeader(Lexer & lex)
686 int unknown_tokens = 0;
688 int begin_header_line = -1;
690 // Initialize parameters that may be/go lacking in header:
691 params().branchlist().clear();
692 params().preamble.erase();
693 params().options.erase();
694 params().master.erase();
695 params().float_placement.erase();
696 params().paperwidth.erase();
697 params().paperheight.erase();
698 params().leftmargin.erase();
699 params().rightmargin.erase();
700 params().topmargin.erase();
701 params().bottommargin.erase();
702 params().headheight.erase();
703 params().headsep.erase();
704 params().footskip.erase();
705 params().columnsep.erase();
706 params().fonts_cjk.erase();
707 params().listings_params.clear();
708 params().clearLayoutModules();
709 params().clearRemovedModules();
710 params().clearIncludedChildren();
711 params().pdfoptions().clear();
712 params().indiceslist().clear();
713 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
714 params().isbackgroundcolor = false;
715 params().fontcolor = RGBColor(0, 0, 0);
716 params().isfontcolor = false;
717 params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
718 params().boxbgcolor = RGBColor(0xFF, 0, 0);
719 params().html_latex_start.clear();
720 params().html_latex_end.clear();
721 params().html_math_img_scale = 1.0;
722 params().output_sync_macro.erase();
724 for (int i = 0; i < 4; ++i) {
725 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
726 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
729 ErrorList & errorList = d->errorLists["Parse"];
738 if (token == "\\end_header")
742 if (token == "\\begin_header") {
743 begin_header_line = line;
747 LYXERR(Debug::PARSER, "Handling document header token: `"
750 string unknown = params().readToken(lex, token, d->filename.onlyPath());
751 if (!unknown.empty()) {
752 if (unknown[0] != '\\' && token == "\\textclass") {
753 Alert::warning(_("Unknown document class"),
754 bformat(_("Using the default document class, because the "
755 "class %1$s is unknown."), from_utf8(unknown)));
758 docstring const s = bformat(_("Unknown token: "
762 errorList.push_back(ErrorItem(_("Document header error"),
767 if (begin_header_line) {
768 docstring const s = _("\\begin_header is missing");
769 errorList.push_back(ErrorItem(_("Document header error"),
773 params().makeDocumentClass();
775 return unknown_tokens;
780 // changed to be public and have one parameter
781 // Returns true if "\end_document" is not read (Asger)
782 bool Buffer::readDocument(Lexer & lex)
784 ErrorList & errorList = d->errorLists["Parse"];
787 // remove dummy empty par
788 paragraphs().clear();
790 if (!lex.checkFor("\\begin_document")) {
791 docstring const s = _("\\begin_document is missing");
792 errorList.push_back(ErrorItem(_("Document header error"),
798 if (params().outputChanges) {
799 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
800 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
801 LaTeXFeatures::isAvailable("xcolor");
803 if (!dvipost && !xcolorulem) {
804 Alert::warning(_("Changes not shown in LaTeX output"),
805 _("Changes will not be highlighted in LaTeX output, "
806 "because neither dvipost nor xcolor/ulem are installed.\n"
807 "Please install these packages or redefine "
808 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
809 } else if (!xcolorulem) {
810 Alert::warning(_("Changes not shown in LaTeX output"),
811 _("Changes will not be highlighted in LaTeX output "
812 "when using pdflatex, because xcolor and ulem are not installed.\n"
813 "Please install both packages or redefine "
814 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
818 if (!params().master.empty()) {
819 FileName const master_file = makeAbsPath(params().master,
820 onlyPath(absFileName()));
821 if (isLyXFileName(master_file.absFileName())) {
823 checkAndLoadLyXFile(master_file, true);
825 // necessary e.g. after a reload
826 // to re-register the child (bug 5873)
827 // FIXME: clean up updateMacros (here, only
828 // child registering is needed).
829 master->updateMacros();
830 // set master as master buffer, but only
831 // if we are a real child
832 if (master->isChild(this))
834 // if the master is not fully loaded
835 // it is probably just loading this
836 // child. No warning needed then.
837 else if (master->isFullyLoaded())
838 LYXERR0("The master '"
840 << "' assigned to this document ("
842 << ") does not include "
843 "this document. Ignoring the master assignment.");
848 // assure we have a default index
849 params().indiceslist().addDefault(B_("Index"));
852 bool const res = text().read(lex, errorList, d->inset);
854 // inform parent buffer about local macros
856 Buffer const * pbuf = parent();
857 UserMacroSet::const_iterator cit = usermacros.begin();
858 UserMacroSet::const_iterator end = usermacros.end();
859 for (; cit != end; ++cit)
860 pbuf->usermacros.insert(*cit);
864 updateMacroInstances(InternalUpdate);
869 bool Buffer::readString(string const & s)
871 params().compressed = false;
876 FileName const fn = FileName::tempName("Buffer_readString");
879 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
880 if (ret_plf != ReadSuccess)
883 if (file_format != LYX_FORMAT) {
884 // We need to call lyx2lyx, so write the input to a file
885 ofstream os(fn.toFilesystemEncoding().c_str());
889 return readFile(fn) == ReadSuccess;
892 if (readDocument(lex))
898 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
902 if (!lex.setFile(fname)) {
903 Alert::error(_("File Not Found"),
904 bformat(_("Unable to open file `%1$s'."),
905 from_utf8(fn.absFileName())));
906 return ReadFileNotFound;
910 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
911 if (ret_plf != ReadSuccess)
914 if (file_format != LYX_FORMAT) {
916 ReadStatus const ret_clf = convertLyXFormat(fn, tmpFile, file_format);
917 if (ret_clf != ReadSuccess)
919 return readFile(tmpFile);
922 // FIXME: InsetInfo needs to know whether the file is under VCS
923 // during the parse process, so this has to be done before.
924 lyxvc().file_found_hook(d->filename);
926 if (readDocument(lex)) {
927 Alert::error(_("Document format failure"),
928 bformat(_("%1$s ended unexpectedly, which means"
929 " that it is probably corrupted."),
930 from_utf8(fn.absFileName())));
931 return ReadDocumentFailure;
934 d->file_fully_loaded = true;
935 d->read_only = !d->filename.isWritable();
936 params().compressed = d->filename.isZippedFile();
942 bool Buffer::isFullyLoaded() const
944 return d->file_fully_loaded;
948 void Buffer::setFullyLoaded(bool value)
950 d->file_fully_loaded = value;
954 PreviewLoader * Buffer::loader() const
956 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
958 if (!d->preview_loader_)
959 d->preview_loader_ = new PreviewLoader(*this);
960 return d->preview_loader_;
964 void Buffer::removePreviews() const
966 delete d->preview_loader_;
967 d->preview_loader_ = 0;
971 void Buffer::updatePreviews() const
973 PreviewLoader * ploader = loader();
977 InsetIterator it = inset_iterator_begin(*d->inset);
978 InsetIterator const end = inset_iterator_end(*d->inset);
979 for (; it != end; ++it)
980 it->addPreview(it, *ploader);
982 ploader->startLoading();
986 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
987 FileName const & fn, int & file_format) const
989 if(!lex.checkFor("\\lyxformat")) {
990 Alert::error(_("Document format failure"),
991 bformat(_("%1$s is not a readable LyX document."),
992 from_utf8(fn.absFileName())));
993 return ReadNoLyXFormat;
999 // LyX formats 217 and earlier were written as 2.17. This corresponds
1000 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1001 // these cases. See also: www.lyx.org/trac/changeset/1313.
1002 size_t dot = tmp_format.find_first_of(".,");
1003 if (dot != string::npos)
1004 tmp_format.erase(dot, 1);
1006 file_format = convert<int>(tmp_format);
1011 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1012 FileName & tmpfile, int from_format)
1014 tmpfile = FileName::tempName("Buffer_convertLyXFormat");
1015 if(tmpfile.empty()) {
1016 Alert::error(_("Conversion failed"),
1017 bformat(_("%1$s is from a different"
1018 " version of LyX, but a temporary"
1019 " file for converting it could"
1020 " not be created."),
1021 from_utf8(fn.absFileName())));
1022 return LyX2LyXNoTempFile;
1025 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1026 if (lyx2lyx.empty()) {
1027 Alert::error(_("Conversion script not found"),
1028 bformat(_("%1$s is from a different"
1029 " version of LyX, but the"
1030 " conversion script lyx2lyx"
1031 " could not be found."),
1032 from_utf8(fn.absFileName())));
1033 return LyX2LyXNotFound;
1037 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1038 ostringstream command;
1039 command << os::python()
1040 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1041 << " -t " << convert<string>(LYX_FORMAT)
1042 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
1043 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1044 string const command_str = command.str();
1046 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1048 cmd_ret const ret = runCommand(command_str);
1049 if (ret.first != 0) {
1050 if (from_format < LYX_FORMAT) {
1051 Alert::error(_("Conversion script failed"),
1052 bformat(_("%1$s is from an older version"
1053 " of LyX and the lyx2lyx script"
1054 " failed to convert it."),
1055 from_utf8(fn.absFileName())));
1056 return LyX2LyXOlderFormat;
1058 Alert::error(_("Conversion script failed"),
1059 bformat(_("%1$s is from a newer version"
1060 " of LyX and the lyx2lyx script"
1061 " failed to convert it."),
1062 from_utf8(fn.absFileName())));
1063 return LyX2LyXNewerFormat;
1070 // Should probably be moved to somewhere else: BufferView? GuiView?
1071 bool Buffer::save() const
1073 docstring const file = makeDisplayPath(absFileName(), 20);
1074 d->filename.refresh();
1076 // check the read-only status before moving the file as a backup
1077 if (d->filename.exists()) {
1078 bool const read_only = !d->filename.isWritable();
1080 Alert::warning(_("File is read-only"),
1081 bformat(_("The file %1$s cannot be written because it "
1082 "is marked as read-only."), file));
1087 // ask if the disk file has been externally modified (use checksum method)
1088 if (fileName().exists() && isExternallyModified(checksum_method)) {
1090 bformat(_("Document %1$s has been externally modified. "
1091 "Are you sure you want to overwrite this file?"), file);
1092 int const ret = Alert::prompt(_("Overwrite modified file?"),
1093 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1098 // We don't need autosaves in the immediate future. (Asger)
1099 resetAutosaveTimers();
1101 FileName backupName;
1102 bool madeBackup = false;
1104 // make a backup if the file already exists
1105 if (lyxrc.make_backup && fileName().exists()) {
1106 backupName = FileName(absFileName() + '~');
1107 if (!lyxrc.backupdir_path.empty()) {
1108 string const mangledName =
1109 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1110 backupName = FileName(addName(lyxrc.backupdir_path,
1114 // Except file is symlink do not copy because of #6587.
1115 // Hard links have bad luck.
1116 if (fileName().isSymLink())
1117 madeBackup = fileName().copyTo(backupName);
1119 madeBackup = fileName().moveTo(backupName);
1122 Alert::error(_("Backup failure"),
1123 bformat(_("Cannot create backup file %1$s.\n"
1124 "Please check whether the directory exists and is writable."),
1125 from_utf8(backupName.absFileName())));
1126 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1130 if (writeFile(d->filename)) {
1134 // Saving failed, so backup is not backup
1136 backupName.moveTo(d->filename);
1142 bool Buffer::writeFile(FileName const & fname) const
1144 // FIXME Do we need to do these here? I don't think writing
1145 // the LyX file depends upon it. (RGH)
1147 // updateMacroInstances();
1149 if (d->read_only && fname == d->filename)
1152 bool retval = false;
1154 docstring const str = bformat(_("Saving document %1$s..."),
1155 makeDisplayPath(fname.absFileName()));
1158 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1160 if (params().compressed) {
1161 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1162 retval = ofs && write(ofs);
1164 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1165 retval = ofs && write(ofs);
1169 message(str + _(" could not write file!"));
1174 // removeAutosaveFile();
1177 message(str + _(" done."));
1183 docstring Buffer::emergencyWrite()
1185 // No need to save if the buffer has not changed.
1189 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1191 docstring user_message = bformat(
1192 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1194 // We try to save three places:
1195 // 1) Same place as document. Unless it is an unnamed doc.
1197 string s = absFileName();
1200 if (writeFile(FileName(s))) {
1202 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1203 return user_message;
1205 user_message += " " + _("Save failed! Trying again...\n");
1209 // 2) In HOME directory.
1210 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1212 lyxerr << ' ' << s << endl;
1213 if (writeFile(FileName(s))) {
1215 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1216 return user_message;
1219 user_message += " " + _("Save failed! Trying yet again...\n");
1221 // 3) In "/tmp" directory.
1222 // MakeAbsPath to prepend the current
1223 // drive letter on OS/2
1224 s = addName(package().temp_dir().absFileName(), absFileName());
1226 lyxerr << ' ' << s << endl;
1227 if (writeFile(FileName(s))) {
1229 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1230 return user_message;
1233 user_message += " " + _("Save failed! Bummer. Document is lost.");
1236 return user_message;
1240 bool Buffer::write(ostream & ofs) const
1243 // Use the standard "C" locale for file output.
1244 ofs.imbue(locale::classic());
1247 // The top of the file should not be written by params().
1249 // write out a comment in the top of the file
1250 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1251 << " created this file. For more info see http://www.lyx.org/\n"
1252 << "\\lyxformat " << LYX_FORMAT << "\n"
1253 << "\\begin_document\n";
1255 /// For each author, set 'used' to true if there is a change
1256 /// by this author in the document; otherwise set it to 'false'.
1257 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1258 AuthorList::Authors::const_iterator a_end = params().authors().end();
1259 for (; a_it != a_end; ++a_it)
1260 a_it->setUsed(false);
1262 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1263 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1264 for ( ; it != end; ++it)
1265 it->checkAuthors(params().authors());
1267 // now write out the buffer parameters.
1268 ofs << "\\begin_header\n";
1269 params().writeFile(ofs);
1270 ofs << "\\end_header\n";
1273 ofs << "\n\\begin_body\n";
1275 ofs << "\n\\end_body\n";
1277 // Write marker that shows file is complete
1278 ofs << "\\end_document" << endl;
1280 // Shouldn't really be needed....
1283 // how to check if close went ok?
1284 // Following is an attempt... (BE 20001011)
1286 // good() returns false if any error occured, including some
1287 // formatting error.
1288 // bad() returns true if something bad happened in the buffer,
1289 // which should include file system full errors.
1294 lyxerr << "File was not closed properly." << endl;
1301 bool Buffer::makeLaTeXFile(FileName const & fname,
1302 string const & original_path,
1303 OutputParams const & runparams_in,
1304 OutputWhat output) const
1306 OutputParams runparams = runparams_in;
1308 // This is necessary for LuaTeX/XeTeX with tex fonts.
1309 // See FIXME in BufferParams::encoding()
1310 if (runparams.isFullUnicode())
1311 runparams.encoding = encodings.fromLyXName("utf8-plain");
1313 string const encoding = runparams.encoding->iconvName();
1314 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1317 try { ofs.reset(encoding); }
1318 catch (iconv_codecvt_facet_exception & e) {
1319 lyxerr << "Caught iconv exception: " << e.what() << endl;
1320 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1321 "verify that the support software for your encoding (%1$s) is "
1322 "properly installed"), from_ascii(encoding)));
1325 if (!openFileWrite(ofs, fname))
1328 //TexStream ts(ofs.rdbuf(), &texrow());
1329 ErrorList & errorList = d->errorLists["Export"];
1331 bool failed_export = false;
1332 otexstream os(ofs, d->texrow);
1334 // make sure we are ready to export
1335 // this needs to be done before we validate
1336 // FIXME Do we need to do this all the time? I.e., in children
1337 // of a master we are exporting?
1339 updateMacroInstances(OutputUpdate);
1342 os.texrow().reset();
1343 writeLaTeXSource(os, original_path, runparams, output);
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 OutputWhat output) 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 bool const output_preamble =
1404 output == FullSource || output == OnlyPreamble;
1405 bool const output_body =
1406 output == FullSource || output == OnlyBody;
1408 // The starting paragraph of the coming rows is the
1409 // first paragraph of the document. (Asger)
1410 if (output_preamble && runparams.nice) {
1411 os << "%% LyX " << lyx_version << " created this file. "
1412 "For more info, see http://www.lyx.org/.\n"
1413 "%% Do not edit unless you really know what "
1416 LYXERR(Debug::INFO, "lyx document header finished");
1418 // There are a few differences between nice LaTeX and usual files:
1419 // usual files have \batchmode and special input@path to allow
1420 // inclusion of figures specified by an explicitly relative path
1421 // (i.e., a path starting with './' or '../') with either \input or
1422 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1423 // input@path is set when the actual parameter original_path is set.
1424 // This is done for usual tex-file, but not for nice-latex-file.
1425 // (Matthias 250696)
1426 // Note that input@path is only needed for something the user does
1427 // in the preamble, included .tex files or ERT, files included by
1428 // LyX work without it.
1429 if (output_preamble) {
1430 if (!runparams.nice) {
1431 // code for usual, NOT nice-latex-file
1432 os << "\\batchmode\n"; // changed from \nonstopmode
1434 if (!original_path.empty()) {
1436 // We don't know the encoding of inputpath
1437 docstring const inputpath = from_utf8(original_path);
1438 docstring uncodable_glyphs;
1439 Encoding const * const enc = runparams.encoding;
1441 for (size_t n = 0; n < inputpath.size(); ++n) {
1442 docstring const glyph =
1443 docstring(1, inputpath[n]);
1444 if (enc->latexChar(inputpath[n], true) != glyph) {
1445 LYXERR0("Uncodable character '"
1447 << "' in input path!");
1448 uncodable_glyphs += glyph;
1453 // warn user if we found uncodable glyphs.
1454 if (!uncodable_glyphs.empty()) {
1455 frontend::Alert::warning(
1456 _("Uncodable character in file path"),
1458 _("The path of your document\n"
1460 "contains glyphs that are unknown "
1461 "in the current document encoding "
1462 "(namely %2$s). This may result in "
1463 "incomplete output, unless "
1464 "TEXINPUTS contains the document "
1465 "directory and you don't use "
1466 "explicitly relative paths (i.e., "
1467 "paths starting with './' or "
1468 "'../') in the preamble or in ERT."
1469 "\n\nIn case of problems, choose "
1470 "an appropriate document encoding\n"
1471 "(such as utf8) or change the "
1473 inputpath, uncodable_glyphs));
1476 support::latex_path(original_path);
1477 if (contains(docdir, '#')) {
1478 docdir = subst(docdir, "#", "\\#");
1479 os << "\\catcode`\\#=11"
1480 "\\def\\#{#}\\catcode`\\#=6\n";
1482 if (contains(docdir, '%')) {
1483 docdir = subst(docdir, "%", "\\%");
1484 os << "\\catcode`\\%=11"
1485 "\\def\\%{%}\\catcode`\\%=14\n";
1487 os << "\\makeatletter\n"
1488 << "\\def\\input@path{{"
1489 << docdir << "/}}\n"
1490 << "\\makeatother\n";
1494 // get parent macros (if this buffer has a parent) which will be
1495 // written at the document begin further down.
1496 MacroSet parentMacros;
1497 listParentMacros(parentMacros, features);
1499 runparams.use_polyglossia = features.usePolyglossia();
1500 // Write the preamble
1501 runparams.use_babel = params().writeLaTeX(os, features,
1502 d->filename.onlyPath());
1504 runparams.use_japanese = features.isRequired("japanese");
1510 os << "\\begin{document}\n";
1512 // output the parent macros
1513 MacroSet::iterator it = parentMacros.begin();
1514 MacroSet::iterator end = parentMacros.end();
1515 for (; it != end; ++it) {
1516 int num_lines = (*it)->write(os.os(), true);
1517 os.texrow().newlines(num_lines);
1520 } // output_preamble
1522 os.texrow().start(paragraphs().begin()->id(), 0);
1524 LYXERR(Debug::INFO, "preamble finished, now the body.");
1526 // if we are doing a real file with body, even if this is the
1527 // child of some other buffer, let's cut the link here.
1528 // This happens for example if only a child document is printed.
1529 Buffer const * save_parent = 0;
1530 if (output_preamble) {
1531 save_parent = d->parent();
1536 latexParagraphs(*this, text(), os, runparams);
1538 // Restore the parenthood if needed
1539 if (output_preamble)
1540 d->setParent(save_parent);
1542 // add this just in case after all the paragraphs
1545 if (output_preamble) {
1546 os << "\\end{document}\n";
1547 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1549 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1551 runparams_in.encoding = runparams.encoding;
1553 // Just to be sure. (Asger)
1554 os.texrow().newline();
1556 //for (int i = 0; i<d->texrow.rows(); i++) {
1558 // if (d->texrow.getIdFromRow(i+1,id,pos) && id>0)
1559 // lyxerr << i+1 << ":" << id << ":" << getParFromID(id).paragraph().asString()<<"\n";
1562 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1563 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
1567 void Buffer::makeDocBookFile(FileName const & fname,
1568 OutputParams const & runparams,
1569 OutputWhat output) const
1571 LYXERR(Debug::LATEX, "makeDocBookFile...");
1574 if (!openFileWrite(ofs, fname))
1577 // make sure we are ready to export
1578 // this needs to be done before we validate
1580 updateMacroInstances(OutputUpdate);
1582 writeDocBookSource(ofs, fname.absFileName(), runparams, output);
1586 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1590 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1591 OutputParams const & runparams,
1592 OutputWhat output) const
1594 LaTeXFeatures features(*this, params(), runparams);
1599 DocumentClass const & tclass = params().documentClass();
1600 string const top_element = tclass.latexname();
1602 bool const output_preamble =
1603 output == FullSource || output == OnlyPreamble;
1604 bool const output_body =
1605 output == FullSource || output == OnlyBody;
1607 if (output_preamble) {
1608 if (runparams.flavor == OutputParams::XML)
1609 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1612 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1615 if (! tclass.class_header().empty())
1616 os << from_ascii(tclass.class_header());
1617 else if (runparams.flavor == OutputParams::XML)
1618 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1619 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1621 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1623 docstring preamble = from_utf8(params().preamble);
1624 if (runparams.flavor != OutputParams::XML ) {
1625 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1626 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1627 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1628 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1631 string const name = runparams.nice
1632 ? changeExtension(absFileName(), ".sgml") : fname;
1633 preamble += features.getIncludedFiles(name);
1634 preamble += features.getLyXSGMLEntities();
1636 if (!preamble.empty()) {
1637 os << "\n [ " << preamble << " ]";
1642 string top = top_element;
1644 if (runparams.flavor == OutputParams::XML)
1645 top += params().language->code();
1647 top += params().language->code().substr(0, 2);
1650 if (!params().options.empty()) {
1652 top += params().options;
1655 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1656 << " file was created by LyX " << lyx_version
1657 << "\n See http://www.lyx.org/ for more information -->\n";
1659 params().documentClass().counters().reset();
1661 sgml::openTag(os, top);
1663 docbookParagraphs(text(), *this, os, runparams);
1664 sgml::closeTag(os, top_element);
1668 void Buffer::makeLyXHTMLFile(FileName const & fname,
1669 OutputParams const & runparams) const
1671 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1674 if (!openFileWrite(ofs, fname))
1677 // make sure we are ready to export
1678 // this has to be done before we validate
1679 updateBuffer(UpdateMaster, OutputUpdate);
1680 updateMacroInstances(OutputUpdate);
1682 writeLyXHTMLSource(ofs, runparams, FullSource);
1686 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1690 void Buffer::writeLyXHTMLSource(odocstream & os,
1691 OutputParams const & runparams,
1692 OutputWhat output) const
1694 LaTeXFeatures features(*this, params(), runparams);
1696 d->bibinfo_.makeCitationLabels(*this);
1698 bool const output_preamble =
1699 output == FullSource || output == OnlyPreamble;
1700 bool const output_body =
1701 output == FullSource || output == OnlyBody;
1703 if (output_preamble) {
1704 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1705 << "<!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"
1706 // FIXME Language should be set properly.
1707 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
1709 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
1710 // FIXME Presumably need to set this right
1711 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1713 docstring const & doctitle = features.htmlTitle();
1715 << (doctitle.empty() ? from_ascii("LyX Document") : doctitle)
1718 os << "\n<!-- Text Class Preamble -->\n"
1719 << features.getTClassHTMLPreamble()
1720 << "\n<!-- Preamble Snippets -->\n"
1721 << from_utf8(features.getPreambleSnippets());
1723 os << "\n<!-- Layout-provided Styles -->\n";
1724 docstring const styleinfo = features.getTClassHTMLStyles();
1725 if (!styleinfo.empty()) {
1726 os << "<style type='text/css'>\n"
1731 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
1732 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
1733 if (needfg || needbg) {
1734 os << "<style type='text/css'>\nbody {\n";
1737 << from_ascii(X11hexname(params().fontcolor))
1740 os << " background-color: "
1741 << from_ascii(X11hexname(params().backgroundcolor))
1743 os << "}\n</style>\n";
1745 os << "</head>\n<body>\n";
1749 params().documentClass().counters().reset();
1750 xhtmlParagraphs(text(), *this, xs, runparams);
1751 if (output_preamble)
1752 os << "</body>\n</html>\n";
1756 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1757 // Other flags: -wall -v0 -x
1758 int Buffer::runChktex()
1762 // get LaTeX-Filename
1763 FileName const path(temppath());
1764 string const name = addName(path.absFileName(), latexName());
1765 string const org_path = filePath();
1767 PathChanger p(path); // path to LaTeX file
1768 message(_("Running chktex..."));
1770 // Generate the LaTeX file if neccessary
1771 OutputParams runparams(¶ms().encoding());
1772 runparams.flavor = OutputParams::LATEX;
1773 runparams.nice = false;
1774 runparams.linelen = lyxrc.plaintext_linelen;
1775 makeLaTeXFile(FileName(name), org_path, runparams);
1778 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
1779 int const res = chktex.run(terr); // run chktex
1782 Alert::error(_("chktex failure"),
1783 _("Could not run chktex successfully."));
1784 } else if (res > 0) {
1785 ErrorList & errlist = d->errorLists["ChkTeX"];
1787 bufferErrors(terr, errlist);
1798 void Buffer::validate(LaTeXFeatures & features) const
1800 params().validate(features);
1802 for_each(paragraphs().begin(), paragraphs().end(),
1803 bind(&Paragraph::validate, _1, ref(features)));
1805 if (lyxerr.debugging(Debug::LATEX)) {
1806 features.showStruct();
1811 void Buffer::getLabelList(vector<docstring> & list) const
1813 // If this is a child document, use the master's list instead.
1815 masterBuffer()->getLabelList(list);
1820 Toc & toc = d->toc_backend.toc("label");
1821 TocIterator toc_it = toc.begin();
1822 TocIterator end = toc.end();
1823 for (; toc_it != end; ++toc_it) {
1824 if (toc_it->depth() == 0)
1825 list.push_back(toc_it->str());
1830 void Buffer::updateBibfilesCache(UpdateScope scope) const
1832 // FIXME This is probably unnecssary, given where we call this.
1833 // If this is a child document, use the parent's cache instead.
1834 if (parent() && scope != UpdateChildOnly) {
1835 masterBuffer()->updateBibfilesCache();
1839 d->bibfiles_cache_.clear();
1840 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1841 if (it->lyxCode() == BIBTEX_CODE) {
1842 InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
1843 support::FileNameList const bibfiles = inset.getBibFiles();
1844 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1847 } else if (it->lyxCode() == INCLUDE_CODE) {
1848 InsetInclude & inset = static_cast<InsetInclude &>(*it);
1849 Buffer const * const incbuf = inset.getChildBuffer();
1852 support::FileNameList const & bibfiles =
1853 incbuf->getBibfilesCache(UpdateChildOnly);
1854 if (!bibfiles.empty()) {
1855 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1861 d->bibfile_cache_valid_ = true;
1862 d->bibinfo_cache_valid_ = false;
1863 d->cite_labels_valid_ = false;
1867 void Buffer::invalidateBibinfoCache() const
1869 d->bibinfo_cache_valid_ = false;
1870 d->cite_labels_valid_ = false;
1871 // also invalidate the cache for the parent buffer
1872 Buffer const * const pbuf = d->parent();
1874 pbuf->invalidateBibinfoCache();
1878 void Buffer::invalidateBibfileCache() const
1880 d->bibfile_cache_valid_ = false;
1881 d->bibinfo_cache_valid_ = false;
1882 d->cite_labels_valid_ = false;
1883 // also invalidate the cache for the parent buffer
1884 Buffer const * const pbuf = d->parent();
1886 pbuf->invalidateBibfileCache();
1890 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1892 // FIXME This is probably unnecessary, given where we call this.
1893 // If this is a child document, use the master's cache instead.
1894 Buffer const * const pbuf = masterBuffer();
1895 if (pbuf != this && scope != UpdateChildOnly)
1896 return pbuf->getBibfilesCache();
1898 if (!d->bibfile_cache_valid_)
1899 this->updateBibfilesCache(scope);
1901 return d->bibfiles_cache_;
1905 BiblioInfo const & Buffer::masterBibInfo() const
1907 Buffer const * const tmp = masterBuffer();
1909 return tmp->masterBibInfo();
1914 void Buffer::checkIfBibInfoCacheIsValid() const
1916 // use the master's cache
1917 Buffer const * const tmp = masterBuffer();
1919 tmp->checkIfBibInfoCacheIsValid();
1923 // compare the cached timestamps with the actual ones.
1924 FileNameList const & bibfiles_cache = getBibfilesCache();
1925 FileNameList::const_iterator ei = bibfiles_cache.begin();
1926 FileNameList::const_iterator en = bibfiles_cache.end();
1927 for (; ei != en; ++ ei) {
1928 time_t lastw = ei->lastModified();
1929 time_t prevw = d->bibfile_status_[*ei];
1930 if (lastw != prevw) {
1931 d->bibinfo_cache_valid_ = false;
1932 d->cite_labels_valid_ = false;
1933 d->bibfile_status_[*ei] = lastw;
1939 void Buffer::reloadBibInfoCache() const
1941 // use the master's cache
1942 Buffer const * const tmp = masterBuffer();
1944 tmp->reloadBibInfoCache();
1948 checkIfBibInfoCacheIsValid();
1949 if (d->bibinfo_cache_valid_)
1952 d->bibinfo_.clear();
1954 d->bibinfo_cache_valid_ = true;
1958 void Buffer::collectBibKeys() const
1960 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1961 it->collectBibKeys(it);
1965 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
1967 Buffer const * tmp = masterBuffer();
1968 BiblioInfo & masterbi = (tmp == this) ?
1969 d->bibinfo_ : tmp->d->bibinfo_;
1970 masterbi.mergeBiblioInfo(bi);
1974 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
1976 Buffer const * tmp = masterBuffer();
1977 BiblioInfo & masterbi = (tmp == this) ?
1978 d->bibinfo_ : tmp->d->bibinfo_;
1983 bool Buffer::citeLabelsValid() const
1985 return masterBuffer()->d->cite_labels_valid_;
1989 bool Buffer::isDepClean(string const & name) const
1991 DepClean::const_iterator const it = d->dep_clean.find(name);
1992 if (it == d->dep_clean.end())
1998 void Buffer::markDepClean(string const & name)
2000 d->dep_clean[name] = true;
2004 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2007 // FIXME? if there is an Buffer LFUN that can be dispatched even
2008 // if internal, put a switch '(cmd.action)' here.
2014 switch (cmd.action()) {
2016 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2017 flag.setOnOff(isReadonly());
2020 // FIXME: There is need for a command-line import.
2021 //case LFUN_BUFFER_IMPORT:
2023 case LFUN_BUFFER_AUTO_SAVE:
2026 case LFUN_BUFFER_EXPORT_CUSTOM:
2027 // FIXME: Nothing to check here?
2030 case LFUN_BUFFER_EXPORT: {
2031 docstring const arg = cmd.argument();
2032 if (arg == "custom") {
2036 string format = to_utf8(arg);
2037 size_t pos = format.find(' ');
2038 if (pos != string::npos)
2039 format = format.substr(0, pos);
2040 enable = params().isExportable(format);
2042 flag.message(bformat(
2043 _("Don't know how to export to format: %1$s"), arg));
2047 case LFUN_BUFFER_CHKTEX:
2048 enable = params().isLatex() && !lyxrc.chktex_command.empty();
2051 case LFUN_BUILD_PROGRAM:
2052 enable = params().isExportable("program");
2055 case LFUN_BRANCH_ACTIVATE:
2056 case LFUN_BRANCH_DEACTIVATE: {
2057 BranchList const & branchList = params().branchlist();
2058 docstring const branchName = cmd.argument();
2059 enable = !branchName.empty() && branchList.find(branchName);
2063 case LFUN_BRANCH_ADD:
2064 case LFUN_BRANCHES_RENAME:
2065 case LFUN_BUFFER_PRINT:
2066 // if no Buffer is present, then of course we won't be called!
2069 case LFUN_BUFFER_LANGUAGE:
2070 enable = !isReadonly();
2076 flag.setEnabled(enable);
2081 void Buffer::dispatch(string const & command, DispatchResult & result)
2083 return dispatch(lyxaction.lookupFunc(command), result);
2087 // NOTE We can end up here even if we have no GUI, because we are called
2088 // by LyX::exec to handled command-line requests. So we may need to check
2089 // whether we have a GUI or not. The boolean use_gui holds this information.
2090 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2093 // FIXME? if there is an Buffer LFUN that can be dispatched even
2094 // if internal, put a switch '(cmd.action())' here.
2095 dr.dispatched(false);
2098 string const argument = to_utf8(func.argument());
2099 // We'll set this back to false if need be.
2100 bool dispatched = true;
2101 undo().beginUndoGroup();
2103 switch (func.action()) {
2104 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2105 if (lyxvc().inUse())
2106 lyxvc().toggleReadOnly();
2108 setReadonly(!isReadonly());
2111 case LFUN_BUFFER_EXPORT: {
2112 ExportStatus const status = doExport(argument, false, false);
2113 dr.setError(status != ExportSuccess);
2114 if (status != ExportSuccess)
2115 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2120 case LFUN_BUILD_PROGRAM:
2121 doExport("program", true, false);
2124 case LFUN_BUFFER_CHKTEX:
2128 case LFUN_BUFFER_EXPORT_CUSTOM: {
2130 string command = split(argument, format_name, ' ');
2131 Format const * format = formats.getFormat(format_name);
2133 lyxerr << "Format \"" << format_name
2134 << "\" not recognized!"
2139 // The name of the file created by the conversion process
2142 // Output to filename
2143 if (format->name() == "lyx") {
2144 string const latexname = latexName(false);
2145 filename = changeExtension(latexname,
2146 format->extension());
2147 filename = addName(temppath(), filename);
2149 if (!writeFile(FileName(filename)))
2153 doExport(format_name, true, false, filename);
2156 // Substitute $$FName for filename
2157 if (!contains(command, "$$FName"))
2158 command = "( " + command + " ) < $$FName";
2159 command = subst(command, "$$FName", filename);
2161 // Execute the command in the background
2163 call.startscript(Systemcall::DontWait, command, filePath());
2167 // FIXME: There is need for a command-line import.
2169 case LFUN_BUFFER_IMPORT:
2174 case LFUN_BUFFER_AUTO_SAVE:
2176 resetAutosaveTimers();
2179 case LFUN_BRANCH_ADD: {
2180 docstring branch_name = func.argument();
2181 if (branch_name.empty()) {
2185 BranchList & branch_list = params().branchlist();
2186 vector<docstring> const branches =
2187 getVectorFromString(branch_name, branch_list.separator());
2189 for (vector<docstring>::const_iterator it = branches.begin();
2190 it != branches.end(); ++it) {
2192 Branch * branch = branch_list.find(branch_name);
2194 LYXERR0("Branch " << branch_name << " already exists.");
2198 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2200 branch_list.add(branch_name);
2201 branch = branch_list.find(branch_name);
2202 string const x11hexname = X11hexname(branch->color());
2203 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2204 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2206 dr.screenUpdate(Update::Force);
2214 case LFUN_BRANCH_ACTIVATE:
2215 case LFUN_BRANCH_DEACTIVATE: {
2216 BranchList & branchList = params().branchlist();
2217 docstring const branchName = func.argument();
2218 // the case without a branch name is handled elsewhere
2219 if (branchName.empty()) {
2223 Branch * branch = branchList.find(branchName);
2225 LYXERR0("Branch " << branchName << " does not exist.");
2227 docstring const msg =
2228 bformat(_("Branch \"%1$s\" does not exist."), branchName);
2231 branch->setSelected(func.action() == LFUN_BRANCH_ACTIVATE);
2233 dr.screenUpdate(Update::Force);
2234 dr.forceBufferUpdate();
2239 case LFUN_BRANCHES_RENAME: {
2240 if (func.argument().empty())
2243 docstring const oldname = from_utf8(func.getArg(0));
2244 docstring const newname = from_utf8(func.getArg(1));
2245 InsetIterator it = inset_iterator_begin(inset());
2246 InsetIterator const end = inset_iterator_end(inset());
2247 bool success = false;
2248 for (; it != end; ++it) {
2249 if (it->lyxCode() == BRANCH_CODE) {
2250 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2251 if (ins.branch() == oldname) {
2252 undo().recordUndo(it);
2253 ins.rename(newname);
2258 if (it->lyxCode() == INCLUDE_CODE) {
2259 // get buffer of external file
2260 InsetInclude const & ins =
2261 static_cast<InsetInclude const &>(*it);
2262 Buffer * child = ins.getChildBuffer();
2265 child->dispatch(func, dr);
2270 dr.screenUpdate(Update::Force);
2271 dr.forceBufferUpdate();
2276 case LFUN_BUFFER_PRINT: {
2277 // we'll assume there's a problem until we succeed
2279 string target = func.getArg(0);
2280 string target_name = func.getArg(1);
2281 string command = func.getArg(2);
2284 || target_name.empty()
2285 || command.empty()) {
2286 LYXERR0("Unable to parse " << func.argument());
2287 docstring const msg =
2288 bformat(_("Unable to parse \"%1$s\""), func.argument());
2292 if (target != "printer" && target != "file") {
2293 LYXERR0("Unrecognized target \"" << target << '"');
2294 docstring const msg =
2295 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2300 if (!doExport("dvi", true)) {
2301 showPrintError(absFileName());
2302 dr.setMessage(_("Error exporting to DVI."));
2306 // Push directory path.
2307 string const path = temppath();
2308 // Prevent the compiler from optimizing away p
2312 // there are three cases here:
2313 // 1. we print to a file
2314 // 2. we print directly to a printer
2315 // 3. we print using a spool command (print to file first)
2318 string const dviname = changeExtension(latexName(true), "dvi");
2320 if (target == "printer") {
2321 if (!lyxrc.print_spool_command.empty()) {
2322 // case 3: print using a spool
2323 string const psname = changeExtension(dviname,".ps");
2324 command += ' ' + lyxrc.print_to_file
2327 + quoteName(dviname);
2329 string command2 = lyxrc.print_spool_command + ' ';
2330 if (target_name != "default") {
2331 command2 += lyxrc.print_spool_printerprefix
2335 command2 += quoteName(psname);
2337 // If successful, then spool command
2338 res = one.startscript(Systemcall::Wait, command,
2342 // If there's no GUI, we have to wait on this command. Otherwise,
2343 // LyX deletes the temporary directory, and with it the spooled
2344 // file, before it can be printed!!
2345 Systemcall::Starttype stype = use_gui ?
2346 Systemcall::DontWait : Systemcall::Wait;
2347 res = one.startscript(stype, command2,
2351 // case 2: print directly to a printer
2352 if (target_name != "default")
2353 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2355 Systemcall::Starttype stype = use_gui ?
2356 Systemcall::DontWait : Systemcall::Wait;
2357 res = one.startscript(stype, command +
2358 quoteName(dviname), filePath());
2362 // case 1: print to a file
2363 FileName const filename(makeAbsPath(target_name, filePath()));
2364 FileName const dvifile(makeAbsPath(dviname, path));
2365 if (filename.exists()) {
2366 docstring text = bformat(
2367 _("The file %1$s already exists.\n\n"
2368 "Do you want to overwrite that file?"),
2369 makeDisplayPath(filename.absFileName()));
2370 if (Alert::prompt(_("Overwrite file?"),
2371 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2374 command += ' ' + lyxrc.print_to_file
2375 + quoteName(filename.toFilesystemEncoding())
2377 + quoteName(dvifile.toFilesystemEncoding());
2379 Systemcall::Starttype stype = use_gui ?
2380 Systemcall::DontWait : Systemcall::Wait;
2381 res = one.startscript(stype, command, filePath());
2387 dr.setMessage(_("Error running external commands."));
2388 showPrintError(absFileName());
2397 dr.dispatched(dispatched);
2398 undo().endUndoGroup();
2402 void Buffer::changeLanguage(Language const * from, Language const * to)
2404 LASSERT(from, /**/);
2407 for_each(par_iterator_begin(),
2409 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2413 bool Buffer::isMultiLingual() const
2415 ParConstIterator end = par_iterator_end();
2416 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2417 if (it->isMultiLingual(params()))
2424 std::set<Language const *> Buffer::getLanguages() const
2426 std::set<Language const *> languages;
2427 getLanguages(languages);
2432 void Buffer::getLanguages(std::set<Language const *> & languages) const
2434 ParConstIterator end = par_iterator_end();
2435 // add the buffer language, even if it's not actively used
2436 languages.insert(language());
2437 // iterate over the paragraphs
2438 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2439 it->getLanguages(languages);
2441 ListOfBuffers clist = getDescendents();
2442 ListOfBuffers::const_iterator cit = clist.begin();
2443 ListOfBuffers::const_iterator const cen = clist.end();
2444 for (; cit != cen; ++cit)
2445 (*cit)->getLanguages(languages);
2449 DocIterator Buffer::getParFromID(int const id) const
2451 Buffer * buf = const_cast<Buffer *>(this);
2453 // John says this is called with id == -1 from undo
2454 lyxerr << "getParFromID(), id: " << id << endl;
2455 return doc_iterator_end(buf);
2458 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2459 if (it.paragraph().id() == id)
2462 return doc_iterator_end(buf);
2466 bool Buffer::hasParWithID(int const id) const
2468 return !getParFromID(id).atEnd();
2472 ParIterator Buffer::par_iterator_begin()
2474 return ParIterator(doc_iterator_begin(this));
2478 ParIterator Buffer::par_iterator_end()
2480 return ParIterator(doc_iterator_end(this));
2484 ParConstIterator Buffer::par_iterator_begin() const
2486 return ParConstIterator(doc_iterator_begin(this));
2490 ParConstIterator Buffer::par_iterator_end() const
2492 return ParConstIterator(doc_iterator_end(this));
2496 Language const * Buffer::language() const
2498 return params().language;
2502 docstring const Buffer::B_(string const & l10n) const
2504 return params().B_(l10n);
2508 bool Buffer::isClean() const
2510 return d->lyx_clean;
2514 bool Buffer::isExternallyModified(CheckMethod method) const
2516 LASSERT(d->filename.exists(), /**/);
2517 // if method == timestamp, check timestamp before checksum
2518 return (method == checksum_method
2519 || d->timestamp_ != d->filename.lastModified())
2520 && d->checksum_ != d->filename.checksum();
2524 void Buffer::saveCheckSum() const
2526 FileName const & file = d->filename;
2529 if (file.exists()) {
2530 d->timestamp_ = file.lastModified();
2531 d->checksum_ = file.checksum();
2533 // in the case of save to a new file.
2540 void Buffer::markClean() const
2542 if (!d->lyx_clean) {
2543 d->lyx_clean = true;
2546 // if the .lyx file has been saved, we don't need an
2548 d->bak_clean = true;
2549 d->undo_.markDirty();
2553 void Buffer::setUnnamed(bool flag)
2559 bool Buffer::isUnnamed() const
2566 /// Don't check unnamed, here: isInternal() is used in
2567 /// newBuffer(), where the unnamed flag has not been set by anyone
2568 /// yet. Also, for an internal buffer, there should be no need for
2569 /// retrieving fileName() nor for checking if it is unnamed or not.
2570 bool Buffer::isInternal() const
2572 return fileName().extension() == "internal";
2576 void Buffer::markDirty()
2579 d->lyx_clean = false;
2582 d->bak_clean = false;
2584 DepClean::iterator it = d->dep_clean.begin();
2585 DepClean::const_iterator const end = d->dep_clean.end();
2587 for (; it != end; ++it)
2592 FileName Buffer::fileName() const
2598 string Buffer::absFileName() const
2600 return d->filename.absFileName();
2604 string Buffer::filePath() const
2606 return d->filename.onlyPath().absFileName() + "/";
2610 bool Buffer::isReadonly() const
2612 return d->read_only;
2616 void Buffer::setParent(Buffer const * buffer)
2618 // Avoids recursive include.
2619 d->setParent(buffer == this ? 0 : buffer);
2624 Buffer const * Buffer::parent() const
2630 ListOfBuffers Buffer::allRelatives() const
2632 ListOfBuffers lb = masterBuffer()->getDescendents();
2633 lb.push_front(const_cast<Buffer *>(masterBuffer()));
2638 Buffer const * Buffer::masterBuffer() const
2640 // FIXME Should be make sure we are not in some kind
2641 // of recursive include? A -> B -> A will crash this.
2642 Buffer const * const pbuf = d->parent();
2646 return pbuf->masterBuffer();
2650 bool Buffer::isChild(Buffer * child) const
2652 return d->children_positions.find(child) != d->children_positions.end();
2656 DocIterator Buffer::firstChildPosition(Buffer const * child)
2658 Impl::BufferPositionMap::iterator it;
2659 it = d->children_positions.find(child);
2660 if (it == d->children_positions.end())
2661 return DocIterator(this);
2666 bool Buffer::hasChildren() const
2668 return !d->children_positions.empty();
2672 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
2674 // loop over children
2675 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2676 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2677 for (; it != end; ++it) {
2678 Buffer * child = const_cast<Buffer *>(it->first);
2680 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
2681 if (bit != clist.end())
2683 clist.push_back(child);
2685 // there might be grandchildren
2686 child->collectChildren(clist, true);
2691 ListOfBuffers Buffer::getChildren() const
2694 collectChildren(v, false);
2695 // Make sure we have not included ourselves.
2696 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
2697 if (bit != v.end()) {
2698 LYXERR0("Recursive include detected in `" << fileName() << "'.");
2705 ListOfBuffers Buffer::getDescendents() const
2708 collectChildren(v, true);
2709 // Make sure we have not included ourselves.
2710 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
2711 if (bit != v.end()) {
2712 LYXERR0("Recursive include detected in `" << fileName() << "'.");
2719 template<typename M>
2720 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
2725 typename M::const_iterator it = m.lower_bound(x);
2726 if (it == m.begin())
2734 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
2735 DocIterator const & pos) const
2737 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2739 // if paragraphs have no macro context set, pos will be empty
2743 // we haven't found anything yet
2744 DocIterator bestPos = owner_->par_iterator_begin();
2745 MacroData const * bestData = 0;
2747 // find macro definitions for name
2748 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
2749 if (nameIt != macros.end()) {
2750 // find last definition in front of pos or at pos itself
2751 PositionScopeMacroMap::const_iterator it
2752 = greatest_below(nameIt->second, pos);
2753 if (it != nameIt->second.end()) {
2755 // scope ends behind pos?
2756 if (pos < it->second.first) {
2757 // Looks good, remember this. If there
2758 // is no external macro behind this,
2759 // we found the right one already.
2760 bestPos = it->first;
2761 bestData = &it->second.second;
2765 // try previous macro if there is one
2766 if (it == nameIt->second.begin())
2773 // find macros in included files
2774 PositionScopeBufferMap::const_iterator it
2775 = greatest_below(position_to_children, pos);
2776 if (it == position_to_children.end())
2777 // no children before
2781 // do we know something better (i.e. later) already?
2782 if (it->first < bestPos )
2785 // scope ends behind pos?
2786 if (pos < it->second.first
2787 && (cloned_buffer_ ||
2788 theBufferList().isLoaded(it->second.second))) {
2789 // look for macro in external file
2791 MacroData const * data
2792 = it->second.second->getMacro(name, false);
2795 bestPos = it->first;
2801 // try previous file if there is one
2802 if (it == position_to_children.begin())
2807 // return the best macro we have found
2812 MacroData const * Buffer::getMacro(docstring const & name,
2813 DocIterator const & pos, bool global) const
2818 // query buffer macros
2819 MacroData const * data = d->getBufferMacro(name, pos);
2823 // If there is a master buffer, query that
2824 Buffer const * const pbuf = d->parent();
2826 d->macro_lock = true;
2827 MacroData const * macro = pbuf->getMacro(
2828 name, *this, false);
2829 d->macro_lock = false;
2835 data = MacroTable::globalMacros().get(name);
2844 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2846 // set scope end behind the last paragraph
2847 DocIterator scope = par_iterator_begin();
2848 scope.pit() = scope.lastpit() + 1;
2850 return getMacro(name, scope, global);
2854 MacroData const * Buffer::getMacro(docstring const & name,
2855 Buffer const & child, bool global) const
2857 // look where the child buffer is included first
2858 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2859 if (it == d->children_positions.end())
2862 // check for macros at the inclusion position
2863 return getMacro(name, it->second, global);
2867 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
2869 pit_type const lastpit = it.lastpit();
2871 // look for macros in each paragraph
2872 while (it.pit() <= lastpit) {
2873 Paragraph & par = it.paragraph();
2875 // iterate over the insets of the current paragraph
2876 InsetList const & insets = par.insetList();
2877 InsetList::const_iterator iit = insets.begin();
2878 InsetList::const_iterator end = insets.end();
2879 for (; iit != end; ++iit) {
2880 it.pos() = iit->pos;
2882 // is it a nested text inset?
2883 if (iit->inset->asInsetText()) {
2884 // Inset needs its own scope?
2885 InsetText const * itext = iit->inset->asInsetText();
2886 bool newScope = itext->isMacroScope();
2888 // scope which ends just behind the inset
2889 DocIterator insetScope = it;
2892 // collect macros in inset
2893 it.push_back(CursorSlice(*iit->inset));
2894 updateMacros(it, newScope ? insetScope : scope);
2899 if (iit->inset->asInsetTabular()) {
2900 CursorSlice slice(*iit->inset);
2901 size_t const numcells = slice.nargs();
2902 for (; slice.idx() < numcells; slice.forwardIdx()) {
2903 it.push_back(slice);
2904 updateMacros(it, scope);
2910 // is it an external file?
2911 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2912 // get buffer of external file
2913 InsetInclude const & inset =
2914 static_cast<InsetInclude const &>(*iit->inset);
2916 Buffer * child = inset.getChildBuffer();
2921 // register its position, but only when it is
2922 // included first in the buffer
2923 if (children_positions.find(child) ==
2924 children_positions.end())
2925 children_positions[child] = it;
2927 // register child with its scope
2928 position_to_children[it] = Impl::ScopeBuffer(scope, child);
2932 InsetMath * im = iit->inset->asInsetMath();
2933 if (doing_export && im) {
2934 InsetMathHull * hull = im->asHullInset();
2936 hull->recordLocation(it);
2939 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2943 MathMacroTemplate & macroTemplate =
2944 *iit->inset->asInsetMath()->asMacroTemplate();
2945 MacroContext mc(owner_, it);
2946 macroTemplate.updateToContext(mc);
2949 bool valid = macroTemplate.validMacro();
2950 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2951 // then the BufferView's cursor will be invalid in
2952 // some cases which leads to crashes.
2957 // FIXME (Abdel), I don't understandt why we pass 'it' here
2958 // instead of 'macroTemplate' defined above... is this correct?
2959 macros[macroTemplate.name()][it] =
2960 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
2970 void Buffer::updateMacros() const
2975 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2977 // start with empty table
2979 d->children_positions.clear();
2980 d->position_to_children.clear();
2982 // Iterate over buffer, starting with first paragraph
2983 // The scope must be bigger than any lookup DocIterator
2984 // later. For the global lookup, lastpit+1 is used, hence
2985 // we use lastpit+2 here.
2986 DocIterator it = par_iterator_begin();
2987 DocIterator outerScope = it;
2988 outerScope.pit() = outerScope.lastpit() + 2;
2989 d->updateMacros(it, outerScope);
2993 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
2995 InsetIterator it = inset_iterator_begin(inset());
2996 InsetIterator const end = inset_iterator_end(inset());
2997 for (; it != end; ++it) {
2998 if (it->lyxCode() == BRANCH_CODE) {
2999 InsetBranch & br = static_cast<InsetBranch &>(*it);
3000 docstring const name = br.branch();
3001 if (!from_master && !params().branchlist().find(name))
3002 result.push_back(name);
3003 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3004 result.push_back(name);
3007 if (it->lyxCode() == INCLUDE_CODE) {
3008 // get buffer of external file
3009 InsetInclude const & ins =
3010 static_cast<InsetInclude const &>(*it);
3011 Buffer * child = ins.getChildBuffer();
3014 child->getUsedBranches(result, true);
3017 // remove duplicates
3022 void Buffer::updateMacroInstances(UpdateType utype) const
3024 LYXERR(Debug::MACROS, "updateMacroInstances for "
3025 << d->filename.onlyFileName());
3026 DocIterator it = doc_iterator_begin(this);
3028 DocIterator const end = doc_iterator_end(this);
3029 for (; it != end; it.forwardInset()) {
3030 // look for MathData cells in InsetMathNest insets
3031 InsetMath * minset = it.nextInset()->asInsetMath();
3035 // update macro in all cells of the InsetMathNest
3036 DocIterator::idx_type n = minset->nargs();
3037 MacroContext mc = MacroContext(this, it);
3038 for (DocIterator::idx_type i = 0; i < n; ++i) {
3039 MathData & data = minset->cell(i);
3040 data.updateMacros(0, mc, utype);
3046 void Buffer::listMacroNames(MacroNameSet & macros) const
3051 d->macro_lock = true;
3053 // loop over macro names
3054 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3055 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3056 for (; nameIt != nameEnd; ++nameIt)
3057 macros.insert(nameIt->first);
3059 // loop over children
3060 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3061 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3062 for (; it != end; ++it)
3063 it->first->listMacroNames(macros);
3066 Buffer const * const pbuf = d->parent();
3068 pbuf->listMacroNames(macros);
3070 d->macro_lock = false;
3074 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3076 Buffer const * const pbuf = d->parent();
3081 pbuf->listMacroNames(names);
3084 MacroNameSet::iterator it = names.begin();
3085 MacroNameSet::iterator end = names.end();
3086 for (; it != end; ++it) {
3088 MacroData const * data =
3089 pbuf->getMacro(*it, *this, false);
3091 macros.insert(data);
3093 // we cannot access the original MathMacroTemplate anymore
3094 // here to calls validate method. So we do its work here manually.
3095 // FIXME: somehow make the template accessible here.
3096 if (data->optionals() > 0)
3097 features.require("xargs");
3103 Buffer::References & Buffer::references(docstring const & label)
3106 return const_cast<Buffer *>(masterBuffer())->references(label);
3108 RefCache::iterator it = d->ref_cache_.find(label);
3109 if (it != d->ref_cache_.end())
3110 return it->second.second;
3112 static InsetLabel const * dummy_il = 0;
3113 static References const dummy_refs;
3114 it = d->ref_cache_.insert(
3115 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3116 return it->second.second;
3120 Buffer::References const & Buffer::references(docstring const & label) const
3122 return const_cast<Buffer *>(this)->references(label);
3126 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3128 masterBuffer()->d->ref_cache_[label].first = il;
3132 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3134 return masterBuffer()->d->ref_cache_[label].first;
3138 void Buffer::clearReferenceCache() const
3141 d->ref_cache_.clear();
3145 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
3148 //FIXME: This does not work for child documents yet.
3149 LASSERT(code == CITE_CODE, /**/);
3151 reloadBibInfoCache();
3153 // Check if the label 'from' appears more than once
3154 BiblioInfo const & keys = masterBibInfo();
3155 BiblioInfo::const_iterator bit = keys.begin();
3156 BiblioInfo::const_iterator bend = keys.end();
3157 vector<docstring> labels;
3159 for (; bit != bend; ++bit)
3161 labels.push_back(bit->first);
3163 if (count(labels.begin(), labels.end(), from) > 1)
3166 string const paramName = "key";
3167 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3168 if (it->lyxCode() == code) {
3169 InsetCommand * inset = it->asInsetCommand();
3172 docstring const oldValue = inset->getParam(paramName);
3173 if (oldValue == from)
3174 inset->setParam(paramName, to);
3180 void Buffer::getSourceCode(odocstream & os, string const format,
3181 pit_type par_begin, pit_type par_end,
3182 bool full_source) const
3184 OutputParams runparams(¶ms().encoding());
3185 runparams.nice = true;
3186 runparams.flavor = params().getOutputFlavor(format);
3187 runparams.linelen = lyxrc.plaintext_linelen;
3188 // No side effect of file copying and image conversion
3189 runparams.dryrun = true;
3192 os << "% " << _("Preview source code") << "\n\n";
3194 d->texrow.newline();
3195 d->texrow.newline();
3196 if (params().isDocBook())
3197 writeDocBookSource(os, absFileName(), runparams, FullSource);
3198 else if (runparams.flavor == OutputParams::HTML)
3199 writeLyXHTMLSource(os, runparams, FullSource);
3201 // latex or literate
3202 otexstream ots(os, d->texrow);
3203 writeLaTeXSource(ots, string(), runparams, FullSource);
3206 runparams.par_begin = par_begin;
3207 runparams.par_end = par_end;
3208 if (par_begin + 1 == par_end) {
3210 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3214 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3215 convert<docstring>(par_begin),
3216 convert<docstring>(par_end - 1))
3223 // output paragraphs
3224 if (params().isDocBook())
3225 docbookParagraphs(text(), *this, os, runparams);
3226 else if (runparams.flavor == OutputParams::HTML) {
3228 xhtmlParagraphs(text(), *this, xs, runparams);
3230 // latex or literate
3231 otexstream ots(os, texrow);
3232 latexParagraphs(*this, text(), ots, runparams);
3238 ErrorList & Buffer::errorList(string const & type) const
3240 return d->errorLists[type];
3244 void Buffer::updateTocItem(std::string const & type,
3245 DocIterator const & dit) const
3248 d->gui_->updateTocItem(type, dit);
3252 void Buffer::structureChanged() const
3255 d->gui_->structureChanged();
3259 void Buffer::errors(string const & err, bool from_master) const
3262 d->gui_->errors(err, from_master);
3266 void Buffer::message(docstring const & msg) const
3269 d->gui_->message(msg);
3273 void Buffer::setBusy(bool on) const
3276 d->gui_->setBusy(on);
3280 void Buffer::updateTitles() const
3283 d->wa_->updateTitles();
3287 void Buffer::resetAutosaveTimers() const
3290 d->gui_->resetAutosaveTimers();
3294 bool Buffer::hasGuiDelegate() const
3300 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3309 class AutoSaveBuffer : public ForkedProcess {
3312 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3313 : buffer_(buffer), fname_(fname) {}
3315 virtual shared_ptr<ForkedProcess> clone() const
3317 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3322 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3323 from_utf8(fname_.absFileName())));
3324 return run(DontWait);
3328 virtual int generateChild();
3330 Buffer const & buffer_;
3335 int AutoSaveBuffer::generateChild()
3337 #if defined(__APPLE__)
3338 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3339 * We should use something else like threads.
3341 * Since I do not know how to determine at run time what is the OS X
3342 * version, I just disable forking altogether for now (JMarc)
3344 pid_t const pid = -1;
3346 // tmp_ret will be located (usually) in /tmp
3347 // will that be a problem?
3348 // Note that this calls ForkedCalls::fork(), so it's
3349 // ok cross-platform.
3350 pid_t const pid = fork();
3351 // If you want to debug the autosave
3352 // you should set pid to -1, and comment out the fork.
3353 if (pid != 0 && pid != -1)
3357 // pid = -1 signifies that lyx was unable
3358 // to fork. But we will do the save
3360 bool failed = false;
3361 FileName const tmp_ret = FileName::tempName("lyxauto");
3362 if (!tmp_ret.empty()) {
3363 buffer_.writeFile(tmp_ret);
3364 // assume successful write of tmp_ret
3365 if (!tmp_ret.moveTo(fname_))
3371 // failed to write/rename tmp_ret so try writing direct
3372 if (!buffer_.writeFile(fname_)) {
3373 // It is dangerous to do this in the child,
3374 // but safe in the parent, so...
3375 if (pid == -1) // emit message signal.
3376 buffer_.message(_("Autosave failed!"));
3380 if (pid == 0) // we are the child so...
3389 FileName Buffer::getEmergencyFileName() const
3391 return FileName(d->filename.absFileName() + ".emergency");
3395 FileName Buffer::getAutosaveFileName() const
3397 // if the document is unnamed try to save in the backup dir, else
3398 // in the default document path, and as a last try in the filePath,
3399 // which will most often be the temporary directory
3402 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3403 : lyxrc.backupdir_path;
3404 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3407 string const fname = "#" + d->filename.onlyFileName() + "#";
3409 return makeAbsPath(fname, fpath);
3413 void Buffer::removeAutosaveFile() const
3415 FileName const f = getAutosaveFileName();
3421 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3423 FileName const newauto = getAutosaveFileName();
3425 if (newauto != oldauto && oldauto.exists())
3426 if (!oldauto.moveTo(newauto))
3427 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3431 bool Buffer::autoSave() const
3433 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
3434 if (buf->d->bak_clean || isReadonly())
3437 message(_("Autosaving current document..."));
3438 buf->d->bak_clean = true;
3440 FileName const fname = getAutosaveFileName();
3441 if (d->cloned_buffer_) {
3442 // If this buffer is cloned, we assume that
3443 // we are running in a separate thread already.
3444 FileName const tmp_ret = FileName::tempName("lyxauto");
3445 if (!tmp_ret.empty()) {
3447 // assume successful write of tmp_ret
3448 if (tmp_ret.moveTo(fname))
3451 // failed to write/rename tmp_ret so try writing direct
3452 return writeFile(fname);
3454 /// This function is deprecated as the frontend needs to take care
3455 /// of cloning the buffer and autosaving it in another thread. It
3456 /// is still here to allow (QT_VERSION < 0x040400).
3457 AutoSaveBuffer autosave(*this, fname);
3465 // helper class, to guarantee this gets reset properly
3466 class MarkAsExporting {
3468 MarkAsExporting(Buffer const * buf) : buf_(buf)
3470 LASSERT(buf_, /* */);
3471 buf_->setExportStatus(true);
3475 buf_->setExportStatus(false);
3478 Buffer const * const buf_;
3483 void Buffer::setExportStatus(bool e) const
3485 d->doing_export = e;
3486 ListOfBuffers clist = getDescendents();
3487 ListOfBuffers::const_iterator cit = clist.begin();
3488 ListOfBuffers::const_iterator const cen = clist.end();
3489 for (; cit != cen; ++cit)
3490 (*cit)->d->doing_export = e;
3494 bool Buffer::isExporting() const
3496 return d->doing_export;
3500 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir) const
3502 bool const update_unincluded =
3503 params().maintain_unincluded_children
3504 && !params().getIncludedChildren().empty();
3505 return doExport(target, put_in_tempdir, update_unincluded);
3509 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3510 bool includeall, string & result_file) const
3512 LYXERR(Debug::FILES, "target=" << target);
3513 OutputParams runparams(¶ms().encoding());
3514 string format = target;
3515 string dest_filename;
3516 size_t pos = target.find(' ');
3517 if (pos != string::npos) {
3518 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
3519 format = target.substr(0, pos);
3520 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
3521 FileName(dest_filename).onlyPath().createPath();
3522 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
3524 MarkAsExporting exporting(this);
3525 string backend_format;
3526 runparams.flavor = OutputParams::LATEX;
3527 runparams.linelen = lyxrc.plaintext_linelen;
3528 runparams.includeall = includeall;
3529 vector<string> backs = params().backends();
3530 Converters converters = theConverters();
3531 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3532 // Get shortest path to format
3533 converters.buildGraph();
3534 Graph::EdgePath path;
3535 for (vector<string>::const_iterator it = backs.begin();
3536 it != backs.end(); ++it) {
3537 Graph::EdgePath p = converters.getPath(*it, format);
3538 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3539 backend_format = *it;
3544 if (!put_in_tempdir) {
3545 // Only show this alert if this is an export to a non-temporary
3546 // file (not for previewing).
3547 Alert::error(_("Couldn't export file"), bformat(
3548 _("No information for exporting the format %1$s."),
3549 formats.prettyName(format)));
3551 return ExportNoPathToFormat;
3553 runparams.flavor = converters.getFlavor(path);
3556 backend_format = format;
3557 LYXERR(Debug::FILES, "backend_format=" << backend_format);
3558 // FIXME: Don't hardcode format names here, but use a flag
3559 if (backend_format == "pdflatex")
3560 runparams.flavor = OutputParams::PDFLATEX;
3561 else if (backend_format == "luatex")
3562 runparams.flavor = OutputParams::LUATEX;
3563 else if (backend_format == "dviluatex")
3564 runparams.flavor = OutputParams::DVILUATEX;
3565 else if (backend_format == "xetex")
3566 runparams.flavor = OutputParams::XETEX;
3569 string filename = latexName(false);
3570 filename = addName(temppath(), filename);
3571 filename = changeExtension(filename,
3572 formats.extension(backend_format));
3573 LYXERR(Debug::FILES, "filename=" << filename);
3575 // Plain text backend
3576 if (backend_format == "text") {
3577 runparams.flavor = OutputParams::TEXT;
3578 writePlaintextFile(*this, FileName(filename), runparams);
3581 else if (backend_format == "xhtml") {
3582 runparams.flavor = OutputParams::HTML;
3583 switch (params().html_math_output) {
3584 case BufferParams::MathML:
3585 runparams.math_flavor = OutputParams::MathAsMathML;
3587 case BufferParams::HTML:
3588 runparams.math_flavor = OutputParams::MathAsHTML;
3590 case BufferParams::Images:
3591 runparams.math_flavor = OutputParams::MathAsImages;
3593 case BufferParams::LaTeX:
3594 runparams.math_flavor = OutputParams::MathAsLaTeX;
3597 makeLyXHTMLFile(FileName(filename), runparams);
3598 } else if (backend_format == "lyx")
3599 writeFile(FileName(filename));
3601 else if (params().isDocBook()) {
3602 runparams.nice = !put_in_tempdir;
3603 makeDocBookFile(FileName(filename), runparams);
3606 else if (backend_format == format) {
3607 runparams.nice = true;
3608 if (!makeLaTeXFile(FileName(filename), string(), runparams)) {
3609 if (d->cloned_buffer_) {
3610 d->cloned_buffer_->d->errorLists["Export"] =
3611 d->errorLists["Export"];
3615 } else if (!lyxrc.tex_allows_spaces
3616 && contains(filePath(), ' ')) {
3617 Alert::error(_("File name error"),
3618 _("The directory path to the document cannot contain spaces."));
3619 return ExportTexPathHasSpaces;
3621 runparams.nice = false;
3622 if (!makeLaTeXFile(FileName(filename), filePath(), runparams)) {
3623 if (d->cloned_buffer_) {
3624 d->cloned_buffer_->d->errorLists["Export"] =
3625 d->errorLists["Export"];
3631 string const error_type = (format == "program")
3632 ? "Build" : params().bufferFormat();
3633 ErrorList & error_list = d->errorLists[error_type];
3634 string const ext = formats.extension(format);
3635 FileName const tmp_result_file(changeExtension(filename, ext));
3636 bool const success = converters.convert(this, FileName(filename),
3637 tmp_result_file, FileName(absFileName()), backend_format, format,
3640 // Emit the signal to show the error list or copy it back to the
3641 // cloned Buffer so that it can be emitted afterwards.
3642 if (format != backend_format) {
3643 if (d->cloned_buffer_) {
3644 d->cloned_buffer_->d->errorLists[error_type] =
3645 d->errorLists[error_type];
3648 // also to the children, in case of master-buffer-view
3649 ListOfBuffers clist = getDescendents();
3650 ListOfBuffers::const_iterator cit = clist.begin();
3651 ListOfBuffers::const_iterator const cen = clist.end();
3652 for (; cit != cen; ++cit) {
3653 if (d->cloned_buffer_) {
3654 // Enable reverse search by copying back the
3655 // texrow object to the cloned buffer.
3656 // FIXME: this is not thread safe.
3657 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
3658 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
3659 (*cit)->d->errorLists[error_type];
3661 (*cit)->errors(error_type, true);
3665 if (d->cloned_buffer_) {
3666 // Enable reverse dvi or pdf to work by copying back the texrow
3667 // object to the cloned buffer.
3668 // FIXME: There is a possibility of concurrent access to texrow
3669 // here from the main GUI thread that should be securized.
3670 d->cloned_buffer_->d->texrow = d->texrow;
3671 string const error_type = params().bufferFormat();
3672 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
3676 return ExportConverterError;
3678 if (put_in_tempdir) {
3679 result_file = tmp_result_file.absFileName();
3680 return ExportSuccess;
3683 if (dest_filename.empty())
3684 result_file = changeExtension(d->exportFileName().absFileName(), ext);
3686 result_file = dest_filename;
3687 // We need to copy referenced files (e. g. included graphics
3688 // if format == "dvi") to the result dir.
3689 vector<ExportedFile> const files =
3690 runparams.exportdata->externalFiles(format);
3691 string const dest = runparams.export_folder.empty() ?
3692 onlyPath(result_file) : runparams.export_folder;
3693 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
3694 : force_overwrite == ALL_FILES;
3695 CopyStatus status = use_force ? FORCE : SUCCESS;
3697 vector<ExportedFile>::const_iterator it = files.begin();
3698 vector<ExportedFile>::const_iterator const en = files.end();
3699 for (; it != en && status != CANCEL; ++it) {
3700 string const fmt = formats.getFormatFromFile(it->sourceName);
3701 string fixedName = it->exportName;
3702 if (!runparams.export_folder.empty()) {
3703 // Relative pathnames starting with ../ will be sanitized
3704 // if exporting to a different folder
3705 while (fixedName.substr(0, 3) == "../")
3706 fixedName = fixedName.substr(3, fixedName.length() - 3);
3708 FileName fixedFileName = makeAbsPath(fixedName, dest);
3709 fixedFileName.onlyPath().createPath();
3710 status = copyFile(fmt, it->sourceName,
3712 it->exportName, status == FORCE,
3713 runparams.export_folder.empty());
3716 if (status == CANCEL) {
3717 message(_("Document export cancelled."));
3718 } else if (tmp_result_file.exists()) {
3719 // Finally copy the main file
3720 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
3721 : force_overwrite != NO_FILES;
3722 if (status == SUCCESS && use_force)
3724 status = copyFile(format, tmp_result_file,
3725 FileName(result_file), result_file,
3727 message(bformat(_("Document exported as %1$s "
3729 formats.prettyName(format),
3730 makeDisplayPath(result_file)));
3732 // This must be a dummy converter like fax (bug 1888)
3733 message(bformat(_("Document exported as %1$s"),
3734 formats.prettyName(format)));
3737 return ExportSuccess;
3741 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3742 bool includeall) const
3745 // (1) export with all included children (omit \includeonly)
3747 ExportStatus const status =
3748 doExport(target, put_in_tempdir, true, result_file);
3749 if (status != ExportSuccess)
3752 // (2) export with included children only
3753 return doExport(target, put_in_tempdir, false, result_file);
3757 Buffer::ExportStatus Buffer::preview(string const & format) const
3759 bool const update_unincluded =
3760 params().maintain_unincluded_children
3761 && !params().getIncludedChildren().empty();
3762 return preview(format, update_unincluded);
3765 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
3767 MarkAsExporting exporting(this);
3769 // (1) export with all included children (omit \includeonly)
3771 ExportStatus const status = doExport(format, true, true);
3772 if (status != ExportSuccess)
3775 // (2) export with included children only
3776 ExportStatus const status = doExport(format, true, false, result_file);
3777 if (status != ExportSuccess)
3779 if (!formats.view(*this, FileName(result_file), format))
3780 return PreviewError;
3781 return PreviewSuccess;
3785 Buffer::ReadStatus Buffer::extractFromVC()
3787 bool const found = LyXVC::file_not_found_hook(d->filename);
3789 return ReadFileNotFound;
3790 if (!d->filename.isReadableFile())
3796 Buffer::ReadStatus Buffer::loadEmergency()
3798 FileName const emergencyFile = getEmergencyFileName();
3799 if (!emergencyFile.exists()
3800 || emergencyFile.lastModified() <= d->filename.lastModified())
3801 return ReadFileNotFound;
3803 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
3804 docstring const text = bformat(_("An emergency save of the document "
3805 "%1$s exists.\n\nRecover emergency save?"), file);
3807 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
3808 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
3814 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
3815 bool const success = (ret_llf == ReadSuccess);
3818 Alert::warning(_("File is read-only"),
3819 bformat(_("An emergency file is successfully loaded, "
3820 "but the original file %1$s is marked read-only. "
3821 "Please make sure to save the document as a different "
3822 "file."), from_utf8(d->filename.absFileName())));
3825 str = _("Document was successfully recovered.");
3827 str = _("Document was NOT successfully recovered.");
3828 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3829 makeDisplayPath(emergencyFile.absFileName()));
3831 int const del_emerg =
3832 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3833 _("&Remove"), _("&Keep"));
3834 if (del_emerg == 0) {
3835 emergencyFile.removeFile();
3837 Alert::warning(_("Emergency file deleted"),
3838 _("Do not forget to save your file now!"), true);
3840 return success ? ReadSuccess : ReadEmergencyFailure;
3843 int const del_emerg =
3844 Alert::prompt(_("Delete emergency file?"),
3845 _("Remove emergency file now?"), 1, 1,
3846 _("&Remove"), _("&Keep"));
3848 emergencyFile.removeFile();
3849 return ReadOriginal;
3859 Buffer::ReadStatus Buffer::loadAutosave()
3861 // Now check if autosave file is newer.
3862 FileName const autosaveFile = getAutosaveFileName();
3863 if (!autosaveFile.exists()
3864 || autosaveFile.lastModified() <= d->filename.lastModified())
3865 return ReadFileNotFound;
3867 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
3868 docstring const text = bformat(_("The backup of the document %1$s "
3869 "is newer.\n\nLoad the backup instead?"), file);
3870 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
3871 _("&Load backup"), _("Load &original"), _("&Cancel"));
3876 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
3877 // the file is not saved if we load the autosave file.
3878 if (ret_llf == ReadSuccess) {
3880 Alert::warning(_("File is read-only"),
3881 bformat(_("A backup file is successfully loaded, "
3882 "but the original file %1$s is marked read-only. "
3883 "Please make sure to save the document as a "
3885 from_utf8(d->filename.absFileName())));
3890 return ReadAutosaveFailure;
3893 // Here we delete the autosave
3894 autosaveFile.removeFile();
3895 return ReadOriginal;
3903 Buffer::ReadStatus Buffer::loadLyXFile()
3905 if (!d->filename.isReadableFile()) {
3906 ReadStatus const ret_rvc = extractFromVC();
3907 if (ret_rvc != ReadSuccess)
3911 ReadStatus const ret_re = loadEmergency();
3912 if (ret_re == ReadSuccess || ret_re == ReadCancel)
3915 ReadStatus const ret_ra = loadAutosave();
3916 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
3919 return loadThisLyXFile(d->filename);
3923 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
3925 return readFile(fn);
3929 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3931 TeXErrors::Errors::const_iterator it = terr.begin();
3932 TeXErrors::Errors::const_iterator end = terr.end();
3933 ListOfBuffers clist = getDescendents();
3934 ListOfBuffers::const_iterator cen = clist.end();
3936 for (; it != end; ++it) {
3939 int errorRow = it->error_in_line;
3940 Buffer const * buf = 0;
3942 if (it->child_name.empty())
3943 p->texrow.getIdFromRow(errorRow, id_start, pos_start);
3945 // The error occurred in a child
3946 ListOfBuffers::const_iterator cit = clist.begin();
3947 for (; cit != cen; ++cit) {
3948 string const child_name =
3949 DocFileName(changeExtension(
3950 (*cit)->absFileName(), "tex")).
3952 if (it->child_name != child_name)
3954 (*cit)->d->texrow.getIdFromRow(errorRow,
3955 id_start, pos_start);
3956 if (id_start != -1) {
3957 buf = d->cloned_buffer_
3958 ? (*cit)->d->cloned_buffer_->d->owner_
3959 : (*cit)->d->owner_;
3970 found = p->texrow.getIdFromRow(errorRow, id_end, pos_end);
3971 } while (found && id_start == id_end && pos_start == pos_end);
3973 if (id_start != id_end) {
3974 // Next registered position is outside the inset where
3975 // the error occurred, so signal end-of-paragraph
3979 errorList.push_back(ErrorItem(it->error_desc,
3980 it->error_text, id_start, pos_start, pos_end, buf));
3985 void Buffer::setBuffersForInsets() const
3987 inset().setBuffer(const_cast<Buffer &>(*this));
3991 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
3993 // Use the master text class also for child documents
3994 Buffer const * const master = masterBuffer();
3995 DocumentClass const & textclass = master->params().documentClass();
3997 // do this only if we are the top-level Buffer
3999 reloadBibInfoCache();
4001 // keep the buffers to be children in this set. If the call from the
4002 // master comes back we can see which of them were actually seen (i.e.
4003 // via an InsetInclude). The remaining ones in the set need still be updated.
4004 static std::set<Buffer const *> bufToUpdate;
4005 if (scope == UpdateMaster) {
4006 // If this is a child document start with the master
4007 if (master != this) {
4008 bufToUpdate.insert(this);
4009 master->updateBuffer(UpdateMaster, utype);
4010 // Do this here in case the master has no gui associated with it. Then,
4011 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
4012 if (!master->d->gui_)
4015 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4016 if (bufToUpdate.find(this) == bufToUpdate.end())
4020 // start over the counters in the master
4021 textclass.counters().reset();
4024 // update will be done below for this buffer
4025 bufToUpdate.erase(this);
4027 // update all caches
4028 clearReferenceCache();
4031 Buffer & cbuf = const_cast<Buffer &>(*this);
4033 LASSERT(!text().paragraphs().empty(), /**/);
4036 ParIterator parit = cbuf.par_iterator_begin();
4037 updateBuffer(parit, utype);
4040 // TocBackend update will be done later.
4043 d->bibinfo_cache_valid_ = true;
4044 d->cite_labels_valid_ = true;
4045 cbuf.tocBackend().update();
4046 if (scope == UpdateMaster)
4047 cbuf.structureChanged();
4051 static depth_type getDepth(DocIterator const & it)
4053 depth_type depth = 0;
4054 for (size_t i = 0 ; i < it.depth() ; ++i)
4055 if (!it[i].inset().inMathed())
4056 depth += it[i].paragraph().getDepth() + 1;
4057 // remove 1 since the outer inset does not count
4061 static depth_type getItemDepth(ParIterator const & it)
4063 Paragraph const & par = *it;
4064 LabelType const labeltype = par.layout().labeltype;
4066 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4069 // this will hold the lowest depth encountered up to now.
4070 depth_type min_depth = getDepth(it);
4071 ParIterator prev_it = it;
4074 --prev_it.top().pit();
4076 // start of nested inset: go to outer par
4078 if (prev_it.empty()) {
4079 // start of document: nothing to do
4084 // We search for the first paragraph with same label
4085 // that is not more deeply nested.
4086 Paragraph & prev_par = *prev_it;
4087 depth_type const prev_depth = getDepth(prev_it);
4088 if (labeltype == prev_par.layout().labeltype) {
4089 if (prev_depth < min_depth)
4090 return prev_par.itemdepth + 1;
4091 if (prev_depth == min_depth)
4092 return prev_par.itemdepth;
4094 min_depth = min(min_depth, prev_depth);
4095 // small optimization: if we are at depth 0, we won't
4096 // find anything else
4097 if (prev_depth == 0)
4103 static bool needEnumCounterReset(ParIterator const & it)
4105 Paragraph const & par = *it;
4106 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
4107 depth_type const cur_depth = par.getDepth();
4108 ParIterator prev_it = it;
4109 while (prev_it.pit()) {
4110 --prev_it.top().pit();
4111 Paragraph const & prev_par = *prev_it;
4112 if (prev_par.getDepth() <= cur_depth)
4113 return prev_par.layout().labeltype != LABEL_ENUMERATE;
4115 // start of nested inset: reset
4120 // set the label of a paragraph. This includes the counters.
4121 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4123 BufferParams const & bp = owner_->masterBuffer()->params();
4124 DocumentClass const & textclass = bp.documentClass();
4125 Paragraph & par = it.paragraph();
4126 Layout const & layout = par.layout();
4127 Counters & counters = textclass.counters();
4129 if (par.params().startOfAppendix()) {
4130 // FIXME: only the counter corresponding to toplevel
4131 // sectioning should be reset
4133 counters.appendix(true);
4135 par.params().appendix(counters.appendix());
4137 // Compute the item depth of the paragraph
4138 par.itemdepth = getItemDepth(it);
4140 if (layout.margintype == MARGIN_MANUAL) {
4141 if (par.params().labelWidthString().empty())
4142 par.params().labelWidthString(par.expandLabel(layout, bp));
4143 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4144 // we do not need to do anything here, since the empty case is
4145 // handled during export.
4147 par.params().labelWidthString(docstring());
4150 switch(layout.labeltype) {
4152 if (layout.toclevel <= bp.secnumdepth
4153 && (layout.latextype != LATEX_ENVIRONMENT
4154 || it.text()->isFirstInSequence(it.pit()))) {
4155 if (counters.hasCounter(layout.counter))
4156 counters.step(layout.counter, utype);
4157 par.params().labelString(par.expandLabel(layout, bp));
4159 par.params().labelString(docstring());
4162 case LABEL_ITEMIZE: {
4163 // At some point of time we should do something more
4164 // clever here, like:
4165 // par.params().labelString(
4166 // bp.user_defined_bullet(par.itemdepth).getText());
4167 // for now, use a simple hardcoded label
4168 docstring itemlabel;
4169 switch (par.itemdepth) {
4171 itemlabel = char_type(0x2022);
4174 itemlabel = char_type(0x2013);
4177 itemlabel = char_type(0x2217);
4180 itemlabel = char_type(0x2219); // or 0x00b7
4183 par.params().labelString(itemlabel);
4187 case LABEL_ENUMERATE: {
4188 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4190 switch (par.itemdepth) {
4199 enumcounter += "iv";
4202 // not a valid enumdepth...
4206 // Maybe we have to reset the enumeration counter.
4207 if (needEnumCounterReset(it))
4208 counters.reset(enumcounter);
4209 counters.step(enumcounter, utype);
4211 string const & lang = par.getParLanguage(bp)->code();
4212 par.params().labelString(counters.theCounter(enumcounter, lang));
4217 case LABEL_SENSITIVE: {
4218 string const & type = counters.current_float();
4219 docstring full_label;
4221 full_label = owner_->B_("Senseless!!! ");
4223 docstring name = owner_->B_(textclass.floats().getType(type).name());
4224 if (counters.hasCounter(from_utf8(type))) {
4225 string const & lang = par.getParLanguage(bp)->code();
4226 counters.step(from_utf8(type), utype);
4227 full_label = bformat(from_ascii("%1$s %2$s:"),
4229 counters.theCounter(from_utf8(type), lang));
4231 full_label = bformat(from_ascii("%1$s #:"), name);
4233 par.params().labelString(full_label);
4237 case LABEL_NO_LABEL:
4238 par.params().labelString(docstring());
4242 case LABEL_TOP_ENVIRONMENT:
4243 case LABEL_CENTERED_TOP_ENVIRONMENT:
4246 par.params().labelString(par.expandLabel(layout, bp));
4252 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4254 LASSERT(parit.pit() == 0, /**/);
4256 // Set the position of the text in the buffer to be able
4257 // to resolve macros in it.
4258 parit.text()->setMacrocontextPosition(parit);
4260 depth_type maxdepth = 0;
4261 pit_type const lastpit = parit.lastpit();
4262 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4263 // reduce depth if necessary
4264 parit->params().depth(min(parit->params().depth(), maxdepth));
4265 maxdepth = parit->getMaxDepthAfter();
4267 if (utype == OutputUpdate) {
4268 // track the active counters
4269 // we have to do this for the master buffer, since the local
4270 // buffer isn't tracking anything.
4271 masterBuffer()->params().documentClass().counters().
4272 setActiveLayout(parit->layout());
4275 // set the counter for this paragraph
4276 d->setLabel(parit, utype);
4279 InsetList::const_iterator iit = parit->insetList().begin();
4280 InsetList::const_iterator end = parit->insetList().end();
4281 for (; iit != end; ++iit) {
4282 parit.pos() = iit->pos;
4283 iit->inset->updateBuffer(parit, utype);
4289 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4290 WordLangTuple & word_lang, docstring_list & suggestions) const
4294 suggestions.clear();
4295 word_lang = WordLangTuple();
4296 bool const to_end = to.empty();
4297 DocIterator const end = to_end ? doc_iterator_end(this) : to;
4298 // OK, we start from here.
4299 for (; from != end; from.forwardPos()) {
4300 // We are only interested in text so remove the math CursorSlice.
4301 while (from.inMathed()) {
4305 // If from is at the end of the document (which is possible
4306 // when leaving the mathed) LyX will crash later otherwise.
4307 if (from.atEnd() || (!to_end && from >= end))
4310 from.paragraph().spellCheck();
4311 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4312 if (SpellChecker::misspelled(res)) {
4317 // Do not increase progress when from == to, otherwise the word
4318 // count will be wrong.
4328 Buffer::ReadStatus Buffer::reload()
4331 // c.f. bug http://www.lyx.org/trac/ticket/6587
4332 removeAutosaveFile();
4333 // e.g., read-only status could have changed due to version control
4334 d->filename.refresh();
4335 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4337 ReadStatus const status = loadLyXFile();
4338 if (status == ReadSuccess) {
4343 message(bformat(_("Document %1$s reloaded."), disp_fn));
4346 message(bformat(_("Could not reload document %1$s."), disp_fn));
4356 bool Buffer::saveAs(FileName const & fn)
4358 FileName const old_name = fileName();
4359 FileName const old_auto = getAutosaveFileName();
4360 bool const old_unnamed = isUnnamed();
4367 // bring the autosave file with us, just in case.
4368 moveAutosaveFile(old_auto);
4369 // validate version control data and
4370 // correct buffer title
4371 lyxvc().file_found_hook(fileName());
4373 // the file has now been saved to the new location.
4374 // we need to check that the locations of child buffers
4376 checkChildBuffers();
4380 // reset the old filename and unnamed state
4381 setFileName(old_name);
4382 setUnnamed(old_unnamed);
4388 // FIXME We could do better here, but it is complicated. What would be
4389 // nice is to offer either (a) to save the child buffer to an appropriate
4390 // location, so that it would "move with the master", or else (b) to update
4391 // the InsetInclude so that it pointed to the same file. But (a) is a bit
4392 // complicated, because the code for this lives in GuiView.
4393 void Buffer::checkChildBuffers()
4395 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4396 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4397 for (; it != en; ++it) {
4398 DocIterator dit = it->second;
4399 Buffer * cbuf = const_cast<Buffer *>(it->first);
4400 if (!cbuf || !theBufferList().isLoaded(cbuf))
4402 Inset * inset = dit.nextInset();
4403 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4404 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4405 docstring const & incfile = inset_inc->getParam("filename");
4406 string oldloc = cbuf->absFileName();
4407 string newloc = makeAbsPath(to_utf8(incfile),
4408 onlyPath(absFileName())).absFileName();
4409 if (oldloc == newloc)
4411 // the location of the child file is incorrect.
4412 Alert::warning(_("Included File Invalid"),
4413 bformat(_("Saving this document to a new location has made the file:\n"
4415 "inaccessible. You will need to update the included filename."),
4416 from_utf8(oldloc)));
4418 inset_inc->setChildBuffer(0);
4420 // invalidate cache of children
4421 d->children_positions.clear();
4422 d->position_to_children.clear();