3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
7 * \author Stefan Schimanski
9 * Full author contact details are available in file CREDITS.
17 #include "LayoutFile.h"
18 #include "BiblioInfo.h"
19 #include "BranchList.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
25 #include "Converter.h"
27 #include "DispatchResult.h"
28 #include "DocIterator.h"
30 #include "ErrorList.h"
33 #include "FuncRequest.h"
34 #include "FuncStatus.h"
35 #include "IndicesList.h"
36 #include "InsetIterator.h"
37 #include "InsetList.h"
39 #include "LaTeXFeatures.h"
43 #include "LyXAction.h"
47 #include "output_docbook.h"
49 #include "output_latex.h"
50 #include "output_xhtml.h"
51 #include "output_plaintext.h"
52 #include "Paragraph.h"
53 #include "ParagraphParameters.h"
54 #include "ParIterator.h"
55 #include "PDFOptions.h"
56 #include "SpellChecker.h"
59 #include "TexStream.h"
61 #include "TextClass.h"
62 #include "TocBackend.h"
64 #include "VCBackend.h"
66 #include "WordLangTuple.h"
69 #include "insets/InsetBibtex.h"
70 #include "insets/InsetBranch.h"
71 #include "insets/InsetInclude.h"
72 #include "insets/InsetTabular.h"
73 #include "insets/InsetText.h"
75 #include "mathed/InsetMathHull.h"
76 #include "mathed/MacroTable.h"
77 #include "mathed/MathMacroTemplate.h"
78 #include "mathed/MathSupport.h"
80 #include "graphics/PreviewLoader.h"
82 #include "frontends/alert.h"
83 #include "frontends/Delegates.h"
84 #include "frontends/WorkAreaManager.h"
86 #include "support/lassert.h"
87 #include "support/convert.h"
88 #include "support/debug.h"
89 #include "support/docstring_list.h"
90 #include "support/ExceptionMessage.h"
91 #include "support/FileName.h"
92 #include "support/FileNameList.h"
93 #include "support/filetools.h"
94 #include "support/ForkedCalls.h"
95 #include "support/gettext.h"
96 #include "support/gzstream.h"
97 #include "support/lstrings.h"
98 #include "support/lyxalgo.h"
99 #include "support/os.h"
100 #include "support/Package.h"
101 #include "support/Path.h"
102 #include "support/Systemcall.h"
103 #include "support/textutils.h"
104 #include "support/types.h"
106 #include "support/bind.h"
107 #include "support/shared_ptr.h"
119 using namespace lyx::support;
120 using namespace lyx::graphics;
124 namespace Alert = frontend::Alert;
125 namespace os = support::os;
129 int const LYX_FORMAT = LYX_FORMAT_LYX;
131 typedef map<string, bool> DepClean;
132 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
134 void showPrintError(string const & name)
136 docstring str = bformat(_("Could not print the document %1$s.\n"
137 "Check that your printer is set up correctly."),
138 makeDisplayPath(name, 50));
139 Alert::error(_("Print document failed"), str);
142 /// a list of Buffers we cloned
143 set<Buffer *> cloned_buffer_list;
152 Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
156 delete preview_loader_;
164 /// search for macro in local (buffer) table or in children
165 MacroData const * getBufferMacro(docstring const & name,
166 DocIterator const & pos) const;
168 /// Update macro table starting with position of it \param it in some
170 void updateMacros(DocIterator & it, DocIterator & scope);
172 void setLabel(ParIterator & it, UpdateType utype) const;
174 /** If we have branches that use the file suffix
175 feature, return the file name with suffix appended.
177 support::FileName exportFileName() const;
184 mutable TexRow texrow;
186 /// need to regenerate .tex?
190 mutable bool lyx_clean;
192 /// is autosave needed?
193 mutable bool bak_clean;
195 /// is this an unnamed file (New...)?
201 /// name of the file the buffer is associated with.
204 /** Set to true only when the file is fully loaded.
205 * Used to prevent the premature generation of previews
206 * and by the citation inset.
208 bool file_fully_loaded;
211 mutable TocBackend toc_backend;
214 typedef pair<DocIterator, MacroData> ScopeMacro;
215 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
216 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
217 /// map from the macro name to the position map,
218 /// which maps the macro definition position to the scope and the MacroData.
219 NamePositionScopeMacroMap macros;
220 /// This seem to change the way Buffer::getMacro() works
221 mutable bool macro_lock;
223 /// positions of child buffers in the buffer
224 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
225 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
226 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
227 /// position of children buffers in this buffer
228 BufferPositionMap children_positions;
229 /// map from children inclusion positions to their scope and their buffer
230 PositionScopeBufferMap position_to_children;
232 /// Container for all sort of Buffer dependant errors.
233 map<string, ErrorList> errorLists;
235 /// timestamp and checksum used to test if the file has been externally
236 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
238 unsigned long checksum_;
241 frontend::WorkAreaManager * wa_;
243 frontend::GuiBufferDelegate * gui_;
248 /// A cache for the bibfiles (including bibfiles of loaded child
249 /// documents), needed for appropriate update of natbib labels.
250 mutable support::FileNameList bibfiles_cache_;
252 // FIXME The caching mechanism could be improved. At present, we have a
253 // cache for each Buffer, that caches all the bibliography info for that
254 // Buffer. A more efficient solution would be to have a global cache per
255 // file, and then to construct the Buffer's bibinfo from that.
256 /// A cache for bibliography info
257 mutable BiblioInfo bibinfo_;
258 /// whether the bibinfo cache is valid
259 mutable bool bibinfo_cache_valid_;
260 /// whether the bibfile cache is valid
261 mutable bool bibfile_cache_valid_;
262 /// Cache of timestamps of .bib files
263 map<FileName, time_t> bibfile_status_;
264 /// Indicates whether the bibinfo has changed since the last time
265 /// we ran updateBuffer(), i.e., whether citation labels may need
267 mutable bool cite_labels_valid_;
269 mutable RefCache ref_cache_;
271 /// our Text that should be wrapped in an InsetText
275 PreviewLoader * preview_loader_;
277 /// This is here to force the test to be done whenever parent_buffer
279 Buffer const * parent() const {
280 // if parent_buffer is not loaded, then it has been unloaded,
281 // which means that parent_buffer is an invalid pointer. So we
282 // set it to null in that case.
283 // however, the BufferList doesn't know about cloned buffers, so
284 // they will always be regarded as unloaded. in that case, we hope
286 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
288 return parent_buffer;
292 void setParent(Buffer const * pb) {
293 if (parent_buffer == pb)
296 if (!cloned_buffer_ && parent_buffer && pb)
297 LYXERR0("Warning: a buffer should not have two parents!");
299 if (!cloned_buffer_ && parent_buffer) {
300 parent_buffer->invalidateBibfileCache();
301 parent_buffer->invalidateBibinfoCache();
305 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
306 /// This one is useful for preview detached in a thread.
307 Buffer const * cloned_buffer_;
308 /// are we in the process of exporting this buffer?
309 mutable bool doing_export;
312 /// So we can force access via the accessors.
313 mutable Buffer const * parent_buffer;
318 /// Creates the per buffer temporary directory
319 static FileName createBufferTmpDir()
322 // We are in our own directory. Why bother to mangle name?
323 // In fact I wrote this code to circumvent a problematic behaviour
324 // (bug?) of EMX mkstemp().
325 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
326 convert<string>(count++));
328 if (!tmpfl.createDirectory(0777)) {
329 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
330 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
331 from_utf8(tmpfl.absFileName())));
337 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
338 Buffer const * cloned_buffer)
339 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
340 read_only(readonly_), filename(file), file_fully_loaded(false),
341 toc_backend(owner), macro_lock(false), timestamp_(0), checksum_(0),
342 wa_(0), gui_(0), undo_(*owner), bibinfo_cache_valid_(false),
343 bibfile_cache_valid_(false), cite_labels_valid_(false),
344 preview_loader_(0), cloned_buffer_(cloned_buffer),
345 doing_export(false), parent_buffer(0)
347 if (!cloned_buffer_) {
348 temppath = createBufferTmpDir();
349 lyxvc.setBuffer(owner_);
351 wa_ = new frontend::WorkAreaManager;
354 temppath = cloned_buffer_->d->temppath;
355 file_fully_loaded = true;
356 params = cloned_buffer_->d->params;
357 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
358 bibinfo_ = cloned_buffer_->d->bibinfo_;
359 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
360 bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
361 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
362 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
363 unnamed = cloned_buffer_->d->unnamed;
367 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
368 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
370 LYXERR(Debug::INFO, "Buffer::Buffer()");
372 d->inset = new InsetText(*cloned_buffer->d->inset);
373 d->inset->setBuffer(*this);
374 // FIXME: optimize this loop somewhat, maybe by creating a new
375 // general recursive Inset::setId().
376 DocIterator it = doc_iterator_begin(this);
377 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
378 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
379 it.paragraph().setId(cloned_it.paragraph().id());
381 d->inset = new InsetText(this);
382 d->inset->setAutoBreakRows(true);
383 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
389 LYXERR(Debug::INFO, "Buffer::~Buffer()");
390 // here the buffer should take care that it is
391 // saved properly, before it goes into the void.
393 // GuiView already destroyed
397 // No need to do additional cleanups for internal buffer.
403 // this is in case of recursive includes: we won't try to delete
404 // ourselves as a child.
405 cloned_buffer_list.erase(this);
406 // loop over children
407 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
408 Impl::BufferPositionMap::iterator end = d->children_positions.end();
409 for (; it != end; ++it) {
410 Buffer * child = const_cast<Buffer *>(it->first);
411 if (cloned_buffer_list.erase(child))
414 // FIXME Do we really need to do this right before we delete d?
415 // clear references to children in macro tables
416 d->children_positions.clear();
417 d->position_to_children.clear();
419 // loop over children
420 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
421 Impl::BufferPositionMap::iterator end = d->children_positions.end();
422 for (; it != end; ++it) {
423 Buffer * child = const_cast<Buffer *>(it->first);
424 if (theBufferList().isLoaded(child))
425 theBufferList().releaseChild(this, child);
429 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
430 msg += emergencyWrite();
431 Alert::warning(_("Attempting to close changed document!"), msg);
434 // FIXME Do we really need to do this right before we delete d?
435 // clear references to children in macro tables
436 d->children_positions.clear();
437 d->position_to_children.clear();
439 if (!d->temppath.destroyDirectory()) {
440 Alert::warning(_("Could not remove temporary directory"),
441 bformat(_("Could not remove the temporary directory %1$s"),
442 from_utf8(d->temppath.absFileName())));
451 Buffer * Buffer::clone() const
454 masterBuffer()->clone(bufmap);
456 // make sure we got cloned
457 BufferMap::const_iterator bit = bufmap.find(this);
458 LASSERT(bit != bufmap.end(), return 0);
459 Buffer * cloned_buffer = bit->second;
461 // this should be empty. if not, then either we have left
462 // some buffer undeleted, or else we are trying to export
463 // two buffers at once. either way is a problem.
464 LASSERT(cloned_buffer_list.empty(), return 0);
465 // record the list of cloned buffers in the cloned master
466 BufferMap::iterator it = bufmap.begin();
467 BufferMap::iterator en = bufmap.end();
468 for (; it != en; ++it)
469 cloned_buffer_list.insert(it->second);
471 return cloned_buffer;
475 void Buffer::clone(BufferMap & bufmap) const
477 // have we already been cloned?
478 if (bufmap.find(this) != bufmap.end())
481 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
482 bufmap[this] = buffer_clone;
483 buffer_clone->d->macro_lock = true;
484 buffer_clone->d->children_positions.clear();
485 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
486 // math macro caches need to be rethought and simplified.
487 // I am not sure wether we should handle Buffer cloning here or in BufferList.
488 // Right now BufferList knows nothing about buffer clones.
489 Impl::PositionScopeBufferMap::iterator it = d->position_to_children.begin();
490 Impl::PositionScopeBufferMap::iterator end = d->position_to_children.end();
491 for (; it != end; ++it) {
492 DocIterator dit = it->first.clone(buffer_clone);
493 dit.setBuffer(buffer_clone);
494 Buffer * child = const_cast<Buffer *>(it->second.second);
496 child->clone(bufmap);
497 BufferMap::iterator const bit = bufmap.find(child);
498 LASSERT(bit != bufmap.end(), continue);
499 Buffer * child_clone = bit->second;
501 Inset * inset = dit.nextInset();
502 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
503 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
504 inset_inc->setChildBuffer(child_clone);
505 child_clone->d->setParent(buffer_clone);
506 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
507 buffer_clone->setChild(dit, child_clone);
509 buffer_clone->d->macro_lock = false;
514 bool Buffer::isClone() const
516 return d->cloned_buffer_;
520 void Buffer::changed(bool update_metrics) const
523 d->wa_->redrawAll(update_metrics);
527 frontend::WorkAreaManager & Buffer::workAreaManager() const
529 LASSERT(d->wa_, /**/);
534 Text & Buffer::text() const
536 return d->inset->text();
540 Inset & Buffer::inset() const
546 BufferParams & Buffer::params()
552 BufferParams const & Buffer::params() const
558 ParagraphList & Buffer::paragraphs()
560 return text().paragraphs();
564 ParagraphList const & Buffer::paragraphs() const
566 return text().paragraphs();
570 LyXVC & Buffer::lyxvc()
576 LyXVC const & Buffer::lyxvc() const
582 string const Buffer::temppath() const
584 return d->temppath.absFileName();
588 TexRow & Buffer::texrow()
594 TexRow const & Buffer::texrow() const
600 TocBackend & Buffer::tocBackend() const
602 return d->toc_backend;
606 Undo & Buffer::undo()
612 void Buffer::setChild(DocIterator const & dit, Buffer * child)
614 d->children_positions[child] = dit;
618 string Buffer::latexName(bool const no_path) const
620 FileName latex_name =
621 makeLatexName(d->exportFileName());
622 return no_path ? latex_name.onlyFileName()
623 : latex_name.absFileName();
627 FileName Buffer::Impl::exportFileName() const
629 docstring const branch_suffix =
630 params.branchlist().getFileNameSuffix();
631 if (branch_suffix.empty())
634 string const name = filename.onlyFileNameWithoutExt()
635 + to_utf8(branch_suffix);
636 FileName res(filename.onlyPath().absFileName() + "/" + name);
637 res.changeExtension(filename.extension());
643 string Buffer::logName(LogType * type) const
645 string const filename = latexName(false);
647 if (filename.empty()) {
653 string const path = temppath();
655 FileName const fname(addName(temppath(),
656 onlyFileName(changeExtension(filename,
659 // FIXME: how do we know this is the name of the build log?
660 FileName const bname(
661 addName(path, onlyFileName(
662 changeExtension(filename,
663 formats.extension(params().bufferFormat()) + ".out"))));
665 // Also consider the master buffer log file
666 FileName masterfname = fname;
668 if (masterBuffer() != this) {
669 string const mlogfile = masterBuffer()->logName(&mtype);
670 masterfname = FileName(mlogfile);
673 // If no Latex log or Build log is newer, show Build log
674 if (bname.exists() &&
675 ((!fname.exists() && !masterfname.exists())
676 || (fname.lastModified() < bname.lastModified()
677 && masterfname.lastModified() < bname.lastModified()))) {
678 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
681 return bname.absFileName();
682 // If we have a newer master file log or only a master log, show this
683 } else if (fname != masterfname
684 && (!fname.exists() && (masterfname.exists()
685 || fname.lastModified() < masterfname.lastModified()))) {
686 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
689 return masterfname.absFileName();
691 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
694 return fname.absFileName();
698 void Buffer::setReadonly(bool const flag)
700 if (d->read_only != flag) {
707 void Buffer::setFileName(FileName const & fname)
710 setReadonly(d->filename.isReadOnly());
716 int Buffer::readHeader(Lexer & lex)
718 int unknown_tokens = 0;
720 int begin_header_line = -1;
722 // Initialize parameters that may be/go lacking in header:
723 params().branchlist().clear();
724 params().preamble.erase();
725 params().options.erase();
726 params().master.erase();
727 params().float_placement.erase();
728 params().paperwidth.erase();
729 params().paperheight.erase();
730 params().leftmargin.erase();
731 params().rightmargin.erase();
732 params().topmargin.erase();
733 params().bottommargin.erase();
734 params().headheight.erase();
735 params().headsep.erase();
736 params().footskip.erase();
737 params().columnsep.erase();
738 params().fonts_cjk.erase();
739 params().listings_params.clear();
740 params().clearLayoutModules();
741 params().clearRemovedModules();
742 params().clearIncludedChildren();
743 params().pdfoptions().clear();
744 params().indiceslist().clear();
745 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
746 params().isbackgroundcolor = false;
747 params().fontcolor = RGBColor(0, 0, 0);
748 params().isfontcolor = false;
749 params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
750 params().boxbgcolor = RGBColor(0xFF, 0, 0);
751 params().html_latex_start.clear();
752 params().html_latex_end.clear();
753 params().html_math_img_scale = 1.0;
754 params().output_sync_macro.erase();
756 for (int i = 0; i < 4; ++i) {
757 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
758 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
761 ErrorList & errorList = d->errorLists["Parse"];
770 if (token == "\\end_header")
774 if (token == "\\begin_header") {
775 begin_header_line = line;
779 LYXERR(Debug::PARSER, "Handling document header token: `"
782 string unknown = params().readToken(lex, token, d->filename.onlyPath());
783 if (!unknown.empty()) {
784 if (unknown[0] != '\\' && token == "\\textclass") {
785 Alert::warning(_("Unknown document class"),
786 bformat(_("Using the default document class, because the "
787 "class %1$s is unknown."), from_utf8(unknown)));
790 docstring const s = bformat(_("Unknown token: "
794 errorList.push_back(ErrorItem(_("Document header error"),
799 if (begin_header_line) {
800 docstring const s = _("\\begin_header is missing");
801 errorList.push_back(ErrorItem(_("Document header error"),
805 params().makeDocumentClass();
807 return unknown_tokens;
812 // changed to be public and have one parameter
813 // Returns true if "\end_document" is not read (Asger)
814 bool Buffer::readDocument(Lexer & lex)
816 ErrorList & errorList = d->errorLists["Parse"];
819 // remove dummy empty par
820 paragraphs().clear();
822 if (!lex.checkFor("\\begin_document")) {
823 docstring const s = _("\\begin_document is missing");
824 errorList.push_back(ErrorItem(_("Document header error"),
830 if (params().outputChanges) {
831 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
832 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
833 LaTeXFeatures::isAvailable("xcolor");
835 if (!dvipost && !xcolorulem) {
836 Alert::warning(_("Changes not shown in LaTeX output"),
837 _("Changes will not be highlighted in LaTeX output, "
838 "because neither dvipost nor xcolor/ulem are installed.\n"
839 "Please install these packages or redefine "
840 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
841 } else if (!xcolorulem) {
842 Alert::warning(_("Changes not shown in LaTeX output"),
843 _("Changes will not be highlighted in LaTeX output "
844 "when using pdflatex, because xcolor and ulem are not installed.\n"
845 "Please install both packages or redefine "
846 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
850 if (!params().master.empty()) {
851 FileName const master_file = makeAbsPath(params().master,
852 onlyPath(absFileName()));
853 if (isLyXFileName(master_file.absFileName())) {
855 checkAndLoadLyXFile(master_file, true);
857 // necessary e.g. after a reload
858 // to re-register the child (bug 5873)
859 // FIXME: clean up updateMacros (here, only
860 // child registering is needed).
861 master->updateMacros();
862 // set master as master buffer, but only
863 // if we are a real child
864 if (master->isChild(this))
866 // if the master is not fully loaded
867 // it is probably just loading this
868 // child. No warning needed then.
869 else if (master->isFullyLoaded())
870 LYXERR0("The master '"
872 << "' assigned to this document ("
874 << ") does not include "
875 "this document. Ignoring the master assignment.");
880 // assure we have a default index
881 params().indiceslist().addDefault(B_("Index"));
884 bool const res = text().read(lex, errorList, d->inset);
886 // inform parent buffer about local macros
888 Buffer const * pbuf = parent();
889 UserMacroSet::const_iterator cit = usermacros.begin();
890 UserMacroSet::const_iterator end = usermacros.end();
891 for (; cit != end; ++cit)
892 pbuf->usermacros.insert(*cit);
896 updateMacroInstances(InternalUpdate);
901 bool Buffer::readString(string const & s)
903 params().compressed = false;
908 FileName const fn = FileName::tempName("Buffer_readString");
911 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
912 if (ret_plf != ReadSuccess)
915 if (file_format != LYX_FORMAT) {
916 // We need to call lyx2lyx, so write the input to a file
917 ofstream os(fn.toFilesystemEncoding().c_str());
921 return readFile(fn) == ReadSuccess;
924 if (readDocument(lex))
930 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
934 if (!lex.setFile(fname)) {
935 Alert::error(_("File Not Found"),
936 bformat(_("Unable to open file `%1$s'."),
937 from_utf8(fn.absFileName())));
938 return ReadFileNotFound;
942 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
943 if (ret_plf != ReadSuccess)
946 if (file_format != LYX_FORMAT) {
948 ReadStatus const ret_clf = convertLyXFormat(fn, tmpFile, file_format);
949 if (ret_clf != ReadSuccess)
951 return readFile(tmpFile);
954 // FIXME: InsetInfo needs to know whether the file is under VCS
955 // during the parse process, so this has to be done before.
956 lyxvc().file_found_hook(d->filename);
958 if (readDocument(lex)) {
959 Alert::error(_("Document format failure"),
960 bformat(_("%1$s ended unexpectedly, which means"
961 " that it is probably corrupted."),
962 from_utf8(fn.absFileName())));
963 return ReadDocumentFailure;
966 d->file_fully_loaded = true;
967 d->read_only = !d->filename.isWritable();
968 params().compressed = d->filename.isZippedFile();
974 bool Buffer::isFullyLoaded() const
976 return d->file_fully_loaded;
980 void Buffer::setFullyLoaded(bool value)
982 d->file_fully_loaded = value;
986 PreviewLoader * Buffer::loader() const
988 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
990 if (!d->preview_loader_)
991 d->preview_loader_ = new PreviewLoader(*this);
992 return d->preview_loader_;
996 void Buffer::removePreviews() const
998 delete d->preview_loader_;
999 d->preview_loader_ = 0;
1003 void Buffer::updatePreviews() const
1005 PreviewLoader * ploader = loader();
1009 InsetIterator it = inset_iterator_begin(*d->inset);
1010 InsetIterator const end = inset_iterator_end(*d->inset);
1011 for (; it != end; ++it)
1012 it->addPreview(it, *ploader);
1014 ploader->startLoading();
1018 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1019 FileName const & fn, int & file_format) const
1021 if(!lex.checkFor("\\lyxformat")) {
1022 Alert::error(_("Document format failure"),
1023 bformat(_("%1$s is not a readable LyX document."),
1024 from_utf8(fn.absFileName())));
1025 return ReadNoLyXFormat;
1031 // LyX formats 217 and earlier were written as 2.17. This corresponds
1032 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1033 // these cases. See also: www.lyx.org/trac/changeset/1313.
1034 size_t dot = tmp_format.find_first_of(".,");
1035 if (dot != string::npos)
1036 tmp_format.erase(dot, 1);
1038 file_format = convert<int>(tmp_format);
1043 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1044 FileName & tmpfile, int from_format)
1046 tmpfile = FileName::tempName("Buffer_convertLyXFormat");
1047 if(tmpfile.empty()) {
1048 Alert::error(_("Conversion failed"),
1049 bformat(_("%1$s is from a different"
1050 " version of LyX, but a temporary"
1051 " file for converting it could"
1052 " not be created."),
1053 from_utf8(fn.absFileName())));
1054 return LyX2LyXNoTempFile;
1057 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1058 if (lyx2lyx.empty()) {
1059 Alert::error(_("Conversion script not found"),
1060 bformat(_("%1$s is from a different"
1061 " version of LyX, but the"
1062 " conversion script lyx2lyx"
1063 " could not be found."),
1064 from_utf8(fn.absFileName())));
1065 return LyX2LyXNotFound;
1069 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1070 ostringstream command;
1071 command << os::python()
1072 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1073 << " -t " << convert<string>(LYX_FORMAT)
1074 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
1075 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1076 string const command_str = command.str();
1078 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1080 cmd_ret const ret = runCommand(command_str);
1081 if (ret.first != 0) {
1082 if (from_format < LYX_FORMAT) {
1083 Alert::error(_("Conversion script failed"),
1084 bformat(_("%1$s is from an older version"
1085 " of LyX and the lyx2lyx script"
1086 " failed to convert it."),
1087 from_utf8(fn.absFileName())));
1088 return LyX2LyXOlderFormat;
1090 Alert::error(_("Conversion script failed"),
1091 bformat(_("%1$s is from a newer version"
1092 " of LyX and the lyx2lyx script"
1093 " failed to convert it."),
1094 from_utf8(fn.absFileName())));
1095 return LyX2LyXNewerFormat;
1102 // Should probably be moved to somewhere else: BufferView? GuiView?
1103 bool Buffer::save() const
1105 docstring const file = makeDisplayPath(absFileName(), 20);
1106 d->filename.refresh();
1108 // check the read-only status before moving the file as a backup
1109 if (d->filename.exists()) {
1110 bool const read_only = !d->filename.isWritable();
1112 Alert::warning(_("File is read-only"),
1113 bformat(_("The file %1$s cannot be written because it "
1114 "is marked as read-only."), file));
1119 // ask if the disk file has been externally modified (use checksum method)
1120 if (fileName().exists() && isExternallyModified(checksum_method)) {
1122 bformat(_("Document %1$s has been externally modified. "
1123 "Are you sure you want to overwrite this file?"), file);
1124 int const ret = Alert::prompt(_("Overwrite modified file?"),
1125 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1130 // We don't need autosaves in the immediate future. (Asger)
1131 resetAutosaveTimers();
1133 FileName backupName;
1134 bool madeBackup = false;
1136 // make a backup if the file already exists
1137 if (lyxrc.make_backup && fileName().exists()) {
1138 backupName = FileName(absFileName() + '~');
1139 if (!lyxrc.backupdir_path.empty()) {
1140 string const mangledName =
1141 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1142 backupName = FileName(addName(lyxrc.backupdir_path,
1146 // Except file is symlink do not copy because of #6587.
1147 // Hard links have bad luck.
1148 if (fileName().isSymLink())
1149 madeBackup = fileName().copyTo(backupName);
1151 madeBackup = fileName().moveTo(backupName);
1154 Alert::error(_("Backup failure"),
1155 bformat(_("Cannot create backup file %1$s.\n"
1156 "Please check whether the directory exists and is writable."),
1157 from_utf8(backupName.absFileName())));
1158 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1162 if (writeFile(d->filename)) {
1166 // Saving failed, so backup is not backup
1168 backupName.moveTo(d->filename);
1174 bool Buffer::writeFile(FileName const & fname) const
1176 // FIXME Do we need to do these here? I don't think writing
1177 // the LyX file depends upon it. (RGH)
1179 // updateMacroInstances();
1181 if (d->read_only && fname == d->filename)
1184 bool retval = false;
1186 docstring const str = bformat(_("Saving document %1$s..."),
1187 makeDisplayPath(fname.absFileName()));
1190 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1192 if (params().compressed) {
1193 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1194 retval = ofs && write(ofs);
1196 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1197 retval = ofs && write(ofs);
1201 message(str + _(" could not write file!"));
1206 // removeAutosaveFile();
1209 message(str + _(" done."));
1215 docstring Buffer::emergencyWrite()
1217 // No need to save if the buffer has not changed.
1221 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1223 docstring user_message = bformat(
1224 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1226 // We try to save three places:
1227 // 1) Same place as document. Unless it is an unnamed doc.
1229 string s = absFileName();
1232 if (writeFile(FileName(s))) {
1234 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1235 return user_message;
1237 user_message += " " + _("Save failed! Trying again...\n");
1241 // 2) In HOME directory.
1242 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1244 lyxerr << ' ' << s << endl;
1245 if (writeFile(FileName(s))) {
1247 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1248 return user_message;
1251 user_message += " " + _("Save failed! Trying yet again...\n");
1253 // 3) In "/tmp" directory.
1254 // MakeAbsPath to prepend the current
1255 // drive letter on OS/2
1256 s = addName(package().temp_dir().absFileName(), absFileName());
1258 lyxerr << ' ' << s << endl;
1259 if (writeFile(FileName(s))) {
1261 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1262 return user_message;
1265 user_message += " " + _("Save failed! Bummer. Document is lost.");
1268 return user_message;
1272 bool Buffer::write(ostream & ofs) const
1275 // Use the standard "C" locale for file output.
1276 ofs.imbue(locale::classic());
1279 // The top of the file should not be written by params().
1281 // write out a comment in the top of the file
1282 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1283 << " created this file. For more info see http://www.lyx.org/\n"
1284 << "\\lyxformat " << LYX_FORMAT << "\n"
1285 << "\\begin_document\n";
1287 /// For each author, set 'used' to true if there is a change
1288 /// by this author in the document; otherwise set it to 'false'.
1289 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1290 AuthorList::Authors::const_iterator a_end = params().authors().end();
1291 for (; a_it != a_end; ++a_it)
1292 a_it->setUsed(false);
1294 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1295 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1296 for ( ; it != end; ++it)
1297 it->checkAuthors(params().authors());
1299 // now write out the buffer parameters.
1300 ofs << "\\begin_header\n";
1301 params().writeFile(ofs);
1302 ofs << "\\end_header\n";
1305 ofs << "\n\\begin_body\n";
1307 ofs << "\n\\end_body\n";
1309 // Write marker that shows file is complete
1310 ofs << "\\end_document" << endl;
1312 // Shouldn't really be needed....
1315 // how to check if close went ok?
1316 // Following is an attempt... (BE 20001011)
1318 // good() returns false if any error occured, including some
1319 // formatting error.
1320 // bad() returns true if something bad happened in the buffer,
1321 // which should include file system full errors.
1326 lyxerr << "File was not closed properly." << endl;
1333 bool Buffer::makeLaTeXFile(FileName const & fname,
1334 string const & original_path,
1335 OutputParams const & runparams_in,
1336 OutputWhat output) const
1338 OutputParams runparams = runparams_in;
1340 // This is necessary for LuaTeX/XeTeX with tex fonts.
1341 // See FIXME in BufferParams::encoding()
1342 if (runparams.isFullUnicode())
1343 runparams.encoding = encodings.fromLyXName("utf8-plain");
1345 string const encoding = runparams.encoding->iconvName();
1346 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1349 try { ofs.reset(encoding); }
1350 catch (iconv_codecvt_facet_exception & e) {
1351 lyxerr << "Caught iconv exception: " << e.what() << endl;
1352 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1353 "verify that the support software for your encoding (%1$s) is "
1354 "properly installed"), from_ascii(encoding)));
1357 if (!openFileWrite(ofs, fname))
1360 //TexStream ts(ofs.rdbuf(), &texrow());
1361 ErrorList & errorList = d->errorLists["Export"];
1363 bool failed_export = false;
1364 otexstream os(ofs, d->texrow);
1366 // make sure we are ready to export
1367 // this needs to be done before we validate
1368 // FIXME Do we need to do this all the time? I.e., in children
1369 // of a master we are exporting?
1371 updateMacroInstances(OutputUpdate);
1374 os.texrow().reset();
1375 writeLaTeXSource(os, original_path, runparams, output);
1377 catch (EncodingException & e) {
1378 odocstringstream ods;
1379 ods.put(e.failed_char);
1381 oss << "0x" << hex << e.failed_char << dec;
1382 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1383 " (code point %2$s)"),
1384 ods.str(), from_utf8(oss.str()));
1385 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1386 "representable in the chosen encoding.\n"
1387 "Changing the document encoding to utf8 could help."),
1388 e.par_id, e.pos, e.pos + 1));
1389 failed_export = true;
1391 catch (iconv_codecvt_facet_exception & e) {
1392 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1393 _(e.what()), -1, 0, 0));
1394 failed_export = true;
1396 catch (exception const & e) {
1397 errorList.push_back(ErrorItem(_("conversion failed"),
1398 _(e.what()), -1, 0, 0));
1399 failed_export = true;
1402 lyxerr << "Caught some really weird exception..." << endl;
1408 failed_export = true;
1409 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1413 return !failed_export;
1417 void Buffer::writeLaTeXSource(otexstream & os,
1418 string const & original_path,
1419 OutputParams const & runparams_in,
1420 OutputWhat output) const
1422 // The child documents, if any, shall be already loaded at this point.
1424 OutputParams runparams = runparams_in;
1426 // Classify the unicode characters appearing in math insets
1427 Encodings::initUnicodeMath(*this);
1429 // validate the buffer.
1430 LYXERR(Debug::LATEX, " Validating buffer...");
1431 LaTeXFeatures features(*this, params(), runparams);
1433 LYXERR(Debug::LATEX, " Buffer validation done.");
1435 bool const output_preamble =
1436 output == FullSource || output == OnlyPreamble;
1437 bool const output_body =
1438 output == FullSource || output == OnlyBody;
1440 // The starting paragraph of the coming rows is the
1441 // first paragraph of the document. (Asger)
1442 if (output_preamble && runparams.nice) {
1443 os << "%% LyX " << lyx_version << " created this file. "
1444 "For more info, see http://www.lyx.org/.\n"
1445 "%% Do not edit unless you really know what "
1448 LYXERR(Debug::INFO, "lyx document header finished");
1450 // There are a few differences between nice LaTeX and usual files:
1451 // usual files have \batchmode and special input@path to allow
1452 // inclusion of figures specified by an explicitly relative path
1453 // (i.e., a path starting with './' or '../') with either \input or
1454 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1455 // input@path is set when the actual parameter original_path is set.
1456 // This is done for usual tex-file, but not for nice-latex-file.
1457 // (Matthias 250696)
1458 // Note that input@path is only needed for something the user does
1459 // in the preamble, included .tex files or ERT, files included by
1460 // LyX work without it.
1461 if (output_preamble) {
1462 if (!runparams.nice) {
1463 // code for usual, NOT nice-latex-file
1464 os << "\\batchmode\n"; // changed from \nonstopmode
1466 if (!original_path.empty()) {
1468 // We don't know the encoding of inputpath
1469 docstring const inputpath = from_utf8(original_path);
1470 docstring uncodable_glyphs;
1471 Encoding const * const enc = runparams.encoding;
1473 for (size_t n = 0; n < inputpath.size(); ++n) {
1474 docstring const glyph =
1475 docstring(1, inputpath[n]);
1476 if (enc->latexChar(inputpath[n], true) != glyph) {
1477 LYXERR0("Uncodable character '"
1479 << "' in input path!");
1480 uncodable_glyphs += glyph;
1485 // warn user if we found uncodable glyphs.
1486 if (!uncodable_glyphs.empty()) {
1487 frontend::Alert::warning(
1488 _("Uncodable character in file path"),
1490 _("The path of your document\n"
1492 "contains glyphs that are unknown "
1493 "in the current document encoding "
1494 "(namely %2$s). This may result in "
1495 "incomplete output, unless "
1496 "TEXINPUTS contains the document "
1497 "directory and you don't use "
1498 "explicitly relative paths (i.e., "
1499 "paths starting with './' or "
1500 "'../') in the preamble or in ERT."
1501 "\n\nIn case of problems, choose "
1502 "an appropriate document encoding\n"
1503 "(such as utf8) or change the "
1505 inputpath, uncodable_glyphs));
1508 support::latex_path(original_path);
1509 if (contains(docdir, '#')) {
1510 docdir = subst(docdir, "#", "\\#");
1511 os << "\\catcode`\\#=11"
1512 "\\def\\#{#}\\catcode`\\#=6\n";
1514 if (contains(docdir, '%')) {
1515 docdir = subst(docdir, "%", "\\%");
1516 os << "\\catcode`\\%=11"
1517 "\\def\\%{%}\\catcode`\\%=14\n";
1519 os << "\\makeatletter\n"
1520 << "\\def\\input@path{{"
1521 << docdir << "/}}\n"
1522 << "\\makeatother\n";
1526 // get parent macros (if this buffer has a parent) which will be
1527 // written at the document begin further down.
1528 MacroSet parentMacros;
1529 listParentMacros(parentMacros, features);
1531 runparams.use_polyglossia = features.usePolyglossia();
1532 // Write the preamble
1533 runparams.use_babel = params().writeLaTeX(os, features,
1534 d->filename.onlyPath());
1536 runparams.use_japanese = features.isRequired("japanese");
1542 os << "\\begin{document}\n";
1544 // output the parent macros
1545 MacroSet::iterator it = parentMacros.begin();
1546 MacroSet::iterator end = parentMacros.end();
1547 for (; it != end; ++it) {
1548 int num_lines = (*it)->write(os.os(), true);
1549 os.texrow().newlines(num_lines);
1552 } // output_preamble
1554 os.texrow().start(paragraphs().begin()->id(), 0);
1556 LYXERR(Debug::INFO, "preamble finished, now the body.");
1558 // if we are doing a real file with body, even if this is the
1559 // child of some other buffer, let's cut the link here.
1560 // This happens for example if only a child document is printed.
1561 Buffer const * save_parent = 0;
1562 if (output_preamble) {
1563 save_parent = d->parent();
1568 latexParagraphs(*this, text(), os, runparams);
1570 // Restore the parenthood if needed
1571 if (output_preamble)
1572 d->setParent(save_parent);
1574 // add this just in case after all the paragraphs
1577 if (output_preamble) {
1578 os << "\\end{document}\n";
1579 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1581 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1583 runparams_in.encoding = runparams.encoding;
1585 // Just to be sure. (Asger)
1586 os.texrow().newline();
1588 //for (int i = 0; i<d->texrow.rows(); i++) {
1590 // if (d->texrow.getIdFromRow(i+1,id,pos) && id>0)
1591 // lyxerr << i+1 << ":" << id << ":" << getParFromID(id).paragraph().asString()<<"\n";
1594 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1595 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
1599 void Buffer::makeDocBookFile(FileName const & fname,
1600 OutputParams const & runparams,
1601 OutputWhat output) const
1603 LYXERR(Debug::LATEX, "makeDocBookFile...");
1606 if (!openFileWrite(ofs, fname))
1609 // make sure we are ready to export
1610 // this needs to be done before we validate
1612 updateMacroInstances(OutputUpdate);
1614 writeDocBookSource(ofs, fname.absFileName(), runparams, output);
1618 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1622 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1623 OutputParams const & runparams,
1624 OutputWhat output) const
1626 LaTeXFeatures features(*this, params(), runparams);
1631 DocumentClass const & tclass = params().documentClass();
1632 string const top_element = tclass.latexname();
1634 bool const output_preamble =
1635 output == FullSource || output == OnlyPreamble;
1636 bool const output_body =
1637 output == FullSource || output == OnlyBody;
1639 if (output_preamble) {
1640 if (runparams.flavor == OutputParams::XML)
1641 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1644 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1647 if (! tclass.class_header().empty())
1648 os << from_ascii(tclass.class_header());
1649 else if (runparams.flavor == OutputParams::XML)
1650 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1651 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1653 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1655 docstring preamble = from_utf8(params().preamble);
1656 if (runparams.flavor != OutputParams::XML ) {
1657 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1658 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1659 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1660 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1663 string const name = runparams.nice
1664 ? changeExtension(absFileName(), ".sgml") : fname;
1665 preamble += features.getIncludedFiles(name);
1666 preamble += features.getLyXSGMLEntities();
1668 if (!preamble.empty()) {
1669 os << "\n [ " << preamble << " ]";
1675 string top = top_element;
1677 if (runparams.flavor == OutputParams::XML)
1678 top += params().language->code();
1680 top += params().language->code().substr(0, 2);
1683 if (!params().options.empty()) {
1685 top += params().options;
1688 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1689 << " file was created by LyX " << lyx_version
1690 << "\n See http://www.lyx.org/ for more information -->\n";
1692 params().documentClass().counters().reset();
1694 sgml::openTag(os, top);
1696 docbookParagraphs(text(), *this, os, runparams);
1697 sgml::closeTag(os, top_element);
1702 void Buffer::makeLyXHTMLFile(FileName const & fname,
1703 OutputParams const & runparams) const
1705 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1708 if (!openFileWrite(ofs, fname))
1711 // make sure we are ready to export
1712 // this has to be done before we validate
1713 updateBuffer(UpdateMaster, OutputUpdate);
1714 updateMacroInstances(OutputUpdate);
1716 writeLyXHTMLSource(ofs, runparams, FullSource);
1720 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1724 void Buffer::writeLyXHTMLSource(odocstream & os,
1725 OutputParams const & runparams,
1726 OutputWhat output) const
1728 LaTeXFeatures features(*this, params(), runparams);
1730 d->bibinfo_.makeCitationLabels(*this);
1732 bool const output_preamble =
1733 output == FullSource || output == OnlyPreamble;
1734 bool const output_body =
1735 output == FullSource || output == OnlyBody;
1737 if (output_preamble) {
1738 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1739 << "<!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"
1740 // FIXME Language should be set properly.
1741 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
1743 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
1744 // FIXME Presumably need to set this right
1745 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1747 docstring const & doctitle = features.htmlTitle();
1749 << (doctitle.empty() ?
1750 from_ascii("LyX Document") :
1751 html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
1754 os << "\n<!-- Text Class Preamble -->\n"
1755 << features.getTClassHTMLPreamble()
1756 << "\n<!-- Preamble Snippets -->\n"
1757 << from_utf8(features.getPreambleSnippets());
1759 os << "\n<!-- Layout-provided Styles -->\n";
1760 docstring const styleinfo = features.getTClassHTMLStyles();
1761 if (!styleinfo.empty()) {
1762 os << "<style type='text/css'>\n"
1767 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
1768 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
1769 if (needfg || needbg) {
1770 os << "<style type='text/css'>\nbody {\n";
1773 << from_ascii(X11hexname(params().fontcolor))
1776 os << " background-color: "
1777 << from_ascii(X11hexname(params().backgroundcolor))
1779 os << "}\n</style>\n";
1787 params().documentClass().counters().reset();
1788 xhtmlParagraphs(text(), *this, xs, runparams);
1792 if (output_preamble)
1797 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1798 // Other flags: -wall -v0 -x
1799 int Buffer::runChktex()
1803 // get LaTeX-Filename
1804 FileName const path(temppath());
1805 string const name = addName(path.absFileName(), latexName());
1806 string const org_path = filePath();
1808 PathChanger p(path); // path to LaTeX file
1809 message(_("Running chktex..."));
1811 // Generate the LaTeX file if neccessary
1812 OutputParams runparams(¶ms().encoding());
1813 runparams.flavor = OutputParams::LATEX;
1814 runparams.nice = false;
1815 runparams.linelen = lyxrc.plaintext_linelen;
1816 makeLaTeXFile(FileName(name), org_path, runparams);
1819 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
1820 int const res = chktex.run(terr); // run chktex
1823 Alert::error(_("chktex failure"),
1824 _("Could not run chktex successfully."));
1825 } else if (res > 0) {
1826 ErrorList & errlist = d->errorLists["ChkTeX"];
1828 bufferErrors(terr, errlist);
1839 void Buffer::validate(LaTeXFeatures & features) const
1841 params().validate(features);
1843 for_each(paragraphs().begin(), paragraphs().end(),
1844 bind(&Paragraph::validate, _1, ref(features)));
1846 if (lyxerr.debugging(Debug::LATEX)) {
1847 features.showStruct();
1852 void Buffer::getLabelList(vector<docstring> & list) const
1854 // If this is a child document, use the master's list instead.
1856 masterBuffer()->getLabelList(list);
1861 Toc & toc = d->toc_backend.toc("label");
1862 TocIterator toc_it = toc.begin();
1863 TocIterator end = toc.end();
1864 for (; toc_it != end; ++toc_it) {
1865 if (toc_it->depth() == 0)
1866 list.push_back(toc_it->str());
1871 void Buffer::updateBibfilesCache(UpdateScope scope) const
1873 // FIXME This is probably unnecssary, given where we call this.
1874 // If this is a child document, use the parent's cache instead.
1875 if (parent() && scope != UpdateChildOnly) {
1876 masterBuffer()->updateBibfilesCache();
1880 d->bibfiles_cache_.clear();
1881 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1882 if (it->lyxCode() == BIBTEX_CODE) {
1883 InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
1884 support::FileNameList const bibfiles = inset.getBibFiles();
1885 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1888 } else if (it->lyxCode() == INCLUDE_CODE) {
1889 InsetInclude & inset = static_cast<InsetInclude &>(*it);
1890 Buffer const * const incbuf = inset.getChildBuffer();
1893 support::FileNameList const & bibfiles =
1894 incbuf->getBibfilesCache(UpdateChildOnly);
1895 if (!bibfiles.empty()) {
1896 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1902 d->bibfile_cache_valid_ = true;
1903 d->bibinfo_cache_valid_ = false;
1904 d->cite_labels_valid_ = false;
1908 void Buffer::invalidateBibinfoCache() const
1910 d->bibinfo_cache_valid_ = false;
1911 d->cite_labels_valid_ = false;
1912 // also invalidate the cache for the parent buffer
1913 Buffer const * const pbuf = d->parent();
1915 pbuf->invalidateBibinfoCache();
1919 void Buffer::invalidateBibfileCache() const
1921 d->bibfile_cache_valid_ = false;
1922 d->bibinfo_cache_valid_ = false;
1923 d->cite_labels_valid_ = false;
1924 // also invalidate the cache for the parent buffer
1925 Buffer const * const pbuf = d->parent();
1927 pbuf->invalidateBibfileCache();
1931 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1933 // FIXME This is probably unnecessary, given where we call this.
1934 // If this is a child document, use the master's cache instead.
1935 Buffer const * const pbuf = masterBuffer();
1936 if (pbuf != this && scope != UpdateChildOnly)
1937 return pbuf->getBibfilesCache();
1939 if (!d->bibfile_cache_valid_)
1940 this->updateBibfilesCache(scope);
1942 return d->bibfiles_cache_;
1946 BiblioInfo const & Buffer::masterBibInfo() const
1948 Buffer const * const tmp = masterBuffer();
1950 return tmp->masterBibInfo();
1955 void Buffer::checkIfBibInfoCacheIsValid() const
1957 // use the master's cache
1958 Buffer const * const tmp = masterBuffer();
1960 tmp->checkIfBibInfoCacheIsValid();
1964 // compare the cached timestamps with the actual ones.
1965 FileNameList const & bibfiles_cache = getBibfilesCache();
1966 FileNameList::const_iterator ei = bibfiles_cache.begin();
1967 FileNameList::const_iterator en = bibfiles_cache.end();
1968 for (; ei != en; ++ ei) {
1969 time_t lastw = ei->lastModified();
1970 time_t prevw = d->bibfile_status_[*ei];
1971 if (lastw != prevw) {
1972 d->bibinfo_cache_valid_ = false;
1973 d->cite_labels_valid_ = false;
1974 d->bibfile_status_[*ei] = lastw;
1980 void Buffer::reloadBibInfoCache() const
1982 // use the master's cache
1983 Buffer const * const tmp = masterBuffer();
1985 tmp->reloadBibInfoCache();
1989 checkIfBibInfoCacheIsValid();
1990 if (d->bibinfo_cache_valid_)
1993 d->bibinfo_.clear();
1995 d->bibinfo_cache_valid_ = true;
1999 void Buffer::collectBibKeys() const
2001 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2002 it->collectBibKeys(it);
2006 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
2008 Buffer const * tmp = masterBuffer();
2009 BiblioInfo & masterbi = (tmp == this) ?
2010 d->bibinfo_ : tmp->d->bibinfo_;
2011 masterbi.mergeBiblioInfo(bi);
2015 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
2017 Buffer const * tmp = masterBuffer();
2018 BiblioInfo & masterbi = (tmp == this) ?
2019 d->bibinfo_ : tmp->d->bibinfo_;
2024 bool Buffer::citeLabelsValid() const
2026 return masterBuffer()->d->cite_labels_valid_;
2030 bool Buffer::isDepClean(string const & name) const
2032 DepClean::const_iterator const it = d->dep_clean.find(name);
2033 if (it == d->dep_clean.end())
2039 void Buffer::markDepClean(string const & name)
2041 d->dep_clean[name] = true;
2045 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2048 // FIXME? if there is an Buffer LFUN that can be dispatched even
2049 // if internal, put a switch '(cmd.action)' here.
2055 switch (cmd.action()) {
2057 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2058 flag.setOnOff(isReadonly());
2061 // FIXME: There is need for a command-line import.
2062 //case LFUN_BUFFER_IMPORT:
2064 case LFUN_BUFFER_AUTO_SAVE:
2067 case LFUN_BUFFER_EXPORT_CUSTOM:
2068 // FIXME: Nothing to check here?
2071 case LFUN_BUFFER_EXPORT: {
2072 docstring const arg = cmd.argument();
2073 if (arg == "custom") {
2077 string format = to_utf8(arg);
2078 size_t pos = format.find(' ');
2079 if (pos != string::npos)
2080 format = format.substr(0, pos);
2081 enable = params().isExportable(format);
2083 flag.message(bformat(
2084 _("Don't know how to export to format: %1$s"), arg));
2088 case LFUN_BUFFER_CHKTEX:
2089 enable = params().isLatex() && !lyxrc.chktex_command.empty();
2092 case LFUN_BUILD_PROGRAM:
2093 enable = params().isExportable("program");
2096 case LFUN_BRANCH_ACTIVATE:
2097 case LFUN_BRANCH_DEACTIVATE: {
2098 BranchList const & branchList = params().branchlist();
2099 docstring const branchName = cmd.argument();
2100 enable = !branchName.empty() && branchList.find(branchName);
2104 case LFUN_BRANCH_ADD:
2105 case LFUN_BRANCHES_RENAME:
2106 case LFUN_BUFFER_PRINT:
2107 // if no Buffer is present, then of course we won't be called!
2110 case LFUN_BUFFER_LANGUAGE:
2111 enable = !isReadonly();
2117 flag.setEnabled(enable);
2122 void Buffer::dispatch(string const & command, DispatchResult & result)
2124 return dispatch(lyxaction.lookupFunc(command), result);
2128 // NOTE We can end up here even if we have no GUI, because we are called
2129 // by LyX::exec to handled command-line requests. So we may need to check
2130 // whether we have a GUI or not. The boolean use_gui holds this information.
2131 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2134 // FIXME? if there is an Buffer LFUN that can be dispatched even
2135 // if internal, put a switch '(cmd.action())' here.
2136 dr.dispatched(false);
2139 string const argument = to_utf8(func.argument());
2140 // We'll set this back to false if need be.
2141 bool dispatched = true;
2142 undo().beginUndoGroup();
2144 switch (func.action()) {
2145 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2146 if (lyxvc().inUse())
2147 lyxvc().toggleReadOnly();
2149 setReadonly(!isReadonly());
2152 case LFUN_BUFFER_EXPORT: {
2153 ExportStatus const status = doExport(argument, false);
2154 dr.setError(status != ExportSuccess);
2155 if (status != ExportSuccess)
2156 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2161 case LFUN_BUILD_PROGRAM:
2162 doExport("program", true);
2165 case LFUN_BUFFER_CHKTEX:
2169 case LFUN_BUFFER_EXPORT_CUSTOM: {
2171 string command = split(argument, format_name, ' ');
2172 Format const * format = formats.getFormat(format_name);
2174 lyxerr << "Format \"" << format_name
2175 << "\" not recognized!"
2180 // The name of the file created by the conversion process
2183 // Output to filename
2184 if (format->name() == "lyx") {
2185 string const latexname = latexName(false);
2186 filename = changeExtension(latexname,
2187 format->extension());
2188 filename = addName(temppath(), filename);
2190 if (!writeFile(FileName(filename)))
2194 doExport(format_name, true, filename);
2197 // Substitute $$FName for filename
2198 if (!contains(command, "$$FName"))
2199 command = "( " + command + " ) < $$FName";
2200 command = subst(command, "$$FName", filename);
2202 // Execute the command in the background
2204 call.startscript(Systemcall::DontWait, command, filePath());
2208 // FIXME: There is need for a command-line import.
2210 case LFUN_BUFFER_IMPORT:
2215 case LFUN_BUFFER_AUTO_SAVE:
2217 resetAutosaveTimers();
2220 case LFUN_BRANCH_ADD: {
2221 docstring branch_name = func.argument();
2222 if (branch_name.empty()) {
2226 BranchList & branch_list = params().branchlist();
2227 vector<docstring> const branches =
2228 getVectorFromString(branch_name, branch_list.separator());
2230 for (vector<docstring>::const_iterator it = branches.begin();
2231 it != branches.end(); ++it) {
2233 Branch * branch = branch_list.find(branch_name);
2235 LYXERR0("Branch " << branch_name << " already exists.");
2239 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2241 branch_list.add(branch_name);
2242 branch = branch_list.find(branch_name);
2243 string const x11hexname = X11hexname(branch->color());
2244 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2245 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2247 dr.screenUpdate(Update::Force);
2255 case LFUN_BRANCH_ACTIVATE:
2256 case LFUN_BRANCH_DEACTIVATE: {
2257 BranchList & branchList = params().branchlist();
2258 docstring const branchName = func.argument();
2259 // the case without a branch name is handled elsewhere
2260 if (branchName.empty()) {
2264 Branch * branch = branchList.find(branchName);
2266 LYXERR0("Branch " << branchName << " does not exist.");
2268 docstring const msg =
2269 bformat(_("Branch \"%1$s\" does not exist."), branchName);
2272 branch->setSelected(func.action() == LFUN_BRANCH_ACTIVATE);
2274 dr.screenUpdate(Update::Force);
2275 dr.forceBufferUpdate();
2280 case LFUN_BRANCHES_RENAME: {
2281 if (func.argument().empty())
2284 docstring const oldname = from_utf8(func.getArg(0));
2285 docstring const newname = from_utf8(func.getArg(1));
2286 InsetIterator it = inset_iterator_begin(inset());
2287 InsetIterator const end = inset_iterator_end(inset());
2288 bool success = false;
2289 for (; it != end; ++it) {
2290 if (it->lyxCode() == BRANCH_CODE) {
2291 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2292 if (ins.branch() == oldname) {
2293 undo().recordUndo(it);
2294 ins.rename(newname);
2299 if (it->lyxCode() == INCLUDE_CODE) {
2300 // get buffer of external file
2301 InsetInclude const & ins =
2302 static_cast<InsetInclude const &>(*it);
2303 Buffer * child = ins.getChildBuffer();
2306 child->dispatch(func, dr);
2311 dr.screenUpdate(Update::Force);
2312 dr.forceBufferUpdate();
2317 case LFUN_BUFFER_PRINT: {
2318 // we'll assume there's a problem until we succeed
2320 string target = func.getArg(0);
2321 string target_name = func.getArg(1);
2322 string command = func.getArg(2);
2325 || target_name.empty()
2326 || command.empty()) {
2327 LYXERR0("Unable to parse " << func.argument());
2328 docstring const msg =
2329 bformat(_("Unable to parse \"%1$s\""), func.argument());
2333 if (target != "printer" && target != "file") {
2334 LYXERR0("Unrecognized target \"" << target << '"');
2335 docstring const msg =
2336 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2341 if (!doExport("dvi", true)) {
2342 showPrintError(absFileName());
2343 dr.setMessage(_("Error exporting to DVI."));
2347 // Push directory path.
2348 string const path = temppath();
2349 // Prevent the compiler from optimizing away p
2353 // there are three cases here:
2354 // 1. we print to a file
2355 // 2. we print directly to a printer
2356 // 3. we print using a spool command (print to file first)
2359 string const dviname = changeExtension(latexName(true), "dvi");
2361 if (target == "printer") {
2362 if (!lyxrc.print_spool_command.empty()) {
2363 // case 3: print using a spool
2364 string const psname = changeExtension(dviname,".ps");
2365 command += ' ' + lyxrc.print_to_file
2368 + quoteName(dviname);
2370 string command2 = lyxrc.print_spool_command + ' ';
2371 if (target_name != "default") {
2372 command2 += lyxrc.print_spool_printerprefix
2376 command2 += quoteName(psname);
2378 // If successful, then spool command
2379 res = one.startscript(Systemcall::Wait, command,
2383 // If there's no GUI, we have to wait on this command. Otherwise,
2384 // LyX deletes the temporary directory, and with it the spooled
2385 // file, before it can be printed!!
2386 Systemcall::Starttype stype = use_gui ?
2387 Systemcall::DontWait : Systemcall::Wait;
2388 res = one.startscript(stype, command2,
2392 // case 2: print directly to a printer
2393 if (target_name != "default")
2394 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2396 Systemcall::Starttype stype = use_gui ?
2397 Systemcall::DontWait : Systemcall::Wait;
2398 res = one.startscript(stype, command +
2399 quoteName(dviname), filePath());
2403 // case 1: print to a file
2404 FileName const filename(makeAbsPath(target_name, filePath()));
2405 FileName const dvifile(makeAbsPath(dviname, path));
2406 if (filename.exists()) {
2407 docstring text = bformat(
2408 _("The file %1$s already exists.\n\n"
2409 "Do you want to overwrite that file?"),
2410 makeDisplayPath(filename.absFileName()));
2411 if (Alert::prompt(_("Overwrite file?"),
2412 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2415 command += ' ' + lyxrc.print_to_file
2416 + quoteName(filename.toFilesystemEncoding())
2418 + quoteName(dvifile.toFilesystemEncoding());
2420 Systemcall::Starttype stype = use_gui ?
2421 Systemcall::DontWait : Systemcall::Wait;
2422 res = one.startscript(stype, command, filePath());
2428 dr.setMessage(_("Error running external commands."));
2429 showPrintError(absFileName());
2438 dr.dispatched(dispatched);
2439 undo().endUndoGroup();
2443 void Buffer::changeLanguage(Language const * from, Language const * to)
2445 LASSERT(from, /**/);
2448 for_each(par_iterator_begin(),
2450 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2454 bool Buffer::isMultiLingual() const
2456 ParConstIterator end = par_iterator_end();
2457 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2458 if (it->isMultiLingual(params()))
2465 std::set<Language const *> Buffer::getLanguages() const
2467 std::set<Language const *> languages;
2468 getLanguages(languages);
2473 void Buffer::getLanguages(std::set<Language const *> & languages) const
2475 ParConstIterator end = par_iterator_end();
2476 // add the buffer language, even if it's not actively used
2477 languages.insert(language());
2478 // iterate over the paragraphs
2479 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2480 it->getLanguages(languages);
2482 ListOfBuffers clist = getDescendents();
2483 ListOfBuffers::const_iterator cit = clist.begin();
2484 ListOfBuffers::const_iterator const cen = clist.end();
2485 for (; cit != cen; ++cit)
2486 (*cit)->getLanguages(languages);
2490 DocIterator Buffer::getParFromID(int const id) const
2492 Buffer * buf = const_cast<Buffer *>(this);
2494 // John says this is called with id == -1 from undo
2495 lyxerr << "getParFromID(), id: " << id << endl;
2496 return doc_iterator_end(buf);
2499 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2500 if (it.paragraph().id() == id)
2503 return doc_iterator_end(buf);
2507 bool Buffer::hasParWithID(int const id) const
2509 return !getParFromID(id).atEnd();
2513 ParIterator Buffer::par_iterator_begin()
2515 return ParIterator(doc_iterator_begin(this));
2519 ParIterator Buffer::par_iterator_end()
2521 return ParIterator(doc_iterator_end(this));
2525 ParConstIterator Buffer::par_iterator_begin() const
2527 return ParConstIterator(doc_iterator_begin(this));
2531 ParConstIterator Buffer::par_iterator_end() const
2533 return ParConstIterator(doc_iterator_end(this));
2537 Language const * Buffer::language() const
2539 return params().language;
2543 docstring const Buffer::B_(string const & l10n) const
2545 return params().B_(l10n);
2549 bool Buffer::isClean() const
2551 return d->lyx_clean;
2555 bool Buffer::isExternallyModified(CheckMethod method) const
2557 LASSERT(d->filename.exists(), /**/);
2558 // if method == timestamp, check timestamp before checksum
2559 return (method == checksum_method
2560 || d->timestamp_ != d->filename.lastModified())
2561 && d->checksum_ != d->filename.checksum();
2565 void Buffer::saveCheckSum() const
2567 FileName const & file = d->filename;
2570 if (file.exists()) {
2571 d->timestamp_ = file.lastModified();
2572 d->checksum_ = file.checksum();
2574 // in the case of save to a new file.
2581 void Buffer::markClean() const
2583 if (!d->lyx_clean) {
2584 d->lyx_clean = true;
2587 // if the .lyx file has been saved, we don't need an
2589 d->bak_clean = true;
2590 d->undo_.markDirty();
2594 void Buffer::setUnnamed(bool flag)
2600 bool Buffer::isUnnamed() const
2607 /// Don't check unnamed, here: isInternal() is used in
2608 /// newBuffer(), where the unnamed flag has not been set by anyone
2609 /// yet. Also, for an internal buffer, there should be no need for
2610 /// retrieving fileName() nor for checking if it is unnamed or not.
2611 bool Buffer::isInternal() const
2613 return fileName().extension() == "internal";
2617 void Buffer::markDirty()
2620 d->lyx_clean = false;
2623 d->bak_clean = false;
2625 DepClean::iterator it = d->dep_clean.begin();
2626 DepClean::const_iterator const end = d->dep_clean.end();
2628 for (; it != end; ++it)
2633 FileName Buffer::fileName() const
2639 string Buffer::absFileName() const
2641 return d->filename.absFileName();
2645 string Buffer::filePath() const
2647 return d->filename.onlyPath().absFileName() + "/";
2651 bool Buffer::isReadonly() const
2653 return d->read_only;
2657 void Buffer::setParent(Buffer const * buffer)
2659 // Avoids recursive include.
2660 d->setParent(buffer == this ? 0 : buffer);
2665 Buffer const * Buffer::parent() const
2671 ListOfBuffers Buffer::allRelatives() const
2673 ListOfBuffers lb = masterBuffer()->getDescendents();
2674 lb.push_front(const_cast<Buffer *>(masterBuffer()));
2679 Buffer const * Buffer::masterBuffer() const
2681 // FIXME Should be make sure we are not in some kind
2682 // of recursive include? A -> B -> A will crash this.
2683 Buffer const * const pbuf = d->parent();
2687 return pbuf->masterBuffer();
2691 bool Buffer::isChild(Buffer * child) const
2693 return d->children_positions.find(child) != d->children_positions.end();
2697 DocIterator Buffer::firstChildPosition(Buffer const * child)
2699 Impl::BufferPositionMap::iterator it;
2700 it = d->children_positions.find(child);
2701 if (it == d->children_positions.end())
2702 return DocIterator(this);
2707 bool Buffer::hasChildren() const
2709 return !d->children_positions.empty();
2713 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
2715 // loop over children
2716 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2717 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2718 for (; it != end; ++it) {
2719 Buffer * child = const_cast<Buffer *>(it->first);
2721 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
2722 if (bit != clist.end())
2724 clist.push_back(child);
2726 // there might be grandchildren
2727 child->collectChildren(clist, true);
2732 ListOfBuffers Buffer::getChildren() const
2735 collectChildren(v, false);
2736 // Make sure we have not included ourselves.
2737 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
2738 if (bit != v.end()) {
2739 LYXERR0("Recursive include detected in `" << fileName() << "'.");
2746 ListOfBuffers Buffer::getDescendents() const
2749 collectChildren(v, true);
2750 // Make sure we have not included ourselves.
2751 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
2752 if (bit != v.end()) {
2753 LYXERR0("Recursive include detected in `" << fileName() << "'.");
2760 template<typename M>
2761 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
2766 typename M::const_iterator it = m.lower_bound(x);
2767 if (it == m.begin())
2775 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
2776 DocIterator const & pos) const
2778 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2780 // if paragraphs have no macro context set, pos will be empty
2784 // we haven't found anything yet
2785 DocIterator bestPos = owner_->par_iterator_begin();
2786 MacroData const * bestData = 0;
2788 // find macro definitions for name
2789 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
2790 if (nameIt != macros.end()) {
2791 // find last definition in front of pos or at pos itself
2792 PositionScopeMacroMap::const_iterator it
2793 = greatest_below(nameIt->second, pos);
2794 if (it != nameIt->second.end()) {
2796 // scope ends behind pos?
2797 if (pos < it->second.first) {
2798 // Looks good, remember this. If there
2799 // is no external macro behind this,
2800 // we found the right one already.
2801 bestPos = it->first;
2802 bestData = &it->second.second;
2806 // try previous macro if there is one
2807 if (it == nameIt->second.begin())
2814 // find macros in included files
2815 PositionScopeBufferMap::const_iterator it
2816 = greatest_below(position_to_children, pos);
2817 if (it == position_to_children.end())
2818 // no children before
2822 // do we know something better (i.e. later) already?
2823 if (it->first < bestPos )
2826 // scope ends behind pos?
2827 if (pos < it->second.first
2828 && (cloned_buffer_ ||
2829 theBufferList().isLoaded(it->second.second))) {
2830 // look for macro in external file
2832 MacroData const * data
2833 = it->second.second->getMacro(name, false);
2836 bestPos = it->first;
2842 // try previous file if there is one
2843 if (it == position_to_children.begin())
2848 // return the best macro we have found
2853 MacroData const * Buffer::getMacro(docstring const & name,
2854 DocIterator const & pos, bool global) const
2859 // query buffer macros
2860 MacroData const * data = d->getBufferMacro(name, pos);
2864 // If there is a master buffer, query that
2865 Buffer const * const pbuf = d->parent();
2867 d->macro_lock = true;
2868 MacroData const * macro = pbuf->getMacro(
2869 name, *this, false);
2870 d->macro_lock = false;
2876 data = MacroTable::globalMacros().get(name);
2885 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2887 // set scope end behind the last paragraph
2888 DocIterator scope = par_iterator_begin();
2889 scope.pit() = scope.lastpit() + 1;
2891 return getMacro(name, scope, global);
2895 MacroData const * Buffer::getMacro(docstring const & name,
2896 Buffer const & child, bool global) const
2898 // look where the child buffer is included first
2899 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2900 if (it == d->children_positions.end())
2903 // check for macros at the inclusion position
2904 return getMacro(name, it->second, global);
2908 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
2910 pit_type const lastpit = it.lastpit();
2912 // look for macros in each paragraph
2913 while (it.pit() <= lastpit) {
2914 Paragraph & par = it.paragraph();
2916 // iterate over the insets of the current paragraph
2917 InsetList const & insets = par.insetList();
2918 InsetList::const_iterator iit = insets.begin();
2919 InsetList::const_iterator end = insets.end();
2920 for (; iit != end; ++iit) {
2921 it.pos() = iit->pos;
2923 // is it a nested text inset?
2924 if (iit->inset->asInsetText()) {
2925 // Inset needs its own scope?
2926 InsetText const * itext = iit->inset->asInsetText();
2927 bool newScope = itext->isMacroScope();
2929 // scope which ends just behind the inset
2930 DocIterator insetScope = it;
2933 // collect macros in inset
2934 it.push_back(CursorSlice(*iit->inset));
2935 updateMacros(it, newScope ? insetScope : scope);
2940 if (iit->inset->asInsetTabular()) {
2941 CursorSlice slice(*iit->inset);
2942 size_t const numcells = slice.nargs();
2943 for (; slice.idx() < numcells; slice.forwardIdx()) {
2944 it.push_back(slice);
2945 updateMacros(it, scope);
2951 // is it an external file?
2952 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2953 // get buffer of external file
2954 InsetInclude const & inset =
2955 static_cast<InsetInclude const &>(*iit->inset);
2957 Buffer * child = inset.getChildBuffer();
2962 // register its position, but only when it is
2963 // included first in the buffer
2964 if (children_positions.find(child) ==
2965 children_positions.end())
2966 children_positions[child] = it;
2968 // register child with its scope
2969 position_to_children[it] = Impl::ScopeBuffer(scope, child);
2973 InsetMath * im = iit->inset->asInsetMath();
2974 if (doing_export && im) {
2975 InsetMathHull * hull = im->asHullInset();
2977 hull->recordLocation(it);
2980 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2984 MathMacroTemplate & macroTemplate =
2985 *iit->inset->asInsetMath()->asMacroTemplate();
2986 MacroContext mc(owner_, it);
2987 macroTemplate.updateToContext(mc);
2990 bool valid = macroTemplate.validMacro();
2991 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2992 // then the BufferView's cursor will be invalid in
2993 // some cases which leads to crashes.
2998 // FIXME (Abdel), I don't understandt why we pass 'it' here
2999 // instead of 'macroTemplate' defined above... is this correct?
3000 macros[macroTemplate.name()][it] =
3001 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3011 void Buffer::updateMacros() const
3016 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3018 // start with empty table
3020 d->children_positions.clear();
3021 d->position_to_children.clear();
3023 // Iterate over buffer, starting with first paragraph
3024 // The scope must be bigger than any lookup DocIterator
3025 // later. For the global lookup, lastpit+1 is used, hence
3026 // we use lastpit+2 here.
3027 DocIterator it = par_iterator_begin();
3028 DocIterator outerScope = it;
3029 outerScope.pit() = outerScope.lastpit() + 2;
3030 d->updateMacros(it, outerScope);
3034 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3036 InsetIterator it = inset_iterator_begin(inset());
3037 InsetIterator const end = inset_iterator_end(inset());
3038 for (; it != end; ++it) {
3039 if (it->lyxCode() == BRANCH_CODE) {
3040 InsetBranch & br = static_cast<InsetBranch &>(*it);
3041 docstring const name = br.branch();
3042 if (!from_master && !params().branchlist().find(name))
3043 result.push_back(name);
3044 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3045 result.push_back(name);
3048 if (it->lyxCode() == INCLUDE_CODE) {
3049 // get buffer of external file
3050 InsetInclude const & ins =
3051 static_cast<InsetInclude const &>(*it);
3052 Buffer * child = ins.getChildBuffer();
3055 child->getUsedBranches(result, true);
3058 // remove duplicates
3063 void Buffer::updateMacroInstances(UpdateType utype) const
3065 LYXERR(Debug::MACROS, "updateMacroInstances for "
3066 << d->filename.onlyFileName());
3067 DocIterator it = doc_iterator_begin(this);
3069 DocIterator const end = doc_iterator_end(this);
3070 for (; it != end; it.forwardInset()) {
3071 // look for MathData cells in InsetMathNest insets
3072 InsetMath * minset = it.nextInset()->asInsetMath();
3076 // update macro in all cells of the InsetMathNest
3077 DocIterator::idx_type n = minset->nargs();
3078 MacroContext mc = MacroContext(this, it);
3079 for (DocIterator::idx_type i = 0; i < n; ++i) {
3080 MathData & data = minset->cell(i);
3081 data.updateMacros(0, mc, utype);
3087 void Buffer::listMacroNames(MacroNameSet & macros) const
3092 d->macro_lock = true;
3094 // loop over macro names
3095 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3096 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3097 for (; nameIt != nameEnd; ++nameIt)
3098 macros.insert(nameIt->first);
3100 // loop over children
3101 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3102 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3103 for (; it != end; ++it)
3104 it->first->listMacroNames(macros);
3107 Buffer const * const pbuf = d->parent();
3109 pbuf->listMacroNames(macros);
3111 d->macro_lock = false;
3115 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3117 Buffer const * const pbuf = d->parent();
3122 pbuf->listMacroNames(names);
3125 MacroNameSet::iterator it = names.begin();
3126 MacroNameSet::iterator end = names.end();
3127 for (; it != end; ++it) {
3129 MacroData const * data =
3130 pbuf->getMacro(*it, *this, false);
3132 macros.insert(data);
3134 // we cannot access the original MathMacroTemplate anymore
3135 // here to calls validate method. So we do its work here manually.
3136 // FIXME: somehow make the template accessible here.
3137 if (data->optionals() > 0)
3138 features.require("xargs");
3144 Buffer::References & Buffer::references(docstring const & label)
3147 return const_cast<Buffer *>(masterBuffer())->references(label);
3149 RefCache::iterator it = d->ref_cache_.find(label);
3150 if (it != d->ref_cache_.end())
3151 return it->second.second;
3153 static InsetLabel const * dummy_il = 0;
3154 static References const dummy_refs;
3155 it = d->ref_cache_.insert(
3156 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3157 return it->second.second;
3161 Buffer::References const & Buffer::references(docstring const & label) const
3163 return const_cast<Buffer *>(this)->references(label);
3167 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3169 masterBuffer()->d->ref_cache_[label].first = il;
3173 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3175 return masterBuffer()->d->ref_cache_[label].first;
3179 void Buffer::clearReferenceCache() const
3182 d->ref_cache_.clear();
3186 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
3189 //FIXME: This does not work for child documents yet.
3190 LASSERT(code == CITE_CODE, /**/);
3192 reloadBibInfoCache();
3194 // Check if the label 'from' appears more than once
3195 BiblioInfo const & keys = masterBibInfo();
3196 BiblioInfo::const_iterator bit = keys.begin();
3197 BiblioInfo::const_iterator bend = keys.end();
3198 vector<docstring> labels;
3200 for (; bit != bend; ++bit)
3202 labels.push_back(bit->first);
3204 if (count(labels.begin(), labels.end(), from) > 1)
3207 string const paramName = "key";
3208 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3209 if (it->lyxCode() == code) {
3210 InsetCommand * inset = it->asInsetCommand();
3213 docstring const oldValue = inset->getParam(paramName);
3214 if (oldValue == from)
3215 inset->setParam(paramName, to);
3221 void Buffer::getSourceCode(odocstream & os, string const format,
3222 pit_type par_begin, pit_type par_end,
3223 OutputWhat output) const
3225 OutputParams runparams(¶ms().encoding());
3226 runparams.nice = true;
3227 runparams.flavor = params().getOutputFlavor(format);
3228 runparams.linelen = lyxrc.plaintext_linelen;
3229 // No side effect of file copying and image conversion
3230 runparams.dryrun = true;
3232 if (output == CurrentParagraph) {
3233 runparams.par_begin = par_begin;
3234 runparams.par_end = par_end;
3235 if (par_begin + 1 == par_end) {
3237 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3241 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3242 convert<docstring>(par_begin),
3243 convert<docstring>(par_end - 1))
3250 // output paragraphs
3251 if (params().isDocBook())
3252 docbookParagraphs(text(), *this, os, runparams);
3253 else if (runparams.flavor == OutputParams::HTML) {
3255 xhtmlParagraphs(text(), *this, xs, runparams);
3257 // latex or literate
3258 otexstream ots(os, texrow);
3259 latexParagraphs(*this, text(), ots, runparams);
3263 if (output == FullSource)
3264 os << _("Preview source code");
3265 else if (output == OnlyPreamble)
3266 os << _("Preview preamble");
3267 else if (output == OnlyBody)
3268 os << _("Preview body");
3271 d->texrow.newline();
3272 d->texrow.newline();
3273 if (params().isDocBook())
3274 writeDocBookSource(os, absFileName(), runparams, output);
3275 else if (runparams.flavor == OutputParams::HTML)
3276 writeLyXHTMLSource(os, runparams, output);
3278 // latex or literate
3279 otexstream ots(os, d->texrow);
3280 writeLaTeXSource(ots, string(), runparams, output);
3286 ErrorList & Buffer::errorList(string const & type) const
3288 return d->errorLists[type];
3292 void Buffer::updateTocItem(std::string const & type,
3293 DocIterator const & dit) const
3296 d->gui_->updateTocItem(type, dit);
3300 void Buffer::structureChanged() const
3303 d->gui_->structureChanged();
3307 void Buffer::errors(string const & err, bool from_master) const
3310 d->gui_->errors(err, from_master);
3314 void Buffer::message(docstring const & msg) const
3317 d->gui_->message(msg);
3321 void Buffer::setBusy(bool on) const
3324 d->gui_->setBusy(on);
3328 void Buffer::updateTitles() const
3331 d->wa_->updateTitles();
3335 void Buffer::resetAutosaveTimers() const
3338 d->gui_->resetAutosaveTimers();
3342 bool Buffer::hasGuiDelegate() const
3348 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3357 class AutoSaveBuffer : public ForkedProcess {
3360 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3361 : buffer_(buffer), fname_(fname) {}
3363 virtual shared_ptr<ForkedProcess> clone() const
3365 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3370 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3371 from_utf8(fname_.absFileName())));
3372 return run(DontWait);
3376 virtual int generateChild();
3378 Buffer const & buffer_;
3383 int AutoSaveBuffer::generateChild()
3385 #if defined(__APPLE__)
3386 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3387 * We should use something else like threads.
3389 * Since I do not know how to determine at run time what is the OS X
3390 * version, I just disable forking altogether for now (JMarc)
3392 pid_t const pid = -1;
3394 // tmp_ret will be located (usually) in /tmp
3395 // will that be a problem?
3396 // Note that this calls ForkedCalls::fork(), so it's
3397 // ok cross-platform.
3398 pid_t const pid = fork();
3399 // If you want to debug the autosave
3400 // you should set pid to -1, and comment out the fork.
3401 if (pid != 0 && pid != -1)
3405 // pid = -1 signifies that lyx was unable
3406 // to fork. But we will do the save
3408 bool failed = false;
3409 FileName const tmp_ret = FileName::tempName("lyxauto");
3410 if (!tmp_ret.empty()) {
3411 buffer_.writeFile(tmp_ret);
3412 // assume successful write of tmp_ret
3413 if (!tmp_ret.moveTo(fname_))
3419 // failed to write/rename tmp_ret so try writing direct
3420 if (!buffer_.writeFile(fname_)) {
3421 // It is dangerous to do this in the child,
3422 // but safe in the parent, so...
3423 if (pid == -1) // emit message signal.
3424 buffer_.message(_("Autosave failed!"));
3428 if (pid == 0) // we are the child so...
3437 FileName Buffer::getEmergencyFileName() const
3439 return FileName(d->filename.absFileName() + ".emergency");
3443 FileName Buffer::getAutosaveFileName() const
3445 // if the document is unnamed try to save in the backup dir, else
3446 // in the default document path, and as a last try in the filePath,
3447 // which will most often be the temporary directory
3450 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3451 : lyxrc.backupdir_path;
3452 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3455 string const fname = "#" + d->filename.onlyFileName() + "#";
3457 return makeAbsPath(fname, fpath);
3461 void Buffer::removeAutosaveFile() const
3463 FileName const f = getAutosaveFileName();
3469 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3471 FileName const newauto = getAutosaveFileName();
3473 if (newauto != oldauto && oldauto.exists())
3474 if (!oldauto.moveTo(newauto))
3475 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3479 bool Buffer::autoSave() const
3481 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
3482 if (buf->d->bak_clean || isReadonly())
3485 message(_("Autosaving current document..."));
3486 buf->d->bak_clean = true;
3488 FileName const fname = getAutosaveFileName();
3489 if (d->cloned_buffer_) {
3490 // If this buffer is cloned, we assume that
3491 // we are running in a separate thread already.
3492 FileName const tmp_ret = FileName::tempName("lyxauto");
3493 if (!tmp_ret.empty()) {
3495 // assume successful write of tmp_ret
3496 if (tmp_ret.moveTo(fname))
3499 // failed to write/rename tmp_ret so try writing direct
3500 return writeFile(fname);
3502 /// This function is deprecated as the frontend needs to take care
3503 /// of cloning the buffer and autosaving it in another thread. It
3504 /// is still here to allow (QT_VERSION < 0x040400).
3505 AutoSaveBuffer autosave(*this, fname);
3512 // helper class, to guarantee this gets reset properly
3513 class Buffer::MarkAsExporting {
3515 MarkAsExporting(Buffer const * buf) : buf_(buf)
3517 LASSERT(buf_, /* */);
3518 buf_->setExportStatus(true);
3522 buf_->setExportStatus(false);
3525 Buffer const * const buf_;
3530 void Buffer::setExportStatus(bool e) const
3532 d->doing_export = e;
3533 ListOfBuffers clist = getDescendents();
3534 ListOfBuffers::const_iterator cit = clist.begin();
3535 ListOfBuffers::const_iterator const cen = clist.end();
3536 for (; cit != cen; ++cit)
3537 (*cit)->d->doing_export = e;
3541 bool Buffer::isExporting() const
3543 return d->doing_export;
3547 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
3551 return doExport(target, put_in_tempdir, result_file);
3554 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3555 string & result_file) const
3557 bool const update_unincluded =
3558 params().maintain_unincluded_children
3559 && !params().getIncludedChildren().empty();
3561 // (1) export with all included children (omit \includeonly)
3562 if (update_unincluded) {
3563 ExportStatus const status =
3564 doExport(target, put_in_tempdir, true, result_file);
3565 if (status != ExportSuccess)
3568 // (2) export with included children only
3569 return doExport(target, put_in_tempdir, false, result_file);
3573 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3574 bool includeall, string & result_file) const
3576 LYXERR(Debug::FILES, "target=" << target);
3577 OutputParams runparams(¶ms().encoding());
3578 string format = target;
3579 string dest_filename;
3580 size_t pos = target.find(' ');
3581 if (pos != string::npos) {
3582 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
3583 format = target.substr(0, pos);
3584 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
3585 FileName(dest_filename).onlyPath().createPath();
3586 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
3588 MarkAsExporting exporting(this);
3589 string backend_format;
3590 runparams.flavor = OutputParams::LATEX;
3591 runparams.linelen = lyxrc.plaintext_linelen;
3592 runparams.includeall = includeall;
3593 vector<string> backs = params().backends();
3594 Converters converters = theConverters();
3595 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3596 // Get shortest path to format
3597 converters.buildGraph();
3598 Graph::EdgePath path;
3599 for (vector<string>::const_iterator it = backs.begin();
3600 it != backs.end(); ++it) {
3601 Graph::EdgePath p = converters.getPath(*it, format);
3602 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3603 backend_format = *it;
3608 if (!put_in_tempdir) {
3609 // Only show this alert if this is an export to a non-temporary
3610 // file (not for previewing).
3611 Alert::error(_("Couldn't export file"), bformat(
3612 _("No information for exporting the format %1$s."),
3613 formats.prettyName(format)));
3615 return ExportNoPathToFormat;
3617 runparams.flavor = converters.getFlavor(path);
3620 backend_format = format;
3621 LYXERR(Debug::FILES, "backend_format=" << backend_format);
3622 // FIXME: Don't hardcode format names here, but use a flag
3623 if (backend_format == "pdflatex")
3624 runparams.flavor = OutputParams::PDFLATEX;
3625 else if (backend_format == "luatex")
3626 runparams.flavor = OutputParams::LUATEX;
3627 else if (backend_format == "dviluatex")
3628 runparams.flavor = OutputParams::DVILUATEX;
3629 else if (backend_format == "xetex")
3630 runparams.flavor = OutputParams::XETEX;
3633 string filename = latexName(false);
3634 filename = addName(temppath(), filename);
3635 filename = changeExtension(filename,
3636 formats.extension(backend_format));
3637 LYXERR(Debug::FILES, "filename=" << filename);
3639 // Plain text backend
3640 if (backend_format == "text") {
3641 runparams.flavor = OutputParams::TEXT;
3642 writePlaintextFile(*this, FileName(filename), runparams);
3645 else if (backend_format == "xhtml") {
3646 runparams.flavor = OutputParams::HTML;
3647 switch (params().html_math_output) {
3648 case BufferParams::MathML:
3649 runparams.math_flavor = OutputParams::MathAsMathML;
3651 case BufferParams::HTML:
3652 runparams.math_flavor = OutputParams::MathAsHTML;
3654 case BufferParams::Images:
3655 runparams.math_flavor = OutputParams::MathAsImages;
3657 case BufferParams::LaTeX:
3658 runparams.math_flavor = OutputParams::MathAsLaTeX;
3661 makeLyXHTMLFile(FileName(filename), runparams);
3662 } else if (backend_format == "lyx")
3663 writeFile(FileName(filename));
3665 else if (params().isDocBook()) {
3666 runparams.nice = !put_in_tempdir;
3667 makeDocBookFile(FileName(filename), runparams);
3670 else if (backend_format == format) {
3671 runparams.nice = true;
3672 if (!makeLaTeXFile(FileName(filename), string(), runparams)) {
3673 if (d->cloned_buffer_) {
3674 d->cloned_buffer_->d->errorLists["Export"] =
3675 d->errorLists["Export"];
3679 } else if (!lyxrc.tex_allows_spaces
3680 && contains(filePath(), ' ')) {
3681 Alert::error(_("File name error"),
3682 _("The directory path to the document cannot contain spaces."));
3683 return ExportTexPathHasSpaces;
3685 runparams.nice = false;
3686 if (!makeLaTeXFile(FileName(filename), filePath(), runparams)) {
3687 if (d->cloned_buffer_) {
3688 d->cloned_buffer_->d->errorLists["Export"] =
3689 d->errorLists["Export"];
3695 string const error_type = (format == "program")
3696 ? "Build" : params().bufferFormat();
3697 ErrorList & error_list = d->errorLists[error_type];
3698 string const ext = formats.extension(format);
3699 FileName const tmp_result_file(changeExtension(filename, ext));
3700 bool const success = converters.convert(this, FileName(filename),
3701 tmp_result_file, FileName(absFileName()), backend_format, format,
3704 // Emit the signal to show the error list or copy it back to the
3705 // cloned Buffer so that it can be emitted afterwards.
3706 if (format != backend_format) {
3707 if (d->cloned_buffer_) {
3708 d->cloned_buffer_->d->errorLists[error_type] =
3709 d->errorLists[error_type];
3712 // also to the children, in case of master-buffer-view
3713 ListOfBuffers clist = getDescendents();
3714 ListOfBuffers::const_iterator cit = clist.begin();
3715 ListOfBuffers::const_iterator const cen = clist.end();
3716 for (; cit != cen; ++cit) {
3717 if (d->cloned_buffer_) {
3718 // Enable reverse search by copying back the
3719 // texrow object to the cloned buffer.
3720 // FIXME: this is not thread safe.
3721 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
3722 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
3723 (*cit)->d->errorLists[error_type];
3725 (*cit)->errors(error_type, true);
3729 if (d->cloned_buffer_) {
3730 // Enable reverse dvi or pdf to work by copying back the texrow
3731 // object to the cloned buffer.
3732 // FIXME: There is a possibility of concurrent access to texrow
3733 // here from the main GUI thread that should be securized.
3734 d->cloned_buffer_->d->texrow = d->texrow;
3735 string const error_type = params().bufferFormat();
3736 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
3740 return ExportConverterError;
3742 if (put_in_tempdir) {
3743 result_file = tmp_result_file.absFileName();
3744 return ExportSuccess;
3747 if (dest_filename.empty())
3748 result_file = changeExtension(d->exportFileName().absFileName(), ext);
3750 result_file = dest_filename;
3751 // We need to copy referenced files (e. g. included graphics
3752 // if format == "dvi") to the result dir.
3753 vector<ExportedFile> const files =
3754 runparams.exportdata->externalFiles(format);
3755 string const dest = runparams.export_folder.empty() ?
3756 onlyPath(result_file) : runparams.export_folder;
3757 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
3758 : force_overwrite == ALL_FILES;
3759 CopyStatus status = use_force ? FORCE : SUCCESS;
3761 vector<ExportedFile>::const_iterator it = files.begin();
3762 vector<ExportedFile>::const_iterator const en = files.end();
3763 for (; it != en && status != CANCEL; ++it) {
3764 string const fmt = formats.getFormatFromFile(it->sourceName);
3765 string fixedName = it->exportName;
3766 if (!runparams.export_folder.empty()) {
3767 // Relative pathnames starting with ../ will be sanitized
3768 // if exporting to a different folder
3769 while (fixedName.substr(0, 3) == "../")
3770 fixedName = fixedName.substr(3, fixedName.length() - 3);
3772 FileName fixedFileName = makeAbsPath(fixedName, dest);
3773 fixedFileName.onlyPath().createPath();
3774 status = copyFile(fmt, it->sourceName,
3776 it->exportName, status == FORCE,
3777 runparams.export_folder.empty());
3780 if (status == CANCEL) {
3781 message(_("Document export cancelled."));
3782 return ExportCancel;
3785 if (tmp_result_file.exists()) {
3786 // Finally copy the main file
3787 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
3788 : force_overwrite != NO_FILES;
3789 if (status == SUCCESS && use_force)
3791 status = copyFile(format, tmp_result_file,
3792 FileName(result_file), result_file,
3794 if (status == CANCEL) {
3795 message(_("Document export cancelled."));
3796 return ExportCancel;
3798 message(bformat(_("Document exported as %1$s "
3800 formats.prettyName(format),
3801 makeDisplayPath(result_file)));
3804 // This must be a dummy converter like fax (bug 1888)
3805 message(bformat(_("Document exported as %1$s"),
3806 formats.prettyName(format)));
3809 return ExportSuccess;
3813 Buffer::ExportStatus Buffer::preview(string const & format) const
3815 bool const update_unincluded =
3816 params().maintain_unincluded_children
3817 && !params().getIncludedChildren().empty();
3818 return preview(format, update_unincluded);
3821 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
3823 MarkAsExporting exporting(this);
3825 // (1) export with all included children (omit \includeonly)
3827 ExportStatus const status = doExport(format, true, true, result_file);
3828 if (status != ExportSuccess)
3831 // (2) export with included children only
3832 ExportStatus const status = doExport(format, true, false, result_file);
3833 if (status != ExportSuccess)
3835 if (!formats.view(*this, FileName(result_file), format))
3836 return PreviewError;
3837 return PreviewSuccess;
3841 Buffer::ReadStatus Buffer::extractFromVC()
3843 bool const found = LyXVC::file_not_found_hook(d->filename);
3845 return ReadFileNotFound;
3846 if (!d->filename.isReadableFile())
3852 Buffer::ReadStatus Buffer::loadEmergency()
3854 FileName const emergencyFile = getEmergencyFileName();
3855 if (!emergencyFile.exists()
3856 || emergencyFile.lastModified() <= d->filename.lastModified())
3857 return ReadFileNotFound;
3859 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
3860 docstring const text = bformat(_("An emergency save of the document "
3861 "%1$s exists.\n\nRecover emergency save?"), file);
3863 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
3864 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
3870 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
3871 bool const success = (ret_llf == ReadSuccess);
3874 Alert::warning(_("File is read-only"),
3875 bformat(_("An emergency file is successfully loaded, "
3876 "but the original file %1$s is marked read-only. "
3877 "Please make sure to save the document as a different "
3878 "file."), from_utf8(d->filename.absFileName())));
3881 str = _("Document was successfully recovered.");
3883 str = _("Document was NOT successfully recovered.");
3884 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3885 makeDisplayPath(emergencyFile.absFileName()));
3887 int const del_emerg =
3888 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3889 _("&Remove"), _("&Keep"));
3890 if (del_emerg == 0) {
3891 emergencyFile.removeFile();
3893 Alert::warning(_("Emergency file deleted"),
3894 _("Do not forget to save your file now!"), true);
3896 return success ? ReadSuccess : ReadEmergencyFailure;
3899 int const del_emerg =
3900 Alert::prompt(_("Delete emergency file?"),
3901 _("Remove emergency file now?"), 1, 1,
3902 _("&Remove"), _("&Keep"));
3904 emergencyFile.removeFile();
3905 return ReadOriginal;
3915 Buffer::ReadStatus Buffer::loadAutosave()
3917 // Now check if autosave file is newer.
3918 FileName const autosaveFile = getAutosaveFileName();
3919 if (!autosaveFile.exists()
3920 || autosaveFile.lastModified() <= d->filename.lastModified())
3921 return ReadFileNotFound;
3923 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
3924 docstring const text = bformat(_("The backup of the document %1$s "
3925 "is newer.\n\nLoad the backup instead?"), file);
3926 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
3927 _("&Load backup"), _("Load &original"), _("&Cancel"));
3932 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
3933 // the file is not saved if we load the autosave file.
3934 if (ret_llf == ReadSuccess) {
3936 Alert::warning(_("File is read-only"),
3937 bformat(_("A backup file is successfully loaded, "
3938 "but the original file %1$s is marked read-only. "
3939 "Please make sure to save the document as a "
3941 from_utf8(d->filename.absFileName())));
3946 return ReadAutosaveFailure;
3949 // Here we delete the autosave
3950 autosaveFile.removeFile();
3951 return ReadOriginal;
3959 Buffer::ReadStatus Buffer::loadLyXFile()
3961 if (!d->filename.isReadableFile()) {
3962 ReadStatus const ret_rvc = extractFromVC();
3963 if (ret_rvc != ReadSuccess)
3967 ReadStatus const ret_re = loadEmergency();
3968 if (ret_re == ReadSuccess || ret_re == ReadCancel)
3971 ReadStatus const ret_ra = loadAutosave();
3972 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
3975 return loadThisLyXFile(d->filename);
3979 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
3981 return readFile(fn);
3985 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3987 TeXErrors::Errors::const_iterator it = terr.begin();
3988 TeXErrors::Errors::const_iterator end = terr.end();
3989 ListOfBuffers clist = getDescendents();
3990 ListOfBuffers::const_iterator cen = clist.end();
3992 for (; it != end; ++it) {
3995 int errorRow = it->error_in_line;
3996 Buffer const * buf = 0;
3998 if (it->child_name.empty())
3999 p->texrow.getIdFromRow(errorRow, id_start, pos_start);
4001 // The error occurred in a child
4002 ListOfBuffers::const_iterator cit = clist.begin();
4003 for (; cit != cen; ++cit) {
4004 string const child_name =
4005 DocFileName(changeExtension(
4006 (*cit)->absFileName(), "tex")).
4008 if (it->child_name != child_name)
4010 (*cit)->d->texrow.getIdFromRow(errorRow,
4011 id_start, pos_start);
4012 if (id_start != -1) {
4013 buf = d->cloned_buffer_
4014 ? (*cit)->d->cloned_buffer_->d->owner_
4015 : (*cit)->d->owner_;
4026 found = p->texrow.getIdFromRow(errorRow, id_end, pos_end);
4027 } while (found && id_start == id_end && pos_start == pos_end);
4029 if (id_start != id_end) {
4030 // Next registered position is outside the inset where
4031 // the error occurred, so signal end-of-paragraph
4035 errorList.push_back(ErrorItem(it->error_desc,
4036 it->error_text, id_start, pos_start, pos_end, buf));
4041 void Buffer::setBuffersForInsets() const
4043 inset().setBuffer(const_cast<Buffer &>(*this));
4047 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4049 // Use the master text class also for child documents
4050 Buffer const * const master = masterBuffer();
4051 DocumentClass const & textclass = master->params().documentClass();
4053 // do this only if we are the top-level Buffer
4055 reloadBibInfoCache();
4057 // keep the buffers to be children in this set. If the call from the
4058 // master comes back we can see which of them were actually seen (i.e.
4059 // via an InsetInclude). The remaining ones in the set need still be updated.
4060 static std::set<Buffer const *> bufToUpdate;
4061 if (scope == UpdateMaster) {
4062 // If this is a child document start with the master
4063 if (master != this) {
4064 bufToUpdate.insert(this);
4065 master->updateBuffer(UpdateMaster, utype);
4066 // Do this here in case the master has no gui associated with it. Then,
4067 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
4068 if (!master->d->gui_)
4071 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4072 if (bufToUpdate.find(this) == bufToUpdate.end())
4076 // start over the counters in the master
4077 textclass.counters().reset();
4080 // update will be done below for this buffer
4081 bufToUpdate.erase(this);
4083 // update all caches
4084 clearReferenceCache();
4087 Buffer & cbuf = const_cast<Buffer &>(*this);
4089 LASSERT(!text().paragraphs().empty(), /**/);
4092 ParIterator parit = cbuf.par_iterator_begin();
4093 updateBuffer(parit, utype);
4096 // TocBackend update will be done later.
4099 d->bibinfo_cache_valid_ = true;
4100 d->cite_labels_valid_ = true;
4101 cbuf.tocBackend().update();
4102 if (scope == UpdateMaster)
4103 cbuf.structureChanged();
4107 static depth_type getDepth(DocIterator const & it)
4109 depth_type depth = 0;
4110 for (size_t i = 0 ; i < it.depth() ; ++i)
4111 if (!it[i].inset().inMathed())
4112 depth += it[i].paragraph().getDepth() + 1;
4113 // remove 1 since the outer inset does not count
4117 static depth_type getItemDepth(ParIterator const & it)
4119 Paragraph const & par = *it;
4120 LabelType const labeltype = par.layout().labeltype;
4122 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4125 // this will hold the lowest depth encountered up to now.
4126 depth_type min_depth = getDepth(it);
4127 ParIterator prev_it = it;
4130 --prev_it.top().pit();
4132 // start of nested inset: go to outer par
4134 if (prev_it.empty()) {
4135 // start of document: nothing to do
4140 // We search for the first paragraph with same label
4141 // that is not more deeply nested.
4142 Paragraph & prev_par = *prev_it;
4143 depth_type const prev_depth = getDepth(prev_it);
4144 if (labeltype == prev_par.layout().labeltype) {
4145 if (prev_depth < min_depth)
4146 return prev_par.itemdepth + 1;
4147 if (prev_depth == min_depth)
4148 return prev_par.itemdepth;
4150 min_depth = min(min_depth, prev_depth);
4151 // small optimization: if we are at depth 0, we won't
4152 // find anything else
4153 if (prev_depth == 0)
4159 static bool needEnumCounterReset(ParIterator const & it)
4161 Paragraph const & par = *it;
4162 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
4163 depth_type const cur_depth = par.getDepth();
4164 ParIterator prev_it = it;
4165 while (prev_it.pit()) {
4166 --prev_it.top().pit();
4167 Paragraph const & prev_par = *prev_it;
4168 if (prev_par.getDepth() <= cur_depth)
4169 return prev_par.layout().labeltype != LABEL_ENUMERATE;
4171 // start of nested inset: reset
4176 // set the label of a paragraph. This includes the counters.
4177 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4179 BufferParams const & bp = owner_->masterBuffer()->params();
4180 DocumentClass const & textclass = bp.documentClass();
4181 Paragraph & par = it.paragraph();
4182 Layout const & layout = par.layout();
4183 Counters & counters = textclass.counters();
4185 if (par.params().startOfAppendix()) {
4186 // FIXME: only the counter corresponding to toplevel
4187 // sectioning should be reset
4189 counters.appendix(true);
4191 par.params().appendix(counters.appendix());
4193 // Compute the item depth of the paragraph
4194 par.itemdepth = getItemDepth(it);
4196 if (layout.margintype == MARGIN_MANUAL) {
4197 if (par.params().labelWidthString().empty())
4198 par.params().labelWidthString(par.expandLabel(layout, bp));
4199 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4200 // we do not need to do anything here, since the empty case is
4201 // handled during export.
4203 par.params().labelWidthString(docstring());
4206 switch(layout.labeltype) {
4208 if (layout.toclevel <= bp.secnumdepth
4209 && (layout.latextype != LATEX_ENVIRONMENT
4210 || it.text()->isFirstInSequence(it.pit()))) {
4211 if (counters.hasCounter(layout.counter))
4212 counters.step(layout.counter, utype);
4213 par.params().labelString(par.expandLabel(layout, bp));
4215 par.params().labelString(docstring());
4218 case LABEL_ITEMIZE: {
4219 // At some point of time we should do something more
4220 // clever here, like:
4221 // par.params().labelString(
4222 // bp.user_defined_bullet(par.itemdepth).getText());
4223 // for now, use a simple hardcoded label
4224 docstring itemlabel;
4225 switch (par.itemdepth) {
4227 itemlabel = char_type(0x2022);
4230 itemlabel = char_type(0x2013);
4233 itemlabel = char_type(0x2217);
4236 itemlabel = char_type(0x2219); // or 0x00b7
4239 par.params().labelString(itemlabel);
4243 case LABEL_ENUMERATE: {
4244 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4246 switch (par.itemdepth) {
4255 enumcounter += "iv";
4258 // not a valid enumdepth...
4262 // Maybe we have to reset the enumeration counter.
4263 if (needEnumCounterReset(it))
4264 counters.reset(enumcounter);
4265 counters.step(enumcounter, utype);
4267 string const & lang = par.getParLanguage(bp)->code();
4268 par.params().labelString(counters.theCounter(enumcounter, lang));
4273 case LABEL_SENSITIVE: {
4274 string const & type = counters.current_float();
4275 docstring full_label;
4277 full_label = owner_->B_("Senseless!!! ");
4279 docstring name = owner_->B_(textclass.floats().getType(type).name());
4280 if (counters.hasCounter(from_utf8(type))) {
4281 string const & lang = par.getParLanguage(bp)->code();
4282 counters.step(from_utf8(type), utype);
4283 full_label = bformat(from_ascii("%1$s %2$s:"),
4285 counters.theCounter(from_utf8(type), lang));
4287 full_label = bformat(from_ascii("%1$s #:"), name);
4289 par.params().labelString(full_label);
4293 case LABEL_NO_LABEL:
4294 par.params().labelString(docstring());
4298 case LABEL_TOP_ENVIRONMENT:
4299 case LABEL_CENTERED_TOP_ENVIRONMENT:
4302 par.params().labelString(par.expandLabel(layout, bp));
4308 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4310 LASSERT(parit.pit() == 0, /**/);
4312 // Set the position of the text in the buffer to be able
4313 // to resolve macros in it.
4314 parit.text()->setMacrocontextPosition(parit);
4316 depth_type maxdepth = 0;
4317 pit_type const lastpit = parit.lastpit();
4318 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4319 // reduce depth if necessary
4320 parit->params().depth(min(parit->params().depth(), maxdepth));
4321 maxdepth = parit->getMaxDepthAfter();
4323 if (utype == OutputUpdate) {
4324 // track the active counters
4325 // we have to do this for the master buffer, since the local
4326 // buffer isn't tracking anything.
4327 masterBuffer()->params().documentClass().counters().
4328 setActiveLayout(parit->layout());
4331 // set the counter for this paragraph
4332 d->setLabel(parit, utype);
4335 InsetList::const_iterator iit = parit->insetList().begin();
4336 InsetList::const_iterator end = parit->insetList().end();
4337 for (; iit != end; ++iit) {
4338 parit.pos() = iit->pos;
4339 iit->inset->updateBuffer(parit, utype);
4345 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4346 WordLangTuple & word_lang, docstring_list & suggestions) const
4350 suggestions.clear();
4351 word_lang = WordLangTuple();
4352 bool const to_end = to.empty();
4353 DocIterator const end = to_end ? doc_iterator_end(this) : to;
4354 // OK, we start from here.
4355 for (; from != end; from.forwardPos()) {
4356 // We are only interested in text so remove the math CursorSlice.
4357 while (from.inMathed()) {
4361 // If from is at the end of the document (which is possible
4362 // when leaving the mathed) LyX will crash later otherwise.
4363 if (from.atEnd() || (!to_end && from >= end))
4366 from.paragraph().spellCheck();
4367 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4368 if (SpellChecker::misspelled(res)) {
4373 // Do not increase progress when from == to, otherwise the word
4374 // count will be wrong.
4384 Buffer::ReadStatus Buffer::reload()
4387 // c.f. bug http://www.lyx.org/trac/ticket/6587
4388 removeAutosaveFile();
4389 // e.g., read-only status could have changed due to version control
4390 d->filename.refresh();
4391 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4393 ReadStatus const status = loadLyXFile();
4394 if (status == ReadSuccess) {
4399 message(bformat(_("Document %1$s reloaded."), disp_fn));
4402 message(bformat(_("Could not reload document %1$s."), disp_fn));
4412 bool Buffer::saveAs(FileName const & fn)
4414 FileName const old_name = fileName();
4415 FileName const old_auto = getAutosaveFileName();
4416 bool const old_unnamed = isUnnamed();
4423 // bring the autosave file with us, just in case.
4424 moveAutosaveFile(old_auto);
4425 // validate version control data and
4426 // correct buffer title
4427 lyxvc().file_found_hook(fileName());
4429 // the file has now been saved to the new location.
4430 // we need to check that the locations of child buffers
4432 checkChildBuffers();
4436 // reset the old filename and unnamed state
4437 setFileName(old_name);
4438 setUnnamed(old_unnamed);
4444 // FIXME We could do better here, but it is complicated. What would be
4445 // nice is to offer either (a) to save the child buffer to an appropriate
4446 // location, so that it would "move with the master", or else (b) to update
4447 // the InsetInclude so that it pointed to the same file. But (a) is a bit
4448 // complicated, because the code for this lives in GuiView.
4449 void Buffer::checkChildBuffers()
4451 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4452 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4453 for (; it != en; ++it) {
4454 DocIterator dit = it->second;
4455 Buffer * cbuf = const_cast<Buffer *>(it->first);
4456 if (!cbuf || !theBufferList().isLoaded(cbuf))
4458 Inset * inset = dit.nextInset();
4459 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4460 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4461 docstring const & incfile = inset_inc->getParam("filename");
4462 string oldloc = cbuf->absFileName();
4463 string newloc = makeAbsPath(to_utf8(incfile),
4464 onlyPath(absFileName())).absFileName();
4465 if (oldloc == newloc)
4467 // the location of the child file is incorrect.
4468 Alert::warning(_("Included File Invalid"),
4469 bformat(_("Saving this document to a new location has made the file:\n"
4471 "inaccessible. You will need to update the included filename."),
4472 from_utf8(oldloc)));
4474 inset_inc->setChildBuffer(0);
4476 // invalidate cache of children
4477 d->children_positions.clear();
4478 d->position_to_children.clear();