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 // Do not remove the comment below, so we get merge conflict in
130 // independent branches. Instead add your own.
131 int const LYX_FORMAT = 416; //uwestoehr : support for horizontal spaces (bug 7728)
133 typedef map<string, bool> DepClean;
134 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
136 void showPrintError(string const & name)
138 docstring str = bformat(_("Could not print the document %1$s.\n"
139 "Check that your printer is set up correctly."),
140 makeDisplayPath(name, 50));
141 Alert::error(_("Print document failed"), str);
150 Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
154 delete preview_loader_;
162 /// search for macro in local (buffer) table or in children
163 MacroData const * getBufferMacro(docstring const & name,
164 DocIterator const & pos) const;
166 /// Update macro table starting with position of it \param it in some
168 void updateMacros(DocIterator & it, DocIterator & scope);
170 void setLabel(ParIterator & it, UpdateType utype) const;
172 /** If we have branches that use the file suffix
173 feature, return the file name with suffix appended.
175 support::FileName exportFileName() const;
182 mutable TexRow texrow;
184 /// need to regenerate .tex?
188 mutable bool lyx_clean;
190 /// is autosave needed?
191 mutable bool bak_clean;
193 /// is this an unnamed file (New...)?
199 /// name of the file the buffer is associated with.
202 /** Set to true only when the file is fully loaded.
203 * Used to prevent the premature generation of previews
204 * and by the citation inset.
206 bool file_fully_loaded;
209 mutable TocBackend toc_backend;
212 typedef pair<DocIterator, MacroData> ScopeMacro;
213 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
214 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
215 /// map from the macro name to the position map,
216 /// which maps the macro definition position to the scope and the MacroData.
217 NamePositionScopeMacroMap macros;
218 /// This seem to change the way Buffer::getMacro() works
219 mutable bool macro_lock;
221 /// positions of child buffers in the buffer
222 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
223 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
224 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
225 /// position of children buffers in this buffer
226 BufferPositionMap children_positions;
227 /// map from children inclusion positions to their scope and their buffer
228 PositionScopeBufferMap position_to_children;
230 /// Container for all sort of Buffer dependant errors.
231 map<string, ErrorList> errorLists;
233 /// timestamp and checksum used to test if the file has been externally
234 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
236 unsigned long checksum_;
239 frontend::WorkAreaManager * wa_;
241 frontend::GuiBufferDelegate * gui_;
246 /// A cache for the bibfiles (including bibfiles of loaded child
247 /// documents), needed for appropriate update of natbib labels.
248 mutable support::FileNameList bibfiles_cache_;
250 // FIXME The caching mechanism could be improved. At present, we have a
251 // cache for each Buffer, that caches all the bibliography info for that
252 // Buffer. A more efficient solution would be to have a global cache per
253 // file, and then to construct the Buffer's bibinfo from that.
254 /// A cache for bibliography info
255 mutable BiblioInfo bibinfo_;
256 /// whether the bibinfo cache is valid
257 mutable bool bibinfo_cache_valid_;
258 /// whether the bibfile cache is valid
259 mutable bool bibfile_cache_valid_;
260 /// Cache of timestamps of .bib files
261 map<FileName, time_t> bibfile_status_;
262 /// Indicates whether the bibinfo has changed since the last time
263 /// we ran updateBuffer(), i.e., whether citation labels may need
265 mutable bool cite_labels_valid_;
267 mutable RefCache ref_cache_;
269 /// our Text that should be wrapped in an InsetText
273 PreviewLoader * preview_loader_;
275 /// This is here to force the test to be done whenever parent_buffer
277 Buffer const * parent() const {
278 // if parent_buffer is not loaded, then it has been unloaded,
279 // which means that parent_buffer is an invalid pointer. So we
280 // set it to null in that case.
281 // however, the BufferList doesn't know about cloned buffers, so
282 // they will always be regarded as unloaded. in that case, we hope
284 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
286 return parent_buffer;
290 void setParent(Buffer const * pb) {
291 if (parent_buffer == pb)
294 if (!cloned_buffer_ && parent_buffer && pb)
295 LYXERR0("Warning: a buffer should not have two parents!");
297 if (!cloned_buffer_ && parent_buffer) {
298 parent_buffer->invalidateBibfileCache();
299 parent_buffer->invalidateBibinfoCache();
303 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
304 /// This one is useful for preview detached in a thread.
305 Buffer const * cloned_buffer_;
306 /// are we in the process of exporting this buffer?
307 mutable bool doing_export;
310 /// So we can force access via the accessors.
311 mutable Buffer const * parent_buffer;
316 /// Creates the per buffer temporary directory
317 static FileName createBufferTmpDir()
320 // We are in our own directory. Why bother to mangle name?
321 // In fact I wrote this code to circumvent a problematic behaviour
322 // (bug?) of EMX mkstemp().
323 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
324 convert<string>(count++));
326 if (!tmpfl.createDirectory(0777)) {
327 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
328 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
329 from_utf8(tmpfl.absFileName())));
335 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
336 Buffer const * cloned_buffer)
337 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
338 read_only(readonly_), filename(file), file_fully_loaded(false),
339 toc_backend(owner), macro_lock(false), timestamp_(0), checksum_(0),
340 wa_(0), gui_(0), undo_(*owner), bibinfo_cache_valid_(false),
341 bibfile_cache_valid_(false), cite_labels_valid_(false),
342 preview_loader_(0), cloned_buffer_(cloned_buffer),
343 doing_export(false), parent_buffer(0)
345 if (!cloned_buffer_) {
346 temppath = createBufferTmpDir();
347 lyxvc.setBuffer(owner_);
349 wa_ = new frontend::WorkAreaManager;
352 temppath = cloned_buffer_->d->temppath;
353 file_fully_loaded = true;
354 params = cloned_buffer_->d->params;
355 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
356 bibinfo_ = cloned_buffer_->d->bibinfo_;
357 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
358 bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
359 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
360 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
364 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
365 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
367 LYXERR(Debug::INFO, "Buffer::Buffer()");
369 d->inset = new InsetText(*cloned_buffer->d->inset);
370 d->inset->setBuffer(*this);
371 // FIXME: optimize this loop somewhat, maybe by creating a new
372 // general recursive Inset::setId().
373 DocIterator it = doc_iterator_begin(this);
374 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
375 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
376 it.paragraph().setId(cloned_it.paragraph().id());
378 d->inset = new InsetText(this);
379 d->inset->setAutoBreakRows(true);
380 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
386 LYXERR(Debug::INFO, "Buffer::~Buffer()");
387 // here the buffer should take care that it is
388 // saved properly, before it goes into the void.
390 // GuiView already destroyed
394 // No need to do additional cleanups for internal buffer.
399 // loop over children
400 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
401 Impl::BufferPositionMap::iterator end = d->children_positions.end();
402 for (; it != end; ++it) {
403 Buffer * child = const_cast<Buffer *>(it->first);
404 if (d->cloned_buffer_)
406 // The child buffer might have been closed already.
407 else if (theBufferList().isLoaded(child))
408 theBufferList().releaseChild(this, child);
412 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
413 msg += emergencyWrite();
414 Alert::warning(_("Attempting to close changed document!"), msg);
417 // clear references to children in macro tables
418 d->children_positions.clear();
419 d->position_to_children.clear();
421 if (!d->cloned_buffer_ && !d->temppath.destroyDirectory()) {
422 Alert::warning(_("Could not remove temporary directory"),
423 bformat(_("Could not remove the temporary directory %1$s"),
424 from_utf8(d->temppath.absFileName())));
434 Buffer * Buffer::clone() const
437 masterBuffer()->clone(bufmap);
438 BufferMap::iterator it = bufmap.find(this);
439 LASSERT(it != bufmap.end(), return 0);
444 void Buffer::clone(BufferMap & bufmap) const
446 // have we already been cloned?
447 if (bufmap.find(this) != bufmap.end())
450 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
451 bufmap[this] = buffer_clone;
452 buffer_clone->d->macro_lock = true;
453 buffer_clone->d->children_positions.clear();
454 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
455 // math macro caches need to be rethought and simplified.
456 // I am not sure wether we should handle Buffer cloning here or in BufferList.
457 // Right now BufferList knows nothing about buffer clones.
458 Impl::PositionScopeBufferMap::iterator it = d->position_to_children.begin();
459 Impl::PositionScopeBufferMap::iterator end = d->position_to_children.end();
460 for (; it != end; ++it) {
461 DocIterator dit = it->first.clone(buffer_clone);
462 dit.setBuffer(buffer_clone);
463 Buffer * child = const_cast<Buffer *>(it->second.second);
465 child->clone(bufmap);
466 BufferMap::iterator const bit = bufmap.find(child);
467 LASSERT(bit != bufmap.end(), continue);
468 Buffer * child_clone = bit->second;
470 Inset * inset = dit.nextInset();
471 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
472 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
473 inset_inc->setChildBuffer(child_clone);
474 child_clone->d->setParent(buffer_clone);
475 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
476 buffer_clone->setChild(dit, child_clone);
478 buffer_clone->d->macro_lock = false;
483 bool Buffer::isClone() const
485 return d->cloned_buffer_;
489 void Buffer::changed(bool update_metrics) const
492 d->wa_->redrawAll(update_metrics);
496 frontend::WorkAreaManager & Buffer::workAreaManager() const
498 LASSERT(d->wa_, /**/);
503 Text & Buffer::text() const
505 return d->inset->text();
509 Inset & Buffer::inset() const
515 BufferParams & Buffer::params()
521 BufferParams const & Buffer::params() const
527 ParagraphList & Buffer::paragraphs()
529 return text().paragraphs();
533 ParagraphList const & Buffer::paragraphs() const
535 return text().paragraphs();
539 LyXVC & Buffer::lyxvc()
545 LyXVC const & Buffer::lyxvc() const
551 string const Buffer::temppath() const
553 return d->temppath.absFileName();
557 TexRow & Buffer::texrow()
563 TexRow const & Buffer::texrow() const
569 TocBackend & Buffer::tocBackend() const
571 return d->toc_backend;
575 Undo & Buffer::undo()
581 void Buffer::setChild(DocIterator const & dit, Buffer * child)
583 d->children_positions[child] = dit;
587 string Buffer::latexName(bool const no_path) const
589 FileName latex_name =
590 makeLatexName(d->exportFileName());
591 return no_path ? latex_name.onlyFileName()
592 : latex_name.absFileName();
596 FileName Buffer::Impl::exportFileName() const
598 docstring const branch_suffix =
599 params.branchlist().getFileNameSuffix();
600 if (branch_suffix.empty())
603 string const name = filename.onlyFileNameWithoutExt()
604 + to_utf8(branch_suffix);
605 FileName res(filename.onlyPath().absFileName() + "/" + name);
606 res.changeExtension(filename.extension());
612 string Buffer::logName(LogType * type) const
614 string const filename = latexName(false);
616 if (filename.empty()) {
622 string const path = temppath();
624 FileName const fname(addName(temppath(),
625 onlyFileName(changeExtension(filename,
628 // FIXME: how do we know this is the name of the build log?
629 FileName const bname(
630 addName(path, onlyFileName(
631 changeExtension(filename,
632 formats.extension(params().bufferFormat()) + ".out"))));
634 // Also consider the master buffer log file
635 FileName masterfname = fname;
637 if (masterBuffer() != this) {
638 string const mlogfile = masterBuffer()->logName(&mtype);
639 masterfname = FileName(mlogfile);
642 // If no Latex log or Build log is newer, show Build log
643 if (bname.exists() &&
644 ((!fname.exists() && !masterfname.exists())
645 || (fname.lastModified() < bname.lastModified()
646 && masterfname.lastModified() < bname.lastModified()))) {
647 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
650 return bname.absFileName();
651 // If we have a newer master file log or only a master log, show this
652 } else if (fname != masterfname
653 && (!fname.exists() && (masterfname.exists()
654 || fname.lastModified() < masterfname.lastModified()))) {
655 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
658 return masterfname.absFileName();
660 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
663 return fname.absFileName();
667 void Buffer::setReadonly(bool const flag)
669 if (d->read_only != flag) {
676 void Buffer::setFileName(FileName const & fname)
679 setReadonly(d->filename.isReadOnly());
685 int Buffer::readHeader(Lexer & lex)
687 int unknown_tokens = 0;
689 int begin_header_line = -1;
691 // Initialize parameters that may be/go lacking in header:
692 params().branchlist().clear();
693 params().preamble.erase();
694 params().options.erase();
695 params().master.erase();
696 params().float_placement.erase();
697 params().paperwidth.erase();
698 params().paperheight.erase();
699 params().leftmargin.erase();
700 params().rightmargin.erase();
701 params().topmargin.erase();
702 params().bottommargin.erase();
703 params().headheight.erase();
704 params().headsep.erase();
705 params().footskip.erase();
706 params().columnsep.erase();
707 params().fonts_cjk.erase();
708 params().listings_params.clear();
709 params().clearLayoutModules();
710 params().clearRemovedModules();
711 params().clearIncludedChildren();
712 params().pdfoptions().clear();
713 params().indiceslist().clear();
714 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
715 params().isbackgroundcolor = false;
716 params().fontcolor = RGBColor(0, 0, 0);
717 params().isfontcolor = false;
718 params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
719 params().boxbgcolor = RGBColor(0xFF, 0, 0);
720 params().html_latex_start.clear();
721 params().html_latex_end.clear();
722 params().html_math_img_scale = 1.0;
723 params().output_sync_macro.erase();
725 for (int i = 0; i < 4; ++i) {
726 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
727 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
730 ErrorList & errorList = d->errorLists["Parse"];
739 if (token == "\\end_header")
743 if (token == "\\begin_header") {
744 begin_header_line = line;
748 LYXERR(Debug::PARSER, "Handling document header token: `"
751 string unknown = params().readToken(lex, token, d->filename.onlyPath());
752 if (!unknown.empty()) {
753 if (unknown[0] != '\\' && token == "\\textclass") {
754 Alert::warning(_("Unknown document class"),
755 bformat(_("Using the default document class, because the "
756 "class %1$s is unknown."), from_utf8(unknown)));
759 docstring const s = bformat(_("Unknown token: "
763 errorList.push_back(ErrorItem(_("Document header error"),
768 if (begin_header_line) {
769 docstring const s = _("\\begin_header is missing");
770 errorList.push_back(ErrorItem(_("Document header error"),
774 params().makeDocumentClass();
776 return unknown_tokens;
781 // changed to be public and have one parameter
782 // Returns true if "\end_document" is not read (Asger)
783 bool Buffer::readDocument(Lexer & lex)
785 ErrorList & errorList = d->errorLists["Parse"];
788 // remove dummy empty par
789 paragraphs().clear();
791 if (!lex.checkFor("\\begin_document")) {
792 docstring const s = _("\\begin_document is missing");
793 errorList.push_back(ErrorItem(_("Document header error"),
799 if (params().outputChanges) {
800 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
801 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
802 LaTeXFeatures::isAvailable("xcolor");
804 if (!dvipost && !xcolorulem) {
805 Alert::warning(_("Changes not shown in LaTeX output"),
806 _("Changes will not be highlighted in LaTeX output, "
807 "because neither dvipost nor xcolor/ulem are installed.\n"
808 "Please install these packages or redefine "
809 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
810 } else if (!xcolorulem) {
811 Alert::warning(_("Changes not shown in LaTeX output"),
812 _("Changes will not be highlighted in LaTeX output "
813 "when using pdflatex, because xcolor and ulem are not installed.\n"
814 "Please install both packages or redefine "
815 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
819 if (!params().master.empty()) {
820 FileName const master_file = makeAbsPath(params().master,
821 onlyPath(absFileName()));
822 if (isLyXFileName(master_file.absFileName())) {
824 checkAndLoadLyXFile(master_file, true);
826 // necessary e.g. after a reload
827 // to re-register the child (bug 5873)
828 // FIXME: clean up updateMacros (here, only
829 // child registering is needed).
830 master->updateMacros();
831 // set master as master buffer, but only
832 // if we are a real child
833 if (master->isChild(this))
835 // if the master is not fully loaded
836 // it is probably just loading this
837 // child. No warning needed then.
838 else if (master->isFullyLoaded())
839 LYXERR0("The master '"
841 << "' assigned to this document ("
843 << ") does not include "
844 "this document. Ignoring the master assignment.");
849 // assure we have a default index
850 params().indiceslist().addDefault(B_("Index"));
853 bool const res = text().read(lex, errorList, d->inset);
855 // inform parent buffer about local macros
857 Buffer const * pbuf = parent();
858 UserMacroSet::const_iterator cit = usermacros.begin();
859 UserMacroSet::const_iterator end = usermacros.end();
860 for (; cit != end; ++cit)
861 pbuf->usermacros.insert(*cit);
865 updateMacroInstances(InternalUpdate);
870 bool Buffer::readString(string const & s)
872 params().compressed = false;
877 FileName const fn = FileName::tempName("Buffer_readString");
880 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
881 if (ret_plf != ReadSuccess)
884 if (file_format != LYX_FORMAT) {
885 // We need to call lyx2lyx, so write the input to a file
886 ofstream os(fn.toFilesystemEncoding().c_str());
890 return readFile(fn) == ReadSuccess;
893 if (readDocument(lex))
899 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
903 if (!lex.setFile(fname)) {
904 Alert::error(_("File Not Found"),
905 bformat(_("Unable to open file `%1$s'."),
906 from_utf8(fn.absFileName())));
907 return ReadFileNotFound;
911 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
912 if (ret_plf != ReadSuccess)
915 if (file_format != LYX_FORMAT) {
917 ReadStatus const ret_clf = convertLyXFormat(fn, tmpFile, file_format);
918 if (ret_clf != ReadSuccess)
920 return readFile(tmpFile);
923 // FIXME: InsetInfo needs to know whether the file is under VCS
924 // during the parse process, so this has to be done before.
925 lyxvc().file_found_hook(d->filename);
927 if (readDocument(lex)) {
928 Alert::error(_("Document format failure"),
929 bformat(_("%1$s ended unexpectedly, which means"
930 " that it is probably corrupted."),
931 from_utf8(fn.absFileName())));
932 return ReadDocumentFailure;
935 d->file_fully_loaded = true;
936 d->read_only = !d->filename.isWritable();
937 params().compressed = d->filename.isZippedFile();
943 bool Buffer::isFullyLoaded() const
945 return d->file_fully_loaded;
949 void Buffer::setFullyLoaded(bool value)
951 d->file_fully_loaded = value;
955 PreviewLoader * Buffer::loader() const
957 if (lyxrc.preview == LyXRC::PREVIEW_OFF)
959 if (!d->preview_loader_)
960 d->preview_loader_ = new PreviewLoader(*this);
961 return d->preview_loader_;
965 void Buffer::removePreviews() const
967 delete d->preview_loader_;
968 d->preview_loader_ = 0;
972 void Buffer::updatePreviews() const
974 PreviewLoader * ploader = loader();
978 InsetIterator it = inset_iterator_begin(*d->inset);
979 InsetIterator const end = inset_iterator_end(*d->inset);
980 for (; it != end; ++it)
981 it->addPreview(it, *ploader);
983 ploader->startLoading();
987 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
988 FileName const & fn, int & file_format) const
990 if(!lex.checkFor("\\lyxformat")) {
991 Alert::error(_("Document format failure"),
992 bformat(_("%1$s is not a readable LyX document."),
993 from_utf8(fn.absFileName())));
994 return ReadNoLyXFormat;
1000 // LyX formats 217 and earlier were written as 2.17. This corresponds
1001 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1002 // these cases. See also: www.lyx.org/trac/changeset/1313.
1003 size_t dot = tmp_format.find_first_of(".,");
1004 if (dot != string::npos)
1005 tmp_format.erase(dot, 1);
1007 file_format = convert<int>(tmp_format);
1012 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1013 FileName & tmpfile, int from_format)
1015 tmpfile = FileName::tempName("Buffer_convertLyXFormat");
1016 if(tmpfile.empty()) {
1017 Alert::error(_("Conversion failed"),
1018 bformat(_("%1$s is from a different"
1019 " version of LyX, but a temporary"
1020 " file for converting it could"
1021 " not be created."),
1022 from_utf8(fn.absFileName())));
1023 return LyX2LyXNoTempFile;
1026 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1027 if (lyx2lyx.empty()) {
1028 Alert::error(_("Conversion script not found"),
1029 bformat(_("%1$s is from a different"
1030 " version of LyX, but the"
1031 " conversion script lyx2lyx"
1032 " could not be found."),
1033 from_utf8(fn.absFileName())));
1034 return LyX2LyXNotFound;
1038 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1039 ostringstream command;
1040 command << os::python()
1041 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1042 << " -t " << convert<string>(LYX_FORMAT)
1043 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
1044 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1045 string const command_str = command.str();
1047 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1049 cmd_ret const ret = runCommand(command_str);
1050 if (ret.first != 0) {
1051 if (from_format < LYX_FORMAT) {
1052 Alert::error(_("Conversion script failed"),
1053 bformat(_("%1$s is from an older version"
1054 " of LyX and the lyx2lyx script"
1055 " failed to convert it."),
1056 from_utf8(fn.absFileName())));
1057 return LyX2LyXOlderFormat;
1059 Alert::error(_("Conversion script failed"),
1060 bformat(_("%1$s is from a newer version"
1061 " of LyX and the lyx2lyx script"
1062 " failed to convert it."),
1063 from_utf8(fn.absFileName())));
1064 return LyX2LyXNewerFormat;
1071 // Should probably be moved to somewhere else: BufferView? GuiView?
1072 bool Buffer::save() const
1074 docstring const file = makeDisplayPath(absFileName(), 20);
1075 d->filename.refresh();
1077 // check the read-only status before moving the file as a backup
1078 if (d->filename.exists()) {
1079 bool const read_only = !d->filename.isWritable();
1081 Alert::warning(_("File is read-only"),
1082 bformat(_("The file %1$s cannot be written because it "
1083 "is marked as read-only."), file));
1088 // ask if the disk file has been externally modified (use checksum method)
1089 if (fileName().exists() && isExternallyModified(checksum_method)) {
1091 bformat(_("Document %1$s has been externally modified. "
1092 "Are you sure you want to overwrite this file?"), file);
1093 int const ret = Alert::prompt(_("Overwrite modified file?"),
1094 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1099 // We don't need autosaves in the immediate future. (Asger)
1100 resetAutosaveTimers();
1102 FileName backupName;
1103 bool madeBackup = false;
1105 // make a backup if the file already exists
1106 if (lyxrc.make_backup && fileName().exists()) {
1107 backupName = FileName(absFileName() + '~');
1108 if (!lyxrc.backupdir_path.empty()) {
1109 string const mangledName =
1110 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1111 backupName = FileName(addName(lyxrc.backupdir_path,
1115 // Except file is symlink do not copy because of #6587.
1116 // Hard links have bad luck.
1117 if (fileName().isSymLink())
1118 madeBackup = fileName().copyTo(backupName);
1120 madeBackup = fileName().moveTo(backupName);
1123 Alert::error(_("Backup failure"),
1124 bformat(_("Cannot create backup file %1$s.\n"
1125 "Please check whether the directory exists and is writable."),
1126 from_utf8(backupName.absFileName())));
1127 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1131 if (writeFile(d->filename)) {
1135 // Saving failed, so backup is not backup
1137 backupName.moveTo(d->filename);
1143 bool Buffer::writeFile(FileName const & fname) const
1145 // FIXME Do we need to do these here? I don't think writing
1146 // the LyX file depends upon it. (RGH)
1148 // updateMacroInstances();
1150 if (d->read_only && fname == d->filename)
1153 bool retval = false;
1155 docstring const str = bformat(_("Saving document %1$s..."),
1156 makeDisplayPath(fname.absFileName()));
1159 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1161 if (params().compressed) {
1162 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1163 retval = ofs && write(ofs);
1165 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1166 retval = ofs && write(ofs);
1170 message(str + _(" could not write file!"));
1175 // removeAutosaveFile();
1178 message(str + _(" done."));
1184 docstring Buffer::emergencyWrite()
1186 // No need to save if the buffer has not changed.
1190 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1192 docstring user_message = bformat(
1193 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1195 // We try to save three places:
1196 // 1) Same place as document. Unless it is an unnamed doc.
1198 string s = absFileName();
1201 if (writeFile(FileName(s))) {
1203 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1204 return user_message;
1206 user_message += " " + _("Save failed! Trying again...\n");
1210 // 2) In HOME directory.
1211 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1213 lyxerr << ' ' << s << endl;
1214 if (writeFile(FileName(s))) {
1216 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1217 return user_message;
1220 user_message += " " + _("Save failed! Trying yet again...\n");
1222 // 3) In "/tmp" directory.
1223 // MakeAbsPath to prepend the current
1224 // drive letter on OS/2
1225 s = addName(package().temp_dir().absFileName(), absFileName());
1227 lyxerr << ' ' << s << endl;
1228 if (writeFile(FileName(s))) {
1230 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1231 return user_message;
1234 user_message += " " + _("Save failed! Bummer. Document is lost.");
1237 return user_message;
1241 bool Buffer::write(ostream & ofs) const
1244 // Use the standard "C" locale for file output.
1245 ofs.imbue(locale::classic());
1248 // The top of the file should not be written by params().
1250 // write out a comment in the top of the file
1251 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1252 << " created this file. For more info see http://www.lyx.org/\n"
1253 << "\\lyxformat " << LYX_FORMAT << "\n"
1254 << "\\begin_document\n";
1256 /// For each author, set 'used' to true if there is a change
1257 /// by this author in the document; otherwise set it to 'false'.
1258 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1259 AuthorList::Authors::const_iterator a_end = params().authors().end();
1260 for (; a_it != a_end; ++a_it)
1261 a_it->setUsed(false);
1263 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1264 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1265 for ( ; it != end; ++it)
1266 it->checkAuthors(params().authors());
1268 // now write out the buffer parameters.
1269 ofs << "\\begin_header\n";
1270 params().writeFile(ofs);
1271 ofs << "\\end_header\n";
1274 ofs << "\n\\begin_body\n";
1276 ofs << "\n\\end_body\n";
1278 // Write marker that shows file is complete
1279 ofs << "\\end_document" << endl;
1281 // Shouldn't really be needed....
1284 // how to check if close went ok?
1285 // Following is an attempt... (BE 20001011)
1287 // good() returns false if any error occured, including some
1288 // formatting error.
1289 // bad() returns true if something bad happened in the buffer,
1290 // which should include file system full errors.
1295 lyxerr << "File was not closed properly." << endl;
1302 bool Buffer::makeLaTeXFile(FileName const & fname,
1303 string const & original_path,
1304 OutputParams const & runparams_in,
1305 bool output_preamble, bool output_body) const
1307 OutputParams runparams = runparams_in;
1309 // This is necessary for LuaTeX/XeTeX with tex fonts.
1310 // See FIXME in BufferParams::encoding()
1311 if (runparams.isFullUnicode())
1312 runparams.encoding = encodings.fromLyXName("utf8-plain");
1314 string const encoding = runparams.encoding->iconvName();
1315 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1318 try { ofs.reset(encoding); }
1319 catch (iconv_codecvt_facet_exception & e) {
1320 lyxerr << "Caught iconv exception: " << e.what() << endl;
1321 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1322 "verify that the support software for your encoding (%1$s) is "
1323 "properly installed"), from_ascii(encoding)));
1326 if (!openFileWrite(ofs, fname))
1329 //TexStream ts(ofs.rdbuf(), &texrow());
1330 ErrorList & errorList = d->errorLists["Export"];
1332 bool failed_export = false;
1333 otexstream os(ofs, d->texrow);
1335 // make sure we are ready to export
1336 // this needs to be done before we validate
1337 // FIXME Do we need to do this all the time? I.e., in children
1338 // of a master we are exporting?
1340 updateMacroInstances(OutputUpdate);
1343 os.texrow().reset();
1344 writeLaTeXSource(os, original_path,
1345 runparams, output_preamble, output_body);
1347 catch (EncodingException & e) {
1348 odocstringstream ods;
1349 ods.put(e.failed_char);
1351 oss << "0x" << hex << e.failed_char << dec;
1352 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1353 " (code point %2$s)"),
1354 ods.str(), from_utf8(oss.str()));
1355 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1356 "representable in the chosen encoding.\n"
1357 "Changing the document encoding to utf8 could help."),
1358 e.par_id, e.pos, e.pos + 1));
1359 failed_export = true;
1361 catch (iconv_codecvt_facet_exception & e) {
1362 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1363 _(e.what()), -1, 0, 0));
1364 failed_export = true;
1366 catch (exception const & e) {
1367 errorList.push_back(ErrorItem(_("conversion failed"),
1368 _(e.what()), -1, 0, 0));
1369 failed_export = true;
1372 lyxerr << "Caught some really weird exception..." << endl;
1378 failed_export = true;
1379 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1383 return !failed_export;
1387 void Buffer::writeLaTeXSource(otexstream & os,
1388 string const & original_path,
1389 OutputParams const & runparams_in,
1390 bool const output_preamble, bool const output_body) const
1392 // The child documents, if any, shall be already loaded at this point.
1394 OutputParams runparams = runparams_in;
1396 // Classify the unicode characters appearing in math insets
1397 Encodings::initUnicodeMath(*this);
1399 // validate the buffer.
1400 LYXERR(Debug::LATEX, " Validating buffer...");
1401 LaTeXFeatures features(*this, params(), runparams);
1403 LYXERR(Debug::LATEX, " Buffer validation done.");
1405 // The starting paragraph of the coming rows is the
1406 // first paragraph of the document. (Asger)
1407 if (output_preamble && runparams.nice) {
1408 os << "%% LyX " << lyx_version << " created this file. "
1409 "For more info, see http://www.lyx.org/.\n"
1410 "%% Do not edit unless you really know what "
1413 LYXERR(Debug::INFO, "lyx document header finished");
1415 // There are a few differences between nice LaTeX and usual files:
1416 // usual files have \batchmode and special input@path to allow
1417 // inclusion of figures specified by an explicitly relative path
1418 // (i.e., a path starting with './' or '../') with either \input or
1419 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1420 // input@path is set when the actual parameter original_path is set.
1421 // This is done for usual tex-file, but not for nice-latex-file.
1422 // (Matthias 250696)
1423 // Note that input@path is only needed for something the user does
1424 // in the preamble, included .tex files or ERT, files included by
1425 // LyX work without it.
1426 if (output_preamble) {
1427 if (!runparams.nice) {
1428 // code for usual, NOT nice-latex-file
1429 os << "\\batchmode\n"; // changed from \nonstopmode
1431 if (!original_path.empty()) {
1433 // We don't know the encoding of inputpath
1434 docstring const inputpath = from_utf8(original_path);
1435 docstring uncodable_glyphs;
1436 Encoding const * const enc = runparams.encoding;
1438 for (size_t n = 0; n < inputpath.size(); ++n) {
1439 docstring const glyph =
1440 docstring(1, inputpath[n]);
1441 if (enc->latexChar(inputpath[n], true) != glyph) {
1442 LYXERR0("Uncodable character '"
1444 << "' in input path!");
1445 uncodable_glyphs += glyph;
1450 // warn user if we found uncodable glyphs.
1451 if (!uncodable_glyphs.empty()) {
1452 frontend::Alert::warning(
1453 _("Uncodable character in file path"),
1455 _("The path of your document\n"
1457 "contains glyphs that are unknown "
1458 "in the current document encoding "
1459 "(namely %2$s). This may result in "
1460 "incomplete output, unless "
1461 "TEXINPUTS contains the document "
1462 "directory and you don't use "
1463 "explicitly relative paths (i.e., "
1464 "paths starting with './' or "
1465 "'../') in the preamble or in ERT."
1466 "\n\nIn case of problems, choose "
1467 "an appropriate document encoding\n"
1468 "(such as utf8) or change the "
1470 inputpath, uncodable_glyphs));
1473 support::latex_path(original_path);
1474 if (contains(docdir, '#')) {
1475 docdir = subst(docdir, "#", "\\#");
1476 os << "\\catcode`\\#=11"
1477 "\\def\\#{#}\\catcode`\\#=6\n";
1479 if (contains(docdir, '%')) {
1480 docdir = subst(docdir, "%", "\\%");
1481 os << "\\catcode`\\%=11"
1482 "\\def\\%{%}\\catcode`\\%=14\n";
1484 os << "\\makeatletter\n"
1485 << "\\def\\input@path{{"
1486 << docdir << "/}}\n"
1487 << "\\makeatother\n";
1491 // get parent macros (if this buffer has a parent) which will be
1492 // written at the document begin further down.
1493 MacroSet parentMacros;
1494 listParentMacros(parentMacros, features);
1496 runparams.use_polyglossia = features.usePolyglossia();
1497 // Write the preamble
1498 runparams.use_babel = params().writeLaTeX(os, features,
1499 d->filename.onlyPath());
1501 runparams.use_japanese = features.isRequired("japanese");
1507 os << "\\begin{document}\n";
1509 // output the parent macros
1510 MacroSet::iterator it = parentMacros.begin();
1511 MacroSet::iterator end = parentMacros.end();
1512 for (; it != end; ++it) {
1513 int num_lines = (*it)->write(os.os(), true);
1514 os.texrow().newlines(num_lines);
1517 } // output_preamble
1519 os.texrow().start(paragraphs().begin()->id(), 0);
1521 LYXERR(Debug::INFO, "preamble finished, now the body.");
1523 // if we are doing a real file with body, even if this is the
1524 // child of some other buffer, let's cut the link here.
1525 // This happens for example if only a child document is printed.
1526 Buffer const * save_parent = 0;
1527 if (output_preamble) {
1528 save_parent = d->parent();
1533 latexParagraphs(*this, text(), os, runparams);
1535 // Restore the parenthood if needed
1536 if (output_preamble)
1537 d->setParent(save_parent);
1539 // add this just in case after all the paragraphs
1542 if (output_preamble) {
1543 os << "\\end{document}\n";
1544 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1546 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1548 runparams_in.encoding = runparams.encoding;
1550 // Just to be sure. (Asger)
1551 os.texrow().newline();
1553 //for (int i = 0; i<d->texrow.rows(); i++) {
1555 // if (d->texrow.getIdFromRow(i+1,id,pos) && id>0)
1556 // lyxerr << i+1 << ":" << id << ":" << getParFromID(id).paragraph().asString()<<"\n";
1559 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1560 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
1564 void Buffer::makeDocBookFile(FileName const & fname,
1565 OutputParams const & runparams,
1566 bool const body_only) const
1568 LYXERR(Debug::LATEX, "makeDocBookFile...");
1571 if (!openFileWrite(ofs, fname))
1574 // make sure we are ready to export
1575 // this needs to be done before we validate
1577 updateMacroInstances(OutputUpdate);
1579 writeDocBookSource(ofs, fname.absFileName(), runparams, body_only);
1583 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1587 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1588 OutputParams const & runparams,
1589 bool const only_body) const
1591 LaTeXFeatures features(*this, params(), runparams);
1596 DocumentClass const & tclass = params().documentClass();
1597 string const top_element = tclass.latexname();
1600 if (runparams.flavor == OutputParams::XML)
1601 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1604 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1607 if (! tclass.class_header().empty())
1608 os << from_ascii(tclass.class_header());
1609 else if (runparams.flavor == OutputParams::XML)
1610 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1611 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1613 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1615 docstring preamble = from_utf8(params().preamble);
1616 if (runparams.flavor != OutputParams::XML ) {
1617 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1618 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1619 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1620 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1623 string const name = runparams.nice
1624 ? changeExtension(absFileName(), ".sgml") : fname;
1625 preamble += features.getIncludedFiles(name);
1626 preamble += features.getLyXSGMLEntities();
1628 if (!preamble.empty()) {
1629 os << "\n [ " << preamble << " ]";
1634 string top = top_element;
1636 if (runparams.flavor == OutputParams::XML)
1637 top += params().language->code();
1639 top += params().language->code().substr(0, 2);
1642 if (!params().options.empty()) {
1644 top += params().options;
1647 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1648 << " file was created by LyX " << lyx_version
1649 << "\n See http://www.lyx.org/ for more information -->\n";
1651 params().documentClass().counters().reset();
1653 sgml::openTag(os, top);
1655 docbookParagraphs(text(), *this, os, runparams);
1656 sgml::closeTag(os, top_element);
1660 void Buffer::makeLyXHTMLFile(FileName const & fname,
1661 OutputParams const & runparams) const
1663 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1666 if (!openFileWrite(ofs, fname))
1669 // make sure we are ready to export
1670 // this has to be done before we validate
1671 updateBuffer(UpdateMaster, OutputUpdate);
1672 updateMacroInstances(OutputUpdate);
1674 writeLyXHTMLSource(ofs, runparams);
1678 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1682 void Buffer::writeLyXHTMLSource(odocstream & os,
1683 OutputParams const & runparams,
1684 bool const only_body) const
1686 LaTeXFeatures features(*this, params(), runparams);
1688 d->bibinfo_.makeCitationLabels(*this);
1691 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1692 << "<!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"
1693 // FIXME Language should be set properly.
1694 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
1696 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
1697 // FIXME Presumably need to set this right
1698 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1700 docstring const & doctitle = features.htmlTitle();
1702 << (doctitle.empty() ? from_ascii("LyX Document") : doctitle)
1705 os << "\n<!-- Text Class Preamble -->\n"
1706 << features.getTClassHTMLPreamble()
1707 << "\n<!-- Preamble Snippets -->\n"
1708 << from_utf8(features.getPreambleSnippets());
1710 os << "\n<!-- Layout-provided Styles -->\n";
1711 docstring const styleinfo = features.getTClassHTMLStyles();
1712 if (!styleinfo.empty()) {
1713 os << "<style type='text/css'>\n"
1718 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
1719 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
1720 if (needfg || needbg) {
1721 os << "<style type='text/css'>\nbody {\n";
1724 << from_ascii(X11hexname(params().fontcolor))
1727 os << " background-color: "
1728 << from_ascii(X11hexname(params().backgroundcolor))
1730 os << "}\n</style>\n";
1732 os << "</head>\n<body>\n";
1736 params().documentClass().counters().reset();
1737 xhtmlParagraphs(text(), *this, xs, runparams);
1739 os << "</body>\n</html>\n";
1743 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1744 // Other flags: -wall -v0 -x
1745 int Buffer::runChktex()
1749 // get LaTeX-Filename
1750 FileName const path(temppath());
1751 string const name = addName(path.absFileName(), latexName());
1752 string const org_path = filePath();
1754 PathChanger p(path); // path to LaTeX file
1755 message(_("Running chktex..."));
1757 // Generate the LaTeX file if neccessary
1758 OutputParams runparams(¶ms().encoding());
1759 runparams.flavor = OutputParams::LATEX;
1760 runparams.nice = false;
1761 runparams.linelen = lyxrc.plaintext_linelen;
1762 makeLaTeXFile(FileName(name), org_path, runparams);
1765 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
1766 int const res = chktex.run(terr); // run chktex
1769 Alert::error(_("chktex failure"),
1770 _("Could not run chktex successfully."));
1771 } else if (res > 0) {
1772 ErrorList & errlist = d->errorLists["ChkTeX"];
1774 bufferErrors(terr, errlist);
1785 void Buffer::validate(LaTeXFeatures & features) const
1787 params().validate(features);
1789 for_each(paragraphs().begin(), paragraphs().end(),
1790 bind(&Paragraph::validate, _1, ref(features)));
1792 if (lyxerr.debugging(Debug::LATEX)) {
1793 features.showStruct();
1798 void Buffer::getLabelList(vector<docstring> & list) const
1800 // If this is a child document, use the master's list instead.
1802 masterBuffer()->getLabelList(list);
1807 Toc & toc = d->toc_backend.toc("label");
1808 TocIterator toc_it = toc.begin();
1809 TocIterator end = toc.end();
1810 for (; toc_it != end; ++toc_it) {
1811 if (toc_it->depth() == 0)
1812 list.push_back(toc_it->str());
1817 void Buffer::updateBibfilesCache(UpdateScope scope) const
1819 // FIXME This is probably unnecssary, given where we call this.
1820 // If this is a child document, use the parent's cache instead.
1821 if (parent() && scope != UpdateChildOnly) {
1822 masterBuffer()->updateBibfilesCache();
1826 d->bibfiles_cache_.clear();
1827 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1828 if (it->lyxCode() == BIBTEX_CODE) {
1829 InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
1830 support::FileNameList const bibfiles = inset.getBibFiles();
1831 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1834 } else if (it->lyxCode() == INCLUDE_CODE) {
1835 InsetInclude & inset = static_cast<InsetInclude &>(*it);
1836 Buffer const * const incbuf = inset.getChildBuffer();
1839 support::FileNameList const & bibfiles =
1840 incbuf->getBibfilesCache(UpdateChildOnly);
1841 if (!bibfiles.empty()) {
1842 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1848 d->bibfile_cache_valid_ = true;
1849 d->bibinfo_cache_valid_ = false;
1850 d->cite_labels_valid_ = false;
1854 void Buffer::invalidateBibinfoCache() const
1856 d->bibinfo_cache_valid_ = false;
1857 d->cite_labels_valid_ = false;
1858 // also invalidate the cache for the parent buffer
1859 Buffer const * const pbuf = d->parent();
1861 pbuf->invalidateBibinfoCache();
1865 void Buffer::invalidateBibfileCache() const
1867 d->bibfile_cache_valid_ = false;
1868 d->bibinfo_cache_valid_ = false;
1869 d->cite_labels_valid_ = false;
1870 // also invalidate the cache for the parent buffer
1871 Buffer const * const pbuf = d->parent();
1873 pbuf->invalidateBibfileCache();
1877 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1879 // FIXME This is probably unnecessary, given where we call this.
1880 // If this is a child document, use the master's cache instead.
1881 Buffer const * const pbuf = masterBuffer();
1882 if (pbuf != this && scope != UpdateChildOnly)
1883 return pbuf->getBibfilesCache();
1885 if (!d->bibfile_cache_valid_)
1886 this->updateBibfilesCache(scope);
1888 return d->bibfiles_cache_;
1892 BiblioInfo const & Buffer::masterBibInfo() const
1894 Buffer const * const tmp = masterBuffer();
1896 return tmp->masterBibInfo();
1901 void Buffer::checkIfBibInfoCacheIsValid() const
1903 // use the master's cache
1904 Buffer const * const tmp = masterBuffer();
1906 tmp->checkIfBibInfoCacheIsValid();
1910 // compare the cached timestamps with the actual ones.
1911 FileNameList const & bibfiles_cache = getBibfilesCache();
1912 FileNameList::const_iterator ei = bibfiles_cache.begin();
1913 FileNameList::const_iterator en = bibfiles_cache.end();
1914 for (; ei != en; ++ ei) {
1915 time_t lastw = ei->lastModified();
1916 time_t prevw = d->bibfile_status_[*ei];
1917 if (lastw != prevw) {
1918 d->bibinfo_cache_valid_ = false;
1919 d->cite_labels_valid_ = false;
1920 d->bibfile_status_[*ei] = lastw;
1926 void Buffer::reloadBibInfoCache() const
1928 // use the master's cache
1929 Buffer const * const tmp = masterBuffer();
1931 tmp->reloadBibInfoCache();
1935 checkIfBibInfoCacheIsValid();
1936 if (d->bibinfo_cache_valid_)
1939 d->bibinfo_.clear();
1941 d->bibinfo_cache_valid_ = true;
1945 void Buffer::collectBibKeys() const
1947 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1948 it->collectBibKeys(it);
1952 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
1954 Buffer const * tmp = masterBuffer();
1955 BiblioInfo & masterbi = (tmp == this) ?
1956 d->bibinfo_ : tmp->d->bibinfo_;
1957 masterbi.mergeBiblioInfo(bi);
1961 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
1963 Buffer const * tmp = masterBuffer();
1964 BiblioInfo & masterbi = (tmp == this) ?
1965 d->bibinfo_ : tmp->d->bibinfo_;
1970 bool Buffer::citeLabelsValid() const
1972 return masterBuffer()->d->cite_labels_valid_;
1976 bool Buffer::isDepClean(string const & name) const
1978 DepClean::const_iterator const it = d->dep_clean.find(name);
1979 if (it == d->dep_clean.end())
1985 void Buffer::markDepClean(string const & name)
1987 d->dep_clean[name] = true;
1991 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1994 // FIXME? if there is an Buffer LFUN that can be dispatched even
1995 // if internal, put a switch '(cmd.action)' here.
2001 switch (cmd.action()) {
2003 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2004 flag.setOnOff(isReadonly());
2007 // FIXME: There is need for a command-line import.
2008 //case LFUN_BUFFER_IMPORT:
2010 case LFUN_BUFFER_AUTO_SAVE:
2013 case LFUN_BUFFER_EXPORT_CUSTOM:
2014 // FIXME: Nothing to check here?
2017 case LFUN_BUFFER_EXPORT: {
2018 docstring const arg = cmd.argument();
2019 if (arg == "custom") {
2023 string format = to_utf8(arg);
2024 size_t pos = format.find(' ');
2025 if (pos != string::npos)
2026 format = format.substr(0, pos);
2027 enable = params().isExportable(format);
2029 flag.message(bformat(
2030 _("Don't know how to export to format: %1$s"), arg));
2034 case LFUN_BUFFER_CHKTEX:
2035 enable = params().isLatex() && !lyxrc.chktex_command.empty();
2038 case LFUN_BUILD_PROGRAM:
2039 enable = params().isExportable("program");
2042 case LFUN_BRANCH_ACTIVATE:
2043 case LFUN_BRANCH_DEACTIVATE: {
2044 BranchList const & branchList = params().branchlist();
2045 docstring const branchName = cmd.argument();
2046 enable = !branchName.empty() && branchList.find(branchName);
2050 case LFUN_BRANCH_ADD:
2051 case LFUN_BRANCHES_RENAME:
2052 case LFUN_BUFFER_PRINT:
2053 // if no Buffer is present, then of course we won't be called!
2056 case LFUN_BUFFER_LANGUAGE:
2057 enable = !isReadonly();
2063 flag.setEnabled(enable);
2068 void Buffer::dispatch(string const & command, DispatchResult & result)
2070 return dispatch(lyxaction.lookupFunc(command), result);
2074 // NOTE We can end up here even if we have no GUI, because we are called
2075 // by LyX::exec to handled command-line requests. So we may need to check
2076 // whether we have a GUI or not. The boolean use_gui holds this information.
2077 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2080 // FIXME? if there is an Buffer LFUN that can be dispatched even
2081 // if internal, put a switch '(cmd.action())' here.
2082 dr.dispatched(false);
2085 string const argument = to_utf8(func.argument());
2086 // We'll set this back to false if need be.
2087 bool dispatched = true;
2088 undo().beginUndoGroup();
2090 switch (func.action()) {
2091 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2092 if (lyxvc().inUse())
2093 lyxvc().toggleReadOnly();
2095 setReadonly(!isReadonly());
2098 case LFUN_BUFFER_EXPORT: {
2099 bool success = doExport(argument, false, false);
2100 dr.setError(!success);
2102 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2107 case LFUN_BUILD_PROGRAM:
2108 doExport("program", true, false);
2111 case LFUN_BUFFER_CHKTEX:
2115 case LFUN_BUFFER_EXPORT_CUSTOM: {
2117 string command = split(argument, format_name, ' ');
2118 Format const * format = formats.getFormat(format_name);
2120 lyxerr << "Format \"" << format_name
2121 << "\" not recognized!"
2126 // The name of the file created by the conversion process
2129 // Output to filename
2130 if (format->name() == "lyx") {
2131 string const latexname = latexName(false);
2132 filename = changeExtension(latexname,
2133 format->extension());
2134 filename = addName(temppath(), filename);
2136 if (!writeFile(FileName(filename)))
2140 doExport(format_name, true, false, filename);
2143 // Substitute $$FName for filename
2144 if (!contains(command, "$$FName"))
2145 command = "( " + command + " ) < $$FName";
2146 command = subst(command, "$$FName", filename);
2148 // Execute the command in the background
2150 call.startscript(Systemcall::DontWait, command, filePath());
2154 // FIXME: There is need for a command-line import.
2156 case LFUN_BUFFER_IMPORT:
2161 case LFUN_BUFFER_AUTO_SAVE:
2163 resetAutosaveTimers();
2166 case LFUN_BRANCH_ADD: {
2167 docstring branch_name = func.argument();
2168 if (branch_name.empty()) {
2172 BranchList & branch_list = params().branchlist();
2173 vector<docstring> const branches =
2174 getVectorFromString(branch_name, branch_list.separator());
2176 for (vector<docstring>::const_iterator it = branches.begin();
2177 it != branches.end(); ++it) {
2179 Branch * branch = branch_list.find(branch_name);
2181 LYXERR0("Branch " << branch_name << " already exists.");
2185 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2187 branch_list.add(branch_name);
2188 branch = branch_list.find(branch_name);
2189 string const x11hexname = X11hexname(branch->color());
2190 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2191 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2193 dr.screenUpdate(Update::Force);
2201 case LFUN_BRANCH_ACTIVATE:
2202 case LFUN_BRANCH_DEACTIVATE: {
2203 BranchList & branchList = params().branchlist();
2204 docstring const branchName = func.argument();
2205 // the case without a branch name is handled elsewhere
2206 if (branchName.empty()) {
2210 Branch * branch = branchList.find(branchName);
2212 LYXERR0("Branch " << branchName << " does not exist.");
2214 docstring const msg =
2215 bformat(_("Branch \"%1$s\" does not exist."), branchName);
2218 branch->setSelected(func.action() == LFUN_BRANCH_ACTIVATE);
2220 dr.screenUpdate(Update::Force);
2221 dr.forceBufferUpdate();
2226 case LFUN_BRANCHES_RENAME: {
2227 if (func.argument().empty())
2230 docstring const oldname = from_utf8(func.getArg(0));
2231 docstring const newname = from_utf8(func.getArg(1));
2232 InsetIterator it = inset_iterator_begin(inset());
2233 InsetIterator const end = inset_iterator_end(inset());
2234 bool success = false;
2235 for (; it != end; ++it) {
2236 if (it->lyxCode() == BRANCH_CODE) {
2237 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2238 if (ins.branch() == oldname) {
2239 undo().recordUndo(it);
2240 ins.rename(newname);
2245 if (it->lyxCode() == INCLUDE_CODE) {
2246 // get buffer of external file
2247 InsetInclude const & ins =
2248 static_cast<InsetInclude const &>(*it);
2249 Buffer * child = ins.getChildBuffer();
2252 child->dispatch(func, dr);
2257 dr.screenUpdate(Update::Force);
2258 dr.forceBufferUpdate();
2263 case LFUN_BUFFER_PRINT: {
2264 // we'll assume there's a problem until we succeed
2266 string target = func.getArg(0);
2267 string target_name = func.getArg(1);
2268 string command = func.getArg(2);
2271 || target_name.empty()
2272 || command.empty()) {
2273 LYXERR0("Unable to parse " << func.argument());
2274 docstring const msg =
2275 bformat(_("Unable to parse \"%1$s\""), func.argument());
2279 if (target != "printer" && target != "file") {
2280 LYXERR0("Unrecognized target \"" << target << '"');
2281 docstring const msg =
2282 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2287 bool const update_unincluded =
2288 params().maintain_unincluded_children
2289 && !params().getIncludedChildren().empty();
2290 if (!doExport("dvi", true, update_unincluded)) {
2291 showPrintError(absFileName());
2292 dr.setMessage(_("Error exporting to DVI."));
2296 // Push directory path.
2297 string const path = temppath();
2298 // Prevent the compiler from optimizing away p
2302 // there are three cases here:
2303 // 1. we print to a file
2304 // 2. we print directly to a printer
2305 // 3. we print using a spool command (print to file first)
2308 string const dviname = changeExtension(latexName(true), "dvi");
2310 if (target == "printer") {
2311 if (!lyxrc.print_spool_command.empty()) {
2312 // case 3: print using a spool
2313 string const psname = changeExtension(dviname,".ps");
2314 command += ' ' + lyxrc.print_to_file
2317 + quoteName(dviname);
2319 string command2 = lyxrc.print_spool_command + ' ';
2320 if (target_name != "default") {
2321 command2 += lyxrc.print_spool_printerprefix
2325 command2 += quoteName(psname);
2327 // If successful, then spool command
2328 res = one.startscript(Systemcall::Wait, command,
2332 // If there's no GUI, we have to wait on this command. Otherwise,
2333 // LyX deletes the temporary directory, and with it the spooled
2334 // file, before it can be printed!!
2335 Systemcall::Starttype stype = use_gui ?
2336 Systemcall::DontWait : Systemcall::Wait;
2337 res = one.startscript(stype, command2,
2341 // case 2: print directly to a printer
2342 if (target_name != "default")
2343 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2345 Systemcall::Starttype stype = use_gui ?
2346 Systemcall::DontWait : Systemcall::Wait;
2347 res = one.startscript(stype, command +
2348 quoteName(dviname), filePath());
2352 // case 1: print to a file
2353 FileName const filename(makeAbsPath(target_name, filePath()));
2354 FileName const dvifile(makeAbsPath(dviname, path));
2355 if (filename.exists()) {
2356 docstring text = bformat(
2357 _("The file %1$s already exists.\n\n"
2358 "Do you want to overwrite that file?"),
2359 makeDisplayPath(filename.absFileName()));
2360 if (Alert::prompt(_("Overwrite file?"),
2361 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2364 command += ' ' + lyxrc.print_to_file
2365 + quoteName(filename.toFilesystemEncoding())
2367 + quoteName(dvifile.toFilesystemEncoding());
2369 Systemcall::Starttype stype = use_gui ?
2370 Systemcall::DontWait : Systemcall::Wait;
2371 res = one.startscript(stype, command, filePath());
2377 dr.setMessage(_("Error running external commands."));
2378 showPrintError(absFileName());
2387 dr.dispatched(dispatched);
2388 undo().endUndoGroup();
2392 void Buffer::changeLanguage(Language const * from, Language const * to)
2394 LASSERT(from, /**/);
2397 for_each(par_iterator_begin(),
2399 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2403 bool Buffer::isMultiLingual() const
2405 ParConstIterator end = par_iterator_end();
2406 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2407 if (it->isMultiLingual(params()))
2414 std::set<Language const *> Buffer::getLanguages() const
2416 std::set<Language const *> languages;
2417 getLanguages(languages);
2422 void Buffer::getLanguages(std::set<Language const *> & languages) const
2424 ParConstIterator end = par_iterator_end();
2425 // add the buffer language, even if it's not actively used
2426 languages.insert(language());
2427 // iterate over the paragraphs
2428 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2429 it->getLanguages(languages);
2431 ListOfBuffers clist = getDescendents();
2432 ListOfBuffers::const_iterator cit = clist.begin();
2433 ListOfBuffers::const_iterator const cen = clist.end();
2434 for (; cit != cen; ++cit)
2435 (*cit)->getLanguages(languages);
2439 DocIterator Buffer::getParFromID(int const id) const
2441 Buffer * buf = const_cast<Buffer *>(this);
2443 // John says this is called with id == -1 from undo
2444 lyxerr << "getParFromID(), id: " << id << endl;
2445 return doc_iterator_end(buf);
2448 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2449 if (it.paragraph().id() == id)
2452 return doc_iterator_end(buf);
2456 bool Buffer::hasParWithID(int const id) const
2458 return !getParFromID(id).atEnd();
2462 ParIterator Buffer::par_iterator_begin()
2464 return ParIterator(doc_iterator_begin(this));
2468 ParIterator Buffer::par_iterator_end()
2470 return ParIterator(doc_iterator_end(this));
2474 ParConstIterator Buffer::par_iterator_begin() const
2476 return ParConstIterator(doc_iterator_begin(this));
2480 ParConstIterator Buffer::par_iterator_end() const
2482 return ParConstIterator(doc_iterator_end(this));
2486 Language const * Buffer::language() const
2488 return params().language;
2492 docstring const Buffer::B_(string const & l10n) const
2494 return params().B_(l10n);
2498 bool Buffer::isClean() const
2500 return d->lyx_clean;
2504 bool Buffer::isExternallyModified(CheckMethod method) const
2506 LASSERT(d->filename.exists(), /**/);
2507 // if method == timestamp, check timestamp before checksum
2508 return (method == checksum_method
2509 || d->timestamp_ != d->filename.lastModified())
2510 && d->checksum_ != d->filename.checksum();
2514 void Buffer::saveCheckSum() const
2516 FileName const & file = d->filename;
2519 if (file.exists()) {
2520 d->timestamp_ = file.lastModified();
2521 d->checksum_ = file.checksum();
2523 // in the case of save to a new file.
2530 void Buffer::markClean() const
2532 if (!d->lyx_clean) {
2533 d->lyx_clean = true;
2536 // if the .lyx file has been saved, we don't need an
2538 d->bak_clean = true;
2539 d->undo_.markDirty();
2543 void Buffer::setUnnamed(bool flag)
2549 bool Buffer::isUnnamed() const
2556 /// Don't check unnamed, here: isInternal() is used in
2557 /// newBuffer(), where the unnamed flag has not been set by anyone
2558 /// yet. Also, for an internal buffer, there should be no need for
2559 /// retrieving fileName() nor for checking if it is unnamed or not.
2560 bool Buffer::isInternal() const
2562 return fileName().extension() == "internal";
2566 void Buffer::markDirty()
2569 d->lyx_clean = false;
2572 d->bak_clean = false;
2574 DepClean::iterator it = d->dep_clean.begin();
2575 DepClean::const_iterator const end = d->dep_clean.end();
2577 for (; it != end; ++it)
2582 FileName Buffer::fileName() const
2588 string Buffer::absFileName() const
2590 return d->filename.absFileName();
2594 string Buffer::filePath() const
2596 return d->filename.onlyPath().absFileName() + "/";
2600 bool Buffer::isReadonly() const
2602 return d->read_only;
2606 void Buffer::setParent(Buffer const * buffer)
2608 // Avoids recursive include.
2609 d->setParent(buffer == this ? 0 : buffer);
2614 Buffer const * Buffer::parent() const
2620 ListOfBuffers Buffer::allRelatives() const
2622 ListOfBuffers lb = masterBuffer()->getDescendents();
2623 lb.push_front(const_cast<Buffer *>(masterBuffer()));
2628 Buffer const * Buffer::masterBuffer() const
2630 // FIXME Should be make sure we are not in some kind
2631 // of recursive include? A -> B -> A will crash this.
2632 Buffer const * const pbuf = d->parent();
2636 return pbuf->masterBuffer();
2640 bool Buffer::isChild(Buffer * child) const
2642 return d->children_positions.find(child) != d->children_positions.end();
2646 DocIterator Buffer::firstChildPosition(Buffer const * child)
2648 Impl::BufferPositionMap::iterator it;
2649 it = d->children_positions.find(child);
2650 if (it == d->children_positions.end())
2651 return DocIterator(this);
2656 bool Buffer::hasChildren() const
2658 return !d->children_positions.empty();
2662 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
2664 // loop over children
2665 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2666 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2667 for (; it != end; ++it) {
2668 Buffer * child = const_cast<Buffer *>(it->first);
2670 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
2671 if (bit != clist.end())
2673 clist.push_back(child);
2675 // there might be grandchildren
2676 child->collectChildren(clist, true);
2681 ListOfBuffers Buffer::getChildren() const
2684 collectChildren(v, false);
2685 // Make sure we have not included ourselves.
2686 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
2687 if (bit != v.end()) {
2688 LYXERR0("Recursive include detected in `" << fileName() << "'.");
2695 ListOfBuffers Buffer::getDescendents() const
2698 collectChildren(v, true);
2699 // Make sure we have not included ourselves.
2700 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
2701 if (bit != v.end()) {
2702 LYXERR0("Recursive include detected in `" << fileName() << "'.");
2709 template<typename M>
2710 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
2715 typename M::const_iterator it = m.lower_bound(x);
2716 if (it == m.begin())
2724 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
2725 DocIterator const & pos) const
2727 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2729 // if paragraphs have no macro context set, pos will be empty
2733 // we haven't found anything yet
2734 DocIterator bestPos = owner_->par_iterator_begin();
2735 MacroData const * bestData = 0;
2737 // find macro definitions for name
2738 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
2739 if (nameIt != macros.end()) {
2740 // find last definition in front of pos or at pos itself
2741 PositionScopeMacroMap::const_iterator it
2742 = greatest_below(nameIt->second, pos);
2743 if (it != nameIt->second.end()) {
2745 // scope ends behind pos?
2746 if (pos < it->second.first) {
2747 // Looks good, remember this. If there
2748 // is no external macro behind this,
2749 // we found the right one already.
2750 bestPos = it->first;
2751 bestData = &it->second.second;
2755 // try previous macro if there is one
2756 if (it == nameIt->second.begin())
2763 // find macros in included files
2764 PositionScopeBufferMap::const_iterator it
2765 = greatest_below(position_to_children, pos);
2766 if (it == position_to_children.end())
2767 // no children before
2771 // do we know something better (i.e. later) already?
2772 if (it->first < bestPos )
2775 // scope ends behind pos?
2776 if (pos < it->second.first
2777 && (cloned_buffer_ ||
2778 theBufferList().isLoaded(it->second.second))) {
2779 // look for macro in external file
2781 MacroData const * data
2782 = it->second.second->getMacro(name, false);
2785 bestPos = it->first;
2791 // try previous file if there is one
2792 if (it == position_to_children.begin())
2797 // return the best macro we have found
2802 MacroData const * Buffer::getMacro(docstring const & name,
2803 DocIterator const & pos, bool global) const
2808 // query buffer macros
2809 MacroData const * data = d->getBufferMacro(name, pos);
2813 // If there is a master buffer, query that
2814 Buffer const * const pbuf = d->parent();
2816 d->macro_lock = true;
2817 MacroData const * macro = pbuf->getMacro(
2818 name, *this, false);
2819 d->macro_lock = false;
2825 data = MacroTable::globalMacros().get(name);
2834 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2836 // set scope end behind the last paragraph
2837 DocIterator scope = par_iterator_begin();
2838 scope.pit() = scope.lastpit() + 1;
2840 return getMacro(name, scope, global);
2844 MacroData const * Buffer::getMacro(docstring const & name,
2845 Buffer const & child, bool global) const
2847 // look where the child buffer is included first
2848 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2849 if (it == d->children_positions.end())
2852 // check for macros at the inclusion position
2853 return getMacro(name, it->second, global);
2857 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
2859 pit_type const lastpit = it.lastpit();
2861 // look for macros in each paragraph
2862 while (it.pit() <= lastpit) {
2863 Paragraph & par = it.paragraph();
2865 // iterate over the insets of the current paragraph
2866 InsetList const & insets = par.insetList();
2867 InsetList::const_iterator iit = insets.begin();
2868 InsetList::const_iterator end = insets.end();
2869 for (; iit != end; ++iit) {
2870 it.pos() = iit->pos;
2872 // is it a nested text inset?
2873 if (iit->inset->asInsetText()) {
2874 // Inset needs its own scope?
2875 InsetText const * itext = iit->inset->asInsetText();
2876 bool newScope = itext->isMacroScope();
2878 // scope which ends just behind the inset
2879 DocIterator insetScope = it;
2882 // collect macros in inset
2883 it.push_back(CursorSlice(*iit->inset));
2884 updateMacros(it, newScope ? insetScope : scope);
2889 if (iit->inset->asInsetTabular()) {
2890 CursorSlice slice(*iit->inset);
2891 size_t const numcells = slice.nargs();
2892 for (; slice.idx() < numcells; slice.forwardIdx()) {
2893 it.push_back(slice);
2894 updateMacros(it, scope);
2900 // is it an external file?
2901 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2902 // get buffer of external file
2903 InsetInclude const & inset =
2904 static_cast<InsetInclude const &>(*iit->inset);
2906 Buffer * child = inset.getChildBuffer();
2911 // register its position, but only when it is
2912 // included first in the buffer
2913 if (children_positions.find(child) ==
2914 children_positions.end())
2915 children_positions[child] = it;
2917 // register child with its scope
2918 position_to_children[it] = Impl::ScopeBuffer(scope, child);
2922 InsetMath * im = iit->inset->asInsetMath();
2923 if (doing_export && im) {
2924 InsetMathHull * hull = im->asHullInset();
2926 hull->recordLocation(it);
2929 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2933 MathMacroTemplate & macroTemplate =
2934 *iit->inset->asInsetMath()->asMacroTemplate();
2935 MacroContext mc(owner_, it);
2936 macroTemplate.updateToContext(mc);
2939 bool valid = macroTemplate.validMacro();
2940 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2941 // then the BufferView's cursor will be invalid in
2942 // some cases which leads to crashes.
2947 // FIXME (Abdel), I don't understandt why we pass 'it' here
2948 // instead of 'macroTemplate' defined above... is this correct?
2949 macros[macroTemplate.name()][it] =
2950 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
2960 void Buffer::updateMacros() const
2965 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2967 // start with empty table
2969 d->children_positions.clear();
2970 d->position_to_children.clear();
2972 // Iterate over buffer, starting with first paragraph
2973 // The scope must be bigger than any lookup DocIterator
2974 // later. For the global lookup, lastpit+1 is used, hence
2975 // we use lastpit+2 here.
2976 DocIterator it = par_iterator_begin();
2977 DocIterator outerScope = it;
2978 outerScope.pit() = outerScope.lastpit() + 2;
2979 d->updateMacros(it, outerScope);
2983 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
2985 InsetIterator it = inset_iterator_begin(inset());
2986 InsetIterator const end = inset_iterator_end(inset());
2987 for (; it != end; ++it) {
2988 if (it->lyxCode() == BRANCH_CODE) {
2989 InsetBranch & br = static_cast<InsetBranch &>(*it);
2990 docstring const name = br.branch();
2991 if (!from_master && !params().branchlist().find(name))
2992 result.push_back(name);
2993 else if (from_master && !masterBuffer()->params().branchlist().find(name))
2994 result.push_back(name);
2997 if (it->lyxCode() == INCLUDE_CODE) {
2998 // get buffer of external file
2999 InsetInclude const & ins =
3000 static_cast<InsetInclude const &>(*it);
3001 Buffer * child = ins.getChildBuffer();
3004 child->getUsedBranches(result, true);
3007 // remove duplicates
3012 void Buffer::updateMacroInstances(UpdateType utype) const
3014 LYXERR(Debug::MACROS, "updateMacroInstances for "
3015 << d->filename.onlyFileName());
3016 DocIterator it = doc_iterator_begin(this);
3018 DocIterator const end = doc_iterator_end(this);
3019 for (; it != end; it.forwardInset()) {
3020 // look for MathData cells in InsetMathNest insets
3021 InsetMath * minset = it.nextInset()->asInsetMath();
3025 // update macro in all cells of the InsetMathNest
3026 DocIterator::idx_type n = minset->nargs();
3027 MacroContext mc = MacroContext(this, it);
3028 for (DocIterator::idx_type i = 0; i < n; ++i) {
3029 MathData & data = minset->cell(i);
3030 data.updateMacros(0, mc, utype);
3036 void Buffer::listMacroNames(MacroNameSet & macros) const
3041 d->macro_lock = true;
3043 // loop over macro names
3044 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3045 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3046 for (; nameIt != nameEnd; ++nameIt)
3047 macros.insert(nameIt->first);
3049 // loop over children
3050 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3051 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3052 for (; it != end; ++it)
3053 it->first->listMacroNames(macros);
3056 Buffer const * const pbuf = d->parent();
3058 pbuf->listMacroNames(macros);
3060 d->macro_lock = false;
3064 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3066 Buffer const * const pbuf = d->parent();
3071 pbuf->listMacroNames(names);
3074 MacroNameSet::iterator it = names.begin();
3075 MacroNameSet::iterator end = names.end();
3076 for (; it != end; ++it) {
3078 MacroData const * data =
3079 pbuf->getMacro(*it, *this, false);
3081 macros.insert(data);
3083 // we cannot access the original MathMacroTemplate anymore
3084 // here to calls validate method. So we do its work here manually.
3085 // FIXME: somehow make the template accessible here.
3086 if (data->optionals() > 0)
3087 features.require("xargs");
3093 Buffer::References & Buffer::references(docstring const & label)
3096 return const_cast<Buffer *>(masterBuffer())->references(label);
3098 RefCache::iterator it = d->ref_cache_.find(label);
3099 if (it != d->ref_cache_.end())
3100 return it->second.second;
3102 static InsetLabel const * dummy_il = 0;
3103 static References const dummy_refs;
3104 it = d->ref_cache_.insert(
3105 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3106 return it->second.second;
3110 Buffer::References const & Buffer::references(docstring const & label) const
3112 return const_cast<Buffer *>(this)->references(label);
3116 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3118 masterBuffer()->d->ref_cache_[label].first = il;
3122 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3124 return masterBuffer()->d->ref_cache_[label].first;
3128 void Buffer::clearReferenceCache() const
3131 d->ref_cache_.clear();
3135 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
3138 //FIXME: This does not work for child documents yet.
3139 LASSERT(code == CITE_CODE, /**/);
3141 reloadBibInfoCache();
3143 // Check if the label 'from' appears more than once
3144 BiblioInfo const & keys = masterBibInfo();
3145 BiblioInfo::const_iterator bit = keys.begin();
3146 BiblioInfo::const_iterator bend = keys.end();
3147 vector<docstring> labels;
3149 for (; bit != bend; ++bit)
3151 labels.push_back(bit->first);
3153 if (count(labels.begin(), labels.end(), from) > 1)
3156 string const paramName = "key";
3157 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3158 if (it->lyxCode() == code) {
3159 InsetCommand * inset = it->asInsetCommand();
3162 docstring const oldValue = inset->getParam(paramName);
3163 if (oldValue == from)
3164 inset->setParam(paramName, to);
3170 void Buffer::getSourceCode(odocstream & os, string const format,
3171 pit_type par_begin, pit_type par_end,
3172 bool full_source) const
3174 OutputParams runparams(¶ms().encoding());
3175 runparams.nice = true;
3176 runparams.flavor = params().getOutputFlavor(format);
3177 runparams.linelen = lyxrc.plaintext_linelen;
3178 // No side effect of file copying and image conversion
3179 runparams.dryrun = true;
3182 os << "% " << _("Preview source code") << "\n\n";
3184 d->texrow.newline();
3185 d->texrow.newline();
3186 if (params().isDocBook())
3187 writeDocBookSource(os, absFileName(), runparams, false);
3188 else if (runparams.flavor == OutputParams::HTML)
3189 writeLyXHTMLSource(os, runparams, false);
3191 // latex or literate
3192 otexstream ots(os, d->texrow);
3193 writeLaTeXSource(ots, string(), runparams, true, true);
3196 runparams.par_begin = par_begin;
3197 runparams.par_end = par_end;
3198 if (par_begin + 1 == par_end) {
3200 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3204 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3205 convert<docstring>(par_begin),
3206 convert<docstring>(par_end - 1))
3213 // output paragraphs
3214 if (params().isDocBook())
3215 docbookParagraphs(text(), *this, os, runparams);
3216 else if (runparams.flavor == OutputParams::HTML) {
3218 xhtmlParagraphs(text(), *this, xs, runparams);
3220 // latex or literate
3221 otexstream ots(os, texrow);
3222 latexParagraphs(*this, text(), ots, runparams);
3228 ErrorList & Buffer::errorList(string const & type) const
3230 return d->errorLists[type];
3234 void Buffer::updateTocItem(std::string const & type,
3235 DocIterator const & dit) const
3238 d->gui_->updateTocItem(type, dit);
3242 void Buffer::structureChanged() const
3245 d->gui_->structureChanged();
3249 void Buffer::errors(string const & err, bool from_master) const
3252 d->gui_->errors(err, from_master);
3256 void Buffer::message(docstring const & msg) const
3259 d->gui_->message(msg);
3263 void Buffer::setBusy(bool on) const
3266 d->gui_->setBusy(on);
3270 void Buffer::updateTitles() const
3273 d->wa_->updateTitles();
3277 void Buffer::resetAutosaveTimers() const
3280 d->gui_->resetAutosaveTimers();
3284 bool Buffer::hasGuiDelegate() const
3290 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3299 class AutoSaveBuffer : public ForkedProcess {
3302 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3303 : buffer_(buffer), fname_(fname) {}
3305 virtual shared_ptr<ForkedProcess> clone() const
3307 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3312 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3313 from_utf8(fname_.absFileName())));
3314 return run(DontWait);
3318 virtual int generateChild();
3320 Buffer const & buffer_;
3325 int AutoSaveBuffer::generateChild()
3327 #if defined(__APPLE__)
3328 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3329 * We should use something else like threads.
3331 * Since I do not know how to determine at run time what is the OS X
3332 * version, I just disable forking altogether for now (JMarc)
3334 pid_t const pid = -1;
3336 // tmp_ret will be located (usually) in /tmp
3337 // will that be a problem?
3338 // Note that this calls ForkedCalls::fork(), so it's
3339 // ok cross-platform.
3340 pid_t const pid = fork();
3341 // If you want to debug the autosave
3342 // you should set pid to -1, and comment out the fork.
3343 if (pid != 0 && pid != -1)
3347 // pid = -1 signifies that lyx was unable
3348 // to fork. But we will do the save
3350 bool failed = false;
3351 FileName const tmp_ret = FileName::tempName("lyxauto");
3352 if (!tmp_ret.empty()) {
3353 buffer_.writeFile(tmp_ret);
3354 // assume successful write of tmp_ret
3355 if (!tmp_ret.moveTo(fname_))
3361 // failed to write/rename tmp_ret so try writing direct
3362 if (!buffer_.writeFile(fname_)) {
3363 // It is dangerous to do this in the child,
3364 // but safe in the parent, so...
3365 if (pid == -1) // emit message signal.
3366 buffer_.message(_("Autosave failed!"));
3370 if (pid == 0) // we are the child so...
3379 FileName Buffer::getEmergencyFileName() const
3381 return FileName(d->filename.absFileName() + ".emergency");
3385 FileName Buffer::getAutosaveFileName() const
3387 // if the document is unnamed try to save in the backup dir, else
3388 // in the default document path, and as a last try in the filePath,
3389 // which will most often be the temporary directory
3392 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3393 : lyxrc.backupdir_path;
3394 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3397 string const fname = "#" + d->filename.onlyFileName() + "#";
3399 return makeAbsPath(fname, fpath);
3403 void Buffer::removeAutosaveFile() const
3405 FileName const f = getAutosaveFileName();
3411 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3413 FileName const newauto = getAutosaveFileName();
3415 if (newauto != oldauto && oldauto.exists())
3416 if (!oldauto.moveTo(newauto))
3417 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3421 bool Buffer::autoSave() const
3423 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
3424 if (buf->d->bak_clean || isReadonly())
3427 message(_("Autosaving current document..."));
3428 buf->d->bak_clean = true;
3430 FileName const fname = getAutosaveFileName();
3431 if (d->cloned_buffer_) {
3432 // If this buffer is cloned, we assume that
3433 // we are running in a separate thread already.
3434 FileName const tmp_ret = FileName::tempName("lyxauto");
3435 if (!tmp_ret.empty()) {
3437 // assume successful write of tmp_ret
3438 if (tmp_ret.moveTo(fname))
3441 // failed to write/rename tmp_ret so try writing direct
3442 return writeFile(fname);
3444 /// This function is deprecated as the frontend needs to take care
3445 /// of cloning the buffer and autosaving it in another thread. It
3446 /// is still here to allow (QT_VERSION < 0x040400).
3447 AutoSaveBuffer autosave(*this, fname);
3455 // helper class, to guarantee this gets reset properly
3456 class MarkAsExporting {
3458 MarkAsExporting(Buffer const * buf) : buf_(buf)
3460 LASSERT(buf_, /* */);
3461 buf_->setExportStatus(true);
3465 buf_->setExportStatus(false);
3468 Buffer const * const buf_;
3473 void Buffer::setExportStatus(bool e) const
3475 d->doing_export = e;
3476 ListOfBuffers clist = getDescendents();
3477 ListOfBuffers::const_iterator cit = clist.begin();
3478 ListOfBuffers::const_iterator const cen = clist.end();
3479 for (; cit != cen; ++cit)
3480 (*cit)->d->doing_export = e;
3484 bool Buffer::isExporting() const
3486 return d->doing_export;
3490 bool Buffer::doExport(string const & target, bool put_in_tempdir,
3491 bool includeall, string & result_file) const
3493 LYXERR(Debug::FILES, "target=" << target << ", result_file=" << result_file);
3494 OutputParams runparams(¶ms().encoding());
3495 string format = target;
3496 string dest_filename;
3497 size_t pos = target.find(' ');
3498 if (pos != string::npos) {
3499 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
3500 format = target.substr(0, pos);
3501 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
3502 FileName(dest_filename).onlyPath().createPath();
3503 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
3505 MarkAsExporting exporting(this);
3506 string backend_format;
3507 runparams.flavor = OutputParams::LATEX;
3508 runparams.linelen = lyxrc.plaintext_linelen;
3509 runparams.includeall = includeall;
3510 vector<string> backs = params().backends();
3511 Converters converters = theConverters();
3512 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3513 // Get shortest path to format
3514 converters.buildGraph();
3515 Graph::EdgePath path;
3516 for (vector<string>::const_iterator it = backs.begin();
3517 it != backs.end(); ++it) {
3518 Graph::EdgePath p = converters.getPath(*it, format);
3519 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3520 backend_format = *it;
3525 if (!put_in_tempdir) {
3526 // Only show this alert if this is an export to a non-temporary
3527 // file (not for previewing).
3528 Alert::error(_("Couldn't export file"), bformat(
3529 _("No information for exporting the format %1$s."),
3530 formats.prettyName(format)));
3534 runparams.flavor = converters.getFlavor(path);
3537 backend_format = format;
3538 LYXERR(Debug::FILES, "backend_format=" << backend_format);
3539 // FIXME: Don't hardcode format names here, but use a flag
3540 if (backend_format == "pdflatex")
3541 runparams.flavor = OutputParams::PDFLATEX;
3542 else if (backend_format == "luatex")
3543 runparams.flavor = OutputParams::LUATEX;
3544 else if (backend_format == "dviluatex")
3545 runparams.flavor = OutputParams::DVILUATEX;
3546 else if (backend_format == "xetex")
3547 runparams.flavor = OutputParams::XETEX;
3550 string filename = latexName(false);
3551 filename = addName(temppath(), filename);
3552 filename = changeExtension(filename,
3553 formats.extension(backend_format));
3554 LYXERR(Debug::FILES, "filename=" << filename);
3556 // Plain text backend
3557 if (backend_format == "text") {
3558 runparams.flavor = OutputParams::TEXT;
3559 writePlaintextFile(*this, FileName(filename), runparams);
3562 else if (backend_format == "xhtml") {
3563 runparams.flavor = OutputParams::HTML;
3564 switch (params().html_math_output) {
3565 case BufferParams::MathML:
3566 runparams.math_flavor = OutputParams::MathAsMathML;
3568 case BufferParams::HTML:
3569 runparams.math_flavor = OutputParams::MathAsHTML;
3571 case BufferParams::Images:
3572 runparams.math_flavor = OutputParams::MathAsImages;
3574 case BufferParams::LaTeX:
3575 runparams.math_flavor = OutputParams::MathAsLaTeX;
3578 makeLyXHTMLFile(FileName(filename), runparams);
3579 } else if (backend_format == "lyx")
3580 writeFile(FileName(filename));
3582 else if (params().isDocBook()) {
3583 runparams.nice = !put_in_tempdir;
3584 makeDocBookFile(FileName(filename), runparams);
3587 else if (backend_format == format) {
3588 runparams.nice = true;
3589 if (!makeLaTeXFile(FileName(filename), string(), runparams)) {
3590 if (d->cloned_buffer_) {
3591 d->cloned_buffer_->d->errorLists["Export"] =
3592 d->errorLists["Export"];
3596 } else if (!lyxrc.tex_allows_spaces
3597 && contains(filePath(), ' ')) {
3598 Alert::error(_("File name error"),
3599 _("The directory path to the document cannot contain spaces."));
3602 runparams.nice = false;
3603 if (!makeLaTeXFile(FileName(filename), filePath(), runparams)) {
3604 if (d->cloned_buffer_) {
3605 d->cloned_buffer_->d->errorLists["Export"] =
3606 d->errorLists["Export"];
3612 string const error_type = (format == "program")
3613 ? "Build" : params().bufferFormat();
3614 ErrorList & error_list = d->errorLists[error_type];
3615 string const ext = formats.extension(format);
3616 FileName const tmp_result_file(changeExtension(filename, ext));
3617 bool const success = converters.convert(this, FileName(filename),
3618 tmp_result_file, FileName(absFileName()), backend_format, format,
3621 // Emit the signal to show the error list or copy it back to the
3622 // cloned Buffer so that it can be emitted afterwards.
3623 if (format != backend_format) {
3624 if (d->cloned_buffer_) {
3625 d->cloned_buffer_->d->errorLists[error_type] =
3626 d->errorLists[error_type];
3629 // also to the children, in case of master-buffer-view
3630 ListOfBuffers clist = getDescendents();
3631 ListOfBuffers::const_iterator cit = clist.begin();
3632 ListOfBuffers::const_iterator const cen = clist.end();
3633 for (; cit != cen; ++cit) {
3634 if (d->cloned_buffer_) {
3635 // Enable reverse search by copying back the
3636 // texrow object to the cloned buffer.
3637 // FIXME: this is not thread safe.
3638 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
3639 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
3640 (*cit)->d->errorLists[error_type];
3642 (*cit)->errors(error_type, true);
3646 if (d->cloned_buffer_) {
3647 // Enable reverse dvi or pdf to work by copying back the texrow
3648 // object to the cloned buffer.
3649 // FIXME: There is a possibility of concurrent access to texrow
3650 // here from the main GUI thread that should be securized.
3651 d->cloned_buffer_->d->texrow = d->texrow;
3652 string const error_type = params().bufferFormat();
3653 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
3659 if (put_in_tempdir) {
3660 result_file = tmp_result_file.absFileName();
3664 if (dest_filename.empty())
3665 result_file = changeExtension(d->exportFileName().absFileName(), ext);
3667 result_file = dest_filename;
3668 // We need to copy referenced files (e. g. included graphics
3669 // if format == "dvi") to the result dir.
3670 vector<ExportedFile> const files =
3671 runparams.exportdata->externalFiles(format);
3672 string const dest = runparams.export_folder.empty() ?
3673 onlyPath(result_file) : runparams.export_folder;
3674 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
3675 : force_overwrite == ALL_FILES;
3676 CopyStatus status = use_force ? FORCE : SUCCESS;
3678 vector<ExportedFile>::const_iterator it = files.begin();
3679 vector<ExportedFile>::const_iterator const en = files.end();
3680 for (; it != en && status != CANCEL; ++it) {
3681 string const fmt = formats.getFormatFromFile(it->sourceName);
3682 string fixedName = it->exportName;
3683 if (!runparams.export_folder.empty()) {
3684 // Relative pathnames starting with ../ will be sanitized
3685 // if exporting to a different folder
3686 while (fixedName.substr(0, 3) == "../")
3687 fixedName = fixedName.substr(3, fixedName.length() - 3);
3689 FileName fixedFileName = makeAbsPath(fixedName, dest);
3690 fixedFileName.onlyPath().createPath();
3691 status = copyFile(fmt, it->sourceName,
3693 it->exportName, status == FORCE,
3694 runparams.export_folder.empty());
3697 if (status == CANCEL) {
3698 message(_("Document export cancelled."));
3699 } else if (tmp_result_file.exists()) {
3700 // Finally copy the main file
3701 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
3702 : force_overwrite != NO_FILES;
3703 if (status == SUCCESS && use_force)
3705 status = copyFile(format, tmp_result_file,
3706 FileName(result_file), result_file,
3708 message(bformat(_("Document exported as %1$s "
3710 formats.prettyName(format),
3711 makeDisplayPath(result_file)));
3713 // This must be a dummy converter like fax (bug 1888)
3714 message(bformat(_("Document exported as %1$s"),
3715 formats.prettyName(format)));
3722 bool Buffer::doExport(string const & target, bool put_in_tempdir,
3723 bool includeall) const
3726 // (1) export with all included children (omit \includeonly)
3727 if (includeall && !doExport(target, put_in_tempdir, true, result_file))
3729 // (2) export with included children only
3730 return doExport(target, put_in_tempdir, false, result_file);
3734 bool Buffer::preview(string const & format, bool includeall) const
3736 MarkAsExporting exporting(this);
3738 // (1) export with all included children (omit \includeonly)
3739 if (includeall && !doExport(format, true, true))
3741 // (2) export with included children only
3742 if (!doExport(format, true, false, result_file))
3744 return formats.view(*this, FileName(result_file), format);
3748 Buffer::ReadStatus Buffer::extractFromVC()
3750 bool const found = LyXVC::file_not_found_hook(d->filename);
3752 return ReadFileNotFound;
3753 if (!d->filename.isReadableFile())
3759 Buffer::ReadStatus Buffer::loadEmergency()
3761 FileName const emergencyFile = getEmergencyFileName();
3762 if (!emergencyFile.exists()
3763 || emergencyFile.lastModified() <= d->filename.lastModified())
3764 return ReadFileNotFound;
3766 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
3767 docstring const text = bformat(_("An emergency save of the document "
3768 "%1$s exists.\n\nRecover emergency save?"), file);
3770 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
3771 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
3777 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
3778 bool const success = (ret_llf == ReadSuccess);
3781 Alert::warning(_("File is read-only"),
3782 bformat(_("An emergency file is successfully loaded, "
3783 "but the original file %1$s is marked read-only. "
3784 "Please make sure to save the document as a different "
3785 "file."), from_utf8(d->filename.absFileName())));
3788 str = _("Document was successfully recovered.");
3790 str = _("Document was NOT successfully recovered.");
3791 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3792 makeDisplayPath(emergencyFile.absFileName()));
3794 int const del_emerg =
3795 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3796 _("&Remove"), _("&Keep"));
3797 if (del_emerg == 0) {
3798 emergencyFile.removeFile();
3800 Alert::warning(_("Emergency file deleted"),
3801 _("Do not forget to save your file now!"), true);
3803 return success ? ReadSuccess : ReadEmergencyFailure;
3806 int const del_emerg =
3807 Alert::prompt(_("Delete emergency file?"),
3808 _("Remove emergency file now?"), 1, 1,
3809 _("&Remove"), _("&Keep"));
3811 emergencyFile.removeFile();
3812 return ReadOriginal;
3822 Buffer::ReadStatus Buffer::loadAutosave()
3824 // Now check if autosave file is newer.
3825 FileName const autosaveFile = getAutosaveFileName();
3826 if (!autosaveFile.exists()
3827 || autosaveFile.lastModified() <= d->filename.lastModified())
3828 return ReadFileNotFound;
3830 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
3831 docstring const text = bformat(_("The backup of the document %1$s "
3832 "is newer.\n\nLoad the backup instead?"), file);
3833 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
3834 _("&Load backup"), _("Load &original"), _("&Cancel"));
3839 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
3840 // the file is not saved if we load the autosave file.
3841 if (ret_llf == ReadSuccess) {
3843 Alert::warning(_("File is read-only"),
3844 bformat(_("A backup file is successfully loaded, "
3845 "but the original file %1$s is marked read-only. "
3846 "Please make sure to save the document as a "
3848 from_utf8(d->filename.absFileName())));
3853 return ReadAutosaveFailure;
3856 // Here we delete the autosave
3857 autosaveFile.removeFile();
3858 return ReadOriginal;
3866 Buffer::ReadStatus Buffer::loadLyXFile()
3868 if (!d->filename.isReadableFile()) {
3869 ReadStatus const ret_rvc = extractFromVC();
3870 if (ret_rvc != ReadSuccess)
3874 ReadStatus const ret_re = loadEmergency();
3875 if (ret_re == ReadSuccess || ret_re == ReadCancel)
3878 ReadStatus const ret_ra = loadAutosave();
3879 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
3882 return loadThisLyXFile(d->filename);
3886 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
3888 return readFile(fn);
3892 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3894 TeXErrors::Errors::const_iterator it = terr.begin();
3895 TeXErrors::Errors::const_iterator end = terr.end();
3896 ListOfBuffers clist = getDescendents();
3897 ListOfBuffers::const_iterator cen = clist.end();
3899 for (; it != end; ++it) {
3902 int errorRow = it->error_in_line;
3903 Buffer const * buf = 0;
3905 if (it->child_name.empty())
3906 p->texrow.getIdFromRow(errorRow, id_start, pos_start);
3908 // The error occurred in a child
3909 ListOfBuffers::const_iterator cit = clist.begin();
3910 for (; cit != cen; ++cit) {
3911 string const child_name =
3912 DocFileName(changeExtension(
3913 (*cit)->absFileName(), "tex")).
3915 if (it->child_name != child_name)
3917 (*cit)->d->texrow.getIdFromRow(errorRow,
3918 id_start, pos_start);
3919 if (id_start != -1) {
3920 buf = d->cloned_buffer_
3921 ? (*cit)->d->cloned_buffer_->d->owner_
3922 : (*cit)->d->owner_;
3933 found = p->texrow.getIdFromRow(errorRow, id_end, pos_end);
3934 } while (found && id_start == id_end && pos_start == pos_end);
3936 if (id_start != id_end) {
3937 // Next registered position is outside the inset where
3938 // the error occurred, so signal end-of-paragraph
3942 errorList.push_back(ErrorItem(it->error_desc,
3943 it->error_text, id_start, pos_start, pos_end, buf));
3948 void Buffer::setBuffersForInsets() const
3950 inset().setBuffer(const_cast<Buffer &>(*this));
3954 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
3956 // Use the master text class also for child documents
3957 Buffer const * const master = masterBuffer();
3958 DocumentClass const & textclass = master->params().documentClass();
3960 // do this only if we are the top-level Buffer
3962 reloadBibInfoCache();
3964 // keep the buffers to be children in this set. If the call from the
3965 // master comes back we can see which of them were actually seen (i.e.
3966 // via an InsetInclude). The remaining ones in the set need still be updated.
3967 static std::set<Buffer const *> bufToUpdate;
3968 if (scope == UpdateMaster) {
3969 // If this is a child document start with the master
3970 if (master != this) {
3971 bufToUpdate.insert(this);
3972 master->updateBuffer(UpdateMaster, utype);
3973 // Do this here in case the master has no gui associated with it. Then,
3974 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3975 if (!master->d->gui_)
3978 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3979 if (bufToUpdate.find(this) == bufToUpdate.end())
3983 // start over the counters in the master
3984 textclass.counters().reset();
3987 // update will be done below for this buffer
3988 bufToUpdate.erase(this);
3990 // update all caches
3991 clearReferenceCache();
3994 Buffer & cbuf = const_cast<Buffer &>(*this);
3996 LASSERT(!text().paragraphs().empty(), /**/);
3999 ParIterator parit = cbuf.par_iterator_begin();
4000 updateBuffer(parit, utype);
4003 // TocBackend update will be done later.
4006 d->bibinfo_cache_valid_ = true;
4007 d->cite_labels_valid_ = true;
4008 cbuf.tocBackend().update();
4009 if (scope == UpdateMaster)
4010 cbuf.structureChanged();
4014 static depth_type getDepth(DocIterator const & it)
4016 depth_type depth = 0;
4017 for (size_t i = 0 ; i < it.depth() ; ++i)
4018 if (!it[i].inset().inMathed())
4019 depth += it[i].paragraph().getDepth() + 1;
4020 // remove 1 since the outer inset does not count
4024 static depth_type getItemDepth(ParIterator const & it)
4026 Paragraph const & par = *it;
4027 LabelType const labeltype = par.layout().labeltype;
4029 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4032 // this will hold the lowest depth encountered up to now.
4033 depth_type min_depth = getDepth(it);
4034 ParIterator prev_it = it;
4037 --prev_it.top().pit();
4039 // start of nested inset: go to outer par
4041 if (prev_it.empty()) {
4042 // start of document: nothing to do
4047 // We search for the first paragraph with same label
4048 // that is not more deeply nested.
4049 Paragraph & prev_par = *prev_it;
4050 depth_type const prev_depth = getDepth(prev_it);
4051 if (labeltype == prev_par.layout().labeltype) {
4052 if (prev_depth < min_depth)
4053 return prev_par.itemdepth + 1;
4054 if (prev_depth == min_depth)
4055 return prev_par.itemdepth;
4057 min_depth = min(min_depth, prev_depth);
4058 // small optimization: if we are at depth 0, we won't
4059 // find anything else
4060 if (prev_depth == 0)
4066 static bool needEnumCounterReset(ParIterator const & it)
4068 Paragraph const & par = *it;
4069 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
4070 depth_type const cur_depth = par.getDepth();
4071 ParIterator prev_it = it;
4072 while (prev_it.pit()) {
4073 --prev_it.top().pit();
4074 Paragraph const & prev_par = *prev_it;
4075 if (prev_par.getDepth() <= cur_depth)
4076 return prev_par.layout().labeltype != LABEL_ENUMERATE;
4078 // start of nested inset: reset
4083 // set the label of a paragraph. This includes the counters.
4084 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4086 BufferParams const & bp = owner_->masterBuffer()->params();
4087 DocumentClass const & textclass = bp.documentClass();
4088 Paragraph & par = it.paragraph();
4089 Layout const & layout = par.layout();
4090 Counters & counters = textclass.counters();
4092 if (par.params().startOfAppendix()) {
4093 // FIXME: only the counter corresponding to toplevel
4094 // sectioning should be reset
4096 counters.appendix(true);
4098 par.params().appendix(counters.appendix());
4100 // Compute the item depth of the paragraph
4101 par.itemdepth = getItemDepth(it);
4103 if (layout.margintype == MARGIN_MANUAL) {
4104 if (par.params().labelWidthString().empty())
4105 par.params().labelWidthString(par.expandLabel(layout, bp));
4106 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4107 // we do not need to do anything here, since the empty case is
4108 // handled during export.
4110 par.params().labelWidthString(docstring());
4113 switch(layout.labeltype) {
4115 if (layout.toclevel <= bp.secnumdepth
4116 && (layout.latextype != LATEX_ENVIRONMENT
4117 || it.text()->isFirstInSequence(it.pit()))) {
4118 if (counters.hasCounter(layout.counter))
4119 counters.step(layout.counter, utype);
4120 par.params().labelString(par.expandLabel(layout, bp));
4122 par.params().labelString(docstring());
4125 case LABEL_ITEMIZE: {
4126 // At some point of time we should do something more
4127 // clever here, like:
4128 // par.params().labelString(
4129 // bp.user_defined_bullet(par.itemdepth).getText());
4130 // for now, use a simple hardcoded label
4131 docstring itemlabel;
4132 switch (par.itemdepth) {
4134 itemlabel = char_type(0x2022);
4137 itemlabel = char_type(0x2013);
4140 itemlabel = char_type(0x2217);
4143 itemlabel = char_type(0x2219); // or 0x00b7
4146 par.params().labelString(itemlabel);
4150 case LABEL_ENUMERATE: {
4151 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4153 switch (par.itemdepth) {
4162 enumcounter += "iv";
4165 // not a valid enumdepth...
4169 // Maybe we have to reset the enumeration counter.
4170 if (needEnumCounterReset(it))
4171 counters.reset(enumcounter);
4172 counters.step(enumcounter, utype);
4174 string const & lang = par.getParLanguage(bp)->code();
4175 par.params().labelString(counters.theCounter(enumcounter, lang));
4180 case LABEL_SENSITIVE: {
4181 string const & type = counters.current_float();
4182 docstring full_label;
4184 full_label = owner_->B_("Senseless!!! ");
4186 docstring name = owner_->B_(textclass.floats().getType(type).name());
4187 if (counters.hasCounter(from_utf8(type))) {
4188 string const & lang = par.getParLanguage(bp)->code();
4189 counters.step(from_utf8(type), utype);
4190 full_label = bformat(from_ascii("%1$s %2$s:"),
4192 counters.theCounter(from_utf8(type), lang));
4194 full_label = bformat(from_ascii("%1$s #:"), name);
4196 par.params().labelString(full_label);
4200 case LABEL_NO_LABEL:
4201 par.params().labelString(docstring());
4205 case LABEL_TOP_ENVIRONMENT:
4206 case LABEL_CENTERED_TOP_ENVIRONMENT:
4209 par.params().labelString(par.expandLabel(layout, bp));
4215 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4217 LASSERT(parit.pit() == 0, /**/);
4219 // Set the position of the text in the buffer to be able
4220 // to resolve macros in it.
4221 parit.text()->setMacrocontextPosition(parit);
4223 depth_type maxdepth = 0;
4224 pit_type const lastpit = parit.lastpit();
4225 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4226 // reduce depth if necessary
4227 parit->params().depth(min(parit->params().depth(), maxdepth));
4228 maxdepth = parit->getMaxDepthAfter();
4230 if (utype == OutputUpdate) {
4231 // track the active counters
4232 // we have to do this for the master buffer, since the local
4233 // buffer isn't tracking anything.
4234 masterBuffer()->params().documentClass().counters().
4235 setActiveLayout(parit->layout());
4238 // set the counter for this paragraph
4239 d->setLabel(parit, utype);
4242 InsetList::const_iterator iit = parit->insetList().begin();
4243 InsetList::const_iterator end = parit->insetList().end();
4244 for (; iit != end; ++iit) {
4245 parit.pos() = iit->pos;
4246 iit->inset->updateBuffer(parit, utype);
4252 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4253 WordLangTuple & word_lang, docstring_list & suggestions) const
4257 suggestions.clear();
4258 word_lang = WordLangTuple();
4259 bool const to_end = to.empty();
4260 DocIterator const end = to_end ? doc_iterator_end(this) : to;
4261 // OK, we start from here.
4262 for (; from != end; from.forwardPos()) {
4263 // We are only interested in text so remove the math CursorSlice.
4264 while (from.inMathed()) {
4268 // If from is at the end of the document (which is possible
4269 // when leaving the mathed) LyX will crash later otherwise.
4270 if (from.atEnd() || (!to_end && from >= end))
4273 from.paragraph().spellCheck();
4274 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4275 if (SpellChecker::misspelled(res)) {
4280 // Do not increase progress when from == to, otherwise the word
4281 // count will be wrong.
4291 Buffer::ReadStatus Buffer::reload()
4294 // c.f. bug http://www.lyx.org/trac/ticket/6587
4295 removeAutosaveFile();
4296 // e.g., read-only status could have changed due to version control
4297 d->filename.refresh();
4298 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4300 ReadStatus const status = loadLyXFile();
4301 if (status == ReadSuccess) {
4306 message(bformat(_("Document %1$s reloaded."), disp_fn));
4309 message(bformat(_("Could not reload document %1$s."), disp_fn));
4319 bool Buffer::saveAs(FileName const & fn)
4321 FileName const old_name = fileName();
4322 FileName const old_auto = getAutosaveFileName();
4323 bool const old_unnamed = isUnnamed();
4330 // bring the autosave file with us, just in case.
4331 moveAutosaveFile(old_auto);
4332 // validate version control data and
4333 // correct buffer title
4334 lyxvc().file_found_hook(fileName());
4336 // the file has now been saved to the new location.
4337 // we need to check that the locations of child buffers
4339 checkChildBuffers();
4343 // reset the old filename and unnamed state
4344 setFileName(old_name);
4345 setUnnamed(old_unnamed);
4351 // FIXME We could do better here, but it is complicated. What would be
4352 // nice is to offer either (a) to save the child buffer to an appropriate
4353 // location, so that it would "move with the master", or else (b) to update
4354 // the InsetInclude so that it pointed to the same file. But (a) is a bit
4355 // complicated, because the code for this lives in GuiView.
4356 void Buffer::checkChildBuffers()
4358 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4359 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4360 for (; it != en; ++it) {
4361 DocIterator dit = it->second;
4362 Buffer * cbuf = const_cast<Buffer *>(it->first);
4363 if (!cbuf || !theBufferList().isLoaded(cbuf))
4365 Inset * inset = dit.nextInset();
4366 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4367 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4368 docstring const & incfile = inset_inc->getParam("filename");
4369 string oldloc = cbuf->absFileName();
4370 string newloc = makeAbsPath(to_utf8(incfile),
4371 onlyPath(absFileName())).absFileName();
4372 if (oldloc == newloc)
4374 // the location of the child file is incorrect.
4375 Alert::warning(_("Included File Invalid"),
4376 bformat(_("Saving this document to a new location has made the file:\n"
4378 "inaccessible. You will need to update the included filename."),
4379 from_utf8(oldloc)));
4381 inset_inc->setChildBuffer(0);
4383 // invalidate cache of children
4384 d->children_positions.clear();
4385 d->position_to_children.clear();