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"
28 #include "CutAndPaste.h"
29 #include "DispatchResult.h"
30 #include "DocIterator.h"
31 #include "BufferEncodings.h"
32 #include "ErrorList.h"
35 #include "FuncRequest.h"
36 #include "FuncStatus.h"
37 #include "IndicesList.h"
38 #include "InsetIterator.h"
39 #include "InsetList.h"
41 #include "LaTeXFeatures.h"
45 #include "LyXAction.h"
49 #include "output_docbook.h"
51 #include "output_latex.h"
52 #include "output_xhtml.h"
53 #include "output_plaintext.h"
54 #include "Paragraph.h"
55 #include "ParagraphParameters.h"
56 #include "ParIterator.h"
57 #include "PDFOptions.h"
58 #include "SpellChecker.h"
62 #include "TextClass.h"
63 #include "TocBackend.h"
65 #include "VCBackend.h"
67 #include "WordLangTuple.h"
70 #include "insets/InsetBibtex.h"
71 #include "insets/InsetBranch.h"
72 #include "insets/InsetInclude.h"
73 #include "insets/InsetTabular.h"
74 #include "insets/InsetText.h"
76 #include "mathed/InsetMathHull.h"
77 #include "mathed/MacroTable.h"
78 #include "mathed/MathMacroTemplate.h"
79 #include "mathed/MathSupport.h"
81 #include "graphics/PreviewLoader.h"
83 #include "frontends/alert.h"
84 #include "frontends/Delegates.h"
85 #include "frontends/WorkAreaManager.h"
87 #include "support/lassert.h"
88 #include "support/convert.h"
89 #include "support/debug.h"
90 #include "support/docstring_list.h"
91 #include "support/ExceptionMessage.h"
92 #include "support/FileName.h"
93 #include "support/FileNameList.h"
94 #include "support/filetools.h"
95 #include "support/ForkedCalls.h"
96 #include "support/gettext.h"
97 #include "support/gzstream.h"
98 #include "support/lstrings.h"
99 #include "support/lyxalgo.h"
100 #include "support/mutex.h"
101 #include "support/os.h"
102 #include "support/Package.h"
103 #include "support/PathChanger.h"
104 #include "support/Systemcall.h"
105 #include "support/TempFile.h"
106 #include "support/textutils.h"
107 #include "support/types.h"
109 #include "support/bind.h"
110 #include "support/shared_ptr.h"
121 using namespace lyx::support;
122 using namespace lyx::graphics;
126 namespace Alert = frontend::Alert;
127 namespace os = support::os;
131 int const LYX_FORMAT = LYX_FORMAT_LYX;
133 typedef map<string, bool> DepClean;
134 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
136 void showPrintError(string const & name)
138 docstring str = bformat(_("Could not print the document %1$s.\n"
139 "Check that your printer is set up correctly."),
140 makeDisplayPath(name, 50));
141 Alert::error(_("Print document failed"), str);
147 // A storehouse for the cloned buffers.
148 list<CloneList *> cloned_buffers;
154 Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
158 delete preview_loader_;
166 /// search for macro in local (buffer) table or in children
167 MacroData const * getBufferMacro(docstring const & name,
168 DocIterator const & pos) const;
170 /// Update macro table starting with position of it \param it in some
172 void updateMacros(DocIterator & it, DocIterator & scope);
174 void setLabel(ParIterator & it, UpdateType utype) const;
176 /** If we have branches that use the file suffix
177 feature, return the file name with suffix appended.
179 support::FileName exportFileName() const;
186 mutable TexRow texrow;
188 /// need to regenerate .tex?
192 mutable bool lyx_clean;
194 /// is autosave needed?
195 mutable bool bak_clean;
197 /// is this an unnamed file (New...)?
200 /// is this an internal bufffer?
201 bool internal_buffer;
206 /// name of the file the buffer is associated with.
209 /** Set to true only when the file is fully loaded.
210 * Used to prevent the premature generation of previews
211 * and by the citation inset.
213 bool file_fully_loaded;
215 /// Ignore the parent (e.g. when exporting a child standalone)?
219 mutable TocBackend toc_backend;
222 typedef pair<DocIterator, MacroData> ScopeMacro;
223 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
224 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
225 /// map from the macro name to the position map,
226 /// which maps the macro definition position to the scope and the MacroData.
227 NamePositionScopeMacroMap macros;
228 /// This seem to change the way Buffer::getMacro() works
229 mutable bool macro_lock;
231 /// positions of child buffers in the buffer
232 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
233 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
234 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
235 /// position of children buffers in this buffer
236 BufferPositionMap children_positions;
237 /// map from children inclusion positions to their scope and their buffer
238 PositionScopeBufferMap position_to_children;
240 /// Container for all sort of Buffer dependant errors.
241 map<string, ErrorList> errorLists;
243 /// timestamp and checksum used to test if the file has been externally
244 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
246 unsigned long checksum_;
249 frontend::WorkAreaManager * wa_;
251 frontend::GuiBufferDelegate * gui_;
256 /// A cache for the bibfiles (including bibfiles of loaded child
257 /// documents), needed for appropriate update of natbib labels.
258 mutable support::FileNameList bibfiles_cache_;
260 // FIXME The caching mechanism could be improved. At present, we have a
261 // cache for each Buffer, that caches all the bibliography info for that
262 // Buffer. A more efficient solution would be to have a global cache per
263 // file, and then to construct the Buffer's bibinfo from that.
264 /// A cache for bibliography info
265 mutable BiblioInfo bibinfo_;
266 /// whether the bibinfo cache is valid
267 mutable bool bibinfo_cache_valid_;
268 /// whether the bibfile cache is valid
269 mutable bool bibfile_cache_valid_;
270 /// Cache of timestamps of .bib files
271 map<FileName, time_t> bibfile_status_;
272 /// Indicates whether the bibinfo has changed since the last time
273 /// we ran updateBuffer(), i.e., whether citation labels may need
275 mutable bool cite_labels_valid_;
277 mutable RefCache ref_cache_;
279 /// our Text that should be wrapped in an InsetText
283 PreviewLoader * preview_loader_;
285 /// This is here to force the test to be done whenever parent_buffer
287 Buffer const * parent() const
289 // ignore_parent temporarily "orphans" a buffer
290 // (e.g. if a child is compiled standalone)
293 // if parent_buffer is not loaded, then it has been unloaded,
294 // which means that parent_buffer is an invalid pointer. So we
295 // set it to null in that case.
296 // however, the BufferList doesn't know about cloned buffers, so
297 // they will always be regarded as unloaded. in that case, we hope
299 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
301 return parent_buffer;
305 void setParent(Buffer const * pb)
307 if (parent_buffer == pb)
310 if (!cloned_buffer_ && parent_buffer && pb)
311 LYXERR0("Warning: a buffer should not have two parents!");
313 if (!cloned_buffer_ && parent_buffer) {
314 parent_buffer->invalidateBibfileCache();
315 parent_buffer->invalidateBibinfoCache();
319 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
320 /// This one is useful for preview detached in a thread.
321 Buffer const * cloned_buffer_;
323 CloneList * clone_list_;
324 /// are we in the process of exporting this buffer?
325 mutable bool doing_export;
327 /// compute statistics
328 /// \p from initial position
329 /// \p to points to the end position
330 void updateStatistics(DocIterator & from, DocIterator & to,
331 bool skipNoOutput = true);
332 /// statistics accessor functions
333 int wordCount() const
337 int charCount(bool with_blanks) const
340 + (with_blanks ? blank_count_ : 0);
344 /// So we can force access via the accessors.
345 mutable Buffer const * parent_buffer;
354 /// Creates the per buffer temporary directory
355 static FileName createBufferTmpDir()
357 // FIXME This would be the ideal application for a TempDir class (like
358 // TempFile but for directories)
363 Mutex::Locker locker(&mutex);
364 counter = convert<string>(count++);
366 // We are in our own directory. Why bother to mangle name?
367 // In fact I wrote this code to circumvent a problematic behaviour
368 // (bug?) of EMX mkstemp().
369 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
372 if (!tmpfl.createDirectory(0777)) {
373 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
374 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
375 from_utf8(tmpfl.absFileName())));
381 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
382 Buffer const * cloned_buffer)
383 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
384 internal_buffer(false), read_only(readonly_), filename(file),
385 file_fully_loaded(false), ignore_parent(false), toc_backend(owner),
386 macro_lock(false), timestamp_(0), checksum_(0), wa_(0), gui_(0),
387 undo_(*owner), bibinfo_cache_valid_(false), bibfile_cache_valid_(false),
388 cite_labels_valid_(false), preview_loader_(0),
389 cloned_buffer_(cloned_buffer), clone_list_(0),
390 doing_export(false), parent_buffer(0)
392 if (!cloned_buffer_) {
393 temppath = createBufferTmpDir();
394 lyxvc.setBuffer(owner_);
396 wa_ = new frontend::WorkAreaManager;
399 temppath = cloned_buffer_->d->temppath;
400 file_fully_loaded = true;
401 params = cloned_buffer_->d->params;
402 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
403 bibinfo_ = cloned_buffer_->d->bibinfo_;
404 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
405 bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
406 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
407 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
408 unnamed = cloned_buffer_->d->unnamed;
409 internal_buffer = cloned_buffer_->d->internal_buffer;
413 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
414 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
416 LYXERR(Debug::INFO, "Buffer::Buffer()");
418 d->inset = new InsetText(*cloned_buffer->d->inset);
419 d->inset->setBuffer(*this);
420 // FIXME: optimize this loop somewhat, maybe by creating a new
421 // general recursive Inset::setId().
422 DocIterator it = doc_iterator_begin(this);
423 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
424 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
425 it.paragraph().setId(cloned_it.paragraph().id());
427 d->inset = new InsetText(this);
428 d->inset->setAutoBreakRows(true);
429 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
435 LYXERR(Debug::INFO, "Buffer::~Buffer()");
436 // here the buffer should take care that it is
437 // saved properly, before it goes into the void.
439 // GuiView already destroyed
443 // No need to do additional cleanups for internal buffer.
449 // this is in case of recursive includes: we won't try to delete
450 // ourselves as a child.
451 d->clone_list_->erase(this);
452 // loop over children
453 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
454 Impl::BufferPositionMap::iterator end = d->children_positions.end();
455 for (; it != end; ++it) {
456 Buffer * child = const_cast<Buffer *>(it->first);
457 if (d->clone_list_->erase(child))
460 // if we're the master buffer, then we should get rid of the list
463 // If this is not empty, we have leaked something. Worse, one of the
464 // children still has a reference to this list. But we will try to
465 // continue, rather than shut down.
466 LATTEST(d->clone_list_->empty());
467 list<CloneList *>::iterator it =
468 find(cloned_buffers.begin(), cloned_buffers.end(), d->clone_list_);
469 if (it == cloned_buffers.end()) {
470 // We will leak in this case, but it is safe to continue.
473 cloned_buffers.erase(it);
474 delete d->clone_list_;
476 // FIXME Do we really need to do this right before we delete d?
477 // clear references to children in macro tables
478 d->children_positions.clear();
479 d->position_to_children.clear();
481 // loop over children
482 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
483 Impl::BufferPositionMap::iterator end = d->children_positions.end();
484 for (; it != end; ++it) {
485 Buffer * child = const_cast<Buffer *>(it->first);
486 if (theBufferList().isLoaded(child))
487 theBufferList().releaseChild(this, child);
491 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
492 msg += emergencyWrite();
493 Alert::warning(_("Attempting to close changed document!"), msg);
496 // FIXME Do we really need to do this right before we delete d?
497 // clear references to children in macro tables
498 d->children_positions.clear();
499 d->position_to_children.clear();
501 if (!d->temppath.destroyDirectory()) {
502 Alert::warning(_("Could not remove temporary directory"),
503 bformat(_("Could not remove the temporary directory %1$s"),
504 from_utf8(d->temppath.absFileName())));
513 Buffer * Buffer::cloneFromMaster() const
516 cloned_buffers.push_back(new CloneList);
517 CloneList * clones = cloned_buffers.back();
519 masterBuffer()->cloneWithChildren(bufmap, clones);
521 // make sure we got cloned
522 BufferMap::const_iterator bit = bufmap.find(this);
523 LASSERT(bit != bufmap.end(), return 0);
524 Buffer * cloned_buffer = bit->second;
526 return cloned_buffer;
530 void Buffer::cloneWithChildren(BufferMap & bufmap, CloneList * clones) const
532 // have we already been cloned?
533 if (bufmap.find(this) != bufmap.end())
536 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
538 // The clone needs its own DocumentClass, since running updateBuffer() will
539 // modify it, and we would otherwise be sharing it with the original Buffer.
540 buffer_clone->params().makeDocumentClass(true);
542 cap::switchBetweenClasses(
543 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
544 static_cast<InsetText &>(buffer_clone->inset()), el);
546 bufmap[this] = buffer_clone;
547 clones->insert(buffer_clone);
548 buffer_clone->d->clone_list_ = clones;
549 buffer_clone->d->macro_lock = true;
550 buffer_clone->d->children_positions.clear();
552 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
553 // math macro caches need to be rethought and simplified.
554 // I am not sure wether we should handle Buffer cloning here or in BufferList.
555 // Right now BufferList knows nothing about buffer clones.
556 Impl::PositionScopeBufferMap::iterator it = d->position_to_children.begin();
557 Impl::PositionScopeBufferMap::iterator end = d->position_to_children.end();
558 for (; it != end; ++it) {
559 DocIterator dit = it->first.clone(buffer_clone);
560 dit.setBuffer(buffer_clone);
561 Buffer * child = const_cast<Buffer *>(it->second.second);
563 child->cloneWithChildren(bufmap, clones);
564 BufferMap::iterator const bit = bufmap.find(child);
565 LASSERT(bit != bufmap.end(), continue);
566 Buffer * child_clone = bit->second;
568 Inset * inset = dit.nextInset();
569 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
570 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
571 inset_inc->setChildBuffer(child_clone);
572 child_clone->d->setParent(buffer_clone);
573 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
574 buffer_clone->setChild(dit, child_clone);
576 buffer_clone->d->macro_lock = false;
581 Buffer * Buffer::cloneBufferOnly() const {
582 cloned_buffers.push_back(new CloneList);
583 CloneList * clones = cloned_buffers.back();
584 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
586 // The clone needs its own DocumentClass, since running updateBuffer() will
587 // modify it, and we would otherwise be sharing it with the original Buffer.
588 buffer_clone->params().makeDocumentClass(true);
590 cap::switchBetweenClasses(
591 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
592 static_cast<InsetText &>(buffer_clone->inset()), el);
594 clones->insert(buffer_clone);
595 buffer_clone->d->clone_list_ = clones;
597 // we won't be cloning the children
598 buffer_clone->d->children_positions.clear();
603 bool Buffer::isClone() const
605 return d->cloned_buffer_;
609 void Buffer::changed(bool update_metrics) const
612 d->wa_->redrawAll(update_metrics);
616 frontend::WorkAreaManager & Buffer::workAreaManager() const
623 Text & Buffer::text() const
625 return d->inset->text();
629 Inset & Buffer::inset() const
635 BufferParams & Buffer::params()
641 BufferParams const & Buffer::params() const
647 BufferParams const & Buffer::masterParams() const
649 if (masterBuffer() == this)
652 BufferParams & mparams = const_cast<Buffer *>(masterBuffer())->params();
653 // Copy child authors to the params. We need those pointers.
654 AuthorList const & child_authors = params().authors();
655 AuthorList::Authors::const_iterator it = child_authors.begin();
656 for (; it != child_authors.end(); ++it)
657 mparams.authors().record(*it);
662 ParagraphList & Buffer::paragraphs()
664 return text().paragraphs();
668 ParagraphList const & Buffer::paragraphs() const
670 return text().paragraphs();
674 LyXVC & Buffer::lyxvc()
680 LyXVC const & Buffer::lyxvc() const
686 string const Buffer::temppath() const
688 return d->temppath.absFileName();
692 TexRow & Buffer::texrow()
698 TexRow const & Buffer::texrow() const
704 TocBackend & Buffer::tocBackend() const
706 return d->toc_backend;
710 Undo & Buffer::undo()
716 void Buffer::setChild(DocIterator const & dit, Buffer * child)
718 d->children_positions[child] = dit;
722 string Buffer::latexName(bool const no_path) const
724 FileName latex_name =
725 makeLatexName(d->exportFileName());
726 return no_path ? latex_name.onlyFileName()
727 : latex_name.absFileName();
731 FileName Buffer::Impl::exportFileName() const
733 docstring const branch_suffix =
734 params.branchlist().getFileNameSuffix();
735 if (branch_suffix.empty())
738 string const name = filename.onlyFileNameWithoutExt()
739 + to_utf8(branch_suffix);
740 FileName res(filename.onlyPath().absFileName() + "/" + name);
741 res.changeExtension(filename.extension());
747 string Buffer::logName(LogType * type) const
749 string const filename = latexName(false);
751 if (filename.empty()) {
757 string const path = temppath();
759 FileName const fname(addName(temppath(),
760 onlyFileName(changeExtension(filename,
763 // FIXME: how do we know this is the name of the build log?
764 FileName const bname(
765 addName(path, onlyFileName(
766 changeExtension(filename,
767 formats.extension(params().bufferFormat()) + ".out"))));
769 // Also consider the master buffer log file
770 FileName masterfname = fname;
772 if (masterBuffer() != this) {
773 string const mlogfile = masterBuffer()->logName(&mtype);
774 masterfname = FileName(mlogfile);
777 // If no Latex log or Build log is newer, show Build log
778 if (bname.exists() &&
779 ((!fname.exists() && !masterfname.exists())
780 || (fname.lastModified() < bname.lastModified()
781 && masterfname.lastModified() < bname.lastModified()))) {
782 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
785 return bname.absFileName();
786 // If we have a newer master file log or only a master log, show this
787 } else if (fname != masterfname
788 && (!fname.exists() && (masterfname.exists()
789 || fname.lastModified() < masterfname.lastModified()))) {
790 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
793 return masterfname.absFileName();
795 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
798 return fname.absFileName();
802 void Buffer::setReadonly(bool const flag)
804 if (d->read_only != flag) {
811 void Buffer::setFileName(FileName const & fname)
813 bool const changed = fname != d->filename;
816 lyxvc().file_found_hook(fname);
817 setReadonly(d->filename.isReadOnly());
823 int Buffer::readHeader(Lexer & lex)
825 int unknown_tokens = 0;
827 int begin_header_line = -1;
829 // Initialize parameters that may be/go lacking in header:
830 params().branchlist().clear();
831 params().preamble.erase();
832 params().options.erase();
833 params().master.erase();
834 params().float_placement.erase();
835 params().paperwidth.erase();
836 params().paperheight.erase();
837 params().leftmargin.erase();
838 params().rightmargin.erase();
839 params().topmargin.erase();
840 params().bottommargin.erase();
841 params().headheight.erase();
842 params().headsep.erase();
843 params().footskip.erase();
844 params().columnsep.erase();
845 params().fonts_cjk.erase();
846 params().listings_params.clear();
847 params().clearLayoutModules();
848 params().clearRemovedModules();
849 params().clearIncludedChildren();
850 params().pdfoptions().clear();
851 params().indiceslist().clear();
852 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
853 params().isbackgroundcolor = false;
854 params().fontcolor = RGBColor(0, 0, 0);
855 params().isfontcolor = false;
856 params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
857 params().boxbgcolor = RGBColor(0xFF, 0, 0);
858 params().html_latex_start.clear();
859 params().html_latex_end.clear();
860 params().html_math_img_scale = 1.0;
861 params().output_sync_macro.erase();
862 params().setLocalLayout(string(), false);
863 params().setLocalLayout(string(), true);
865 for (int i = 0; i < 4; ++i) {
866 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
867 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
870 ErrorList & errorList = d->errorLists["Parse"];
879 if (token == "\\end_header")
883 if (token == "\\begin_header") {
884 begin_header_line = line;
888 LYXERR(Debug::PARSER, "Handling document header token: `"
891 string unknown = params().readToken(lex, token, d->filename.onlyPath());
892 if (!unknown.empty()) {
893 if (unknown[0] != '\\' && token == "\\textclass") {
894 Alert::warning(_("Unknown document class"),
895 bformat(_("Using the default document class, because the "
896 "class %1$s is unknown."), from_utf8(unknown)));
899 docstring const s = bformat(_("Unknown token: "
903 errorList.push_back(ErrorItem(_("Document header error"),
908 if (begin_header_line) {
909 docstring const s = _("\\begin_header is missing");
910 errorList.push_back(ErrorItem(_("Document header error"),
914 params().makeDocumentClass();
916 return unknown_tokens;
921 // changed to be public and have one parameter
922 // Returns true if "\end_document" is not read (Asger)
923 bool Buffer::readDocument(Lexer & lex)
925 ErrorList & errorList = d->errorLists["Parse"];
928 // remove dummy empty par
929 paragraphs().clear();
931 if (!lex.checkFor("\\begin_document")) {
932 docstring const s = _("\\begin_document is missing");
933 errorList.push_back(ErrorItem(_("Document header error"),
939 if (params().output_changes) {
940 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
941 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
942 LaTeXFeatures::isAvailable("xcolor");
944 if (!dvipost && !xcolorulem) {
945 Alert::warning(_("Changes not shown in LaTeX output"),
946 _("Changes will not be highlighted in LaTeX output, "
947 "because neither dvipost nor xcolor/ulem are installed.\n"
948 "Please install these packages or redefine "
949 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
950 } else if (!xcolorulem) {
951 Alert::warning(_("Changes not shown in LaTeX output"),
952 _("Changes will not be highlighted in LaTeX output "
953 "when using pdflatex, because xcolor and ulem are not installed.\n"
954 "Please install both packages or redefine "
955 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
959 if (!parent() && !params().master.empty()) {
960 FileName const master_file = makeAbsPath(params().master,
961 onlyPath(absFileName()));
962 if (isLyXFileName(master_file.absFileName())) {
964 checkAndLoadLyXFile(master_file, true);
966 // necessary e.g. after a reload
967 // to re-register the child (bug 5873)
968 // FIXME: clean up updateMacros (here, only
969 // child registering is needed).
970 master->updateMacros();
971 // set master as master buffer, but only
972 // if we are a real child
973 if (master->isChild(this))
975 // if the master is not fully loaded
976 // it is probably just loading this
977 // child. No warning needed then.
978 else if (master->isFullyLoaded())
979 LYXERR0("The master '"
981 << "' assigned to this document ("
983 << ") does not include "
984 "this document. Ignoring the master assignment.");
989 // assure we have a default index
990 params().indiceslist().addDefault(B_("Index"));
993 bool const res = text().read(lex, errorList, d->inset);
995 // inform parent buffer about local macros
997 Buffer const * pbuf = parent();
998 UserMacroSet::const_iterator cit = usermacros.begin();
999 UserMacroSet::const_iterator end = usermacros.end();
1000 for (; cit != end; ++cit)
1001 pbuf->usermacros.insert(*cit);
1005 updateMacroInstances(InternalUpdate);
1010 bool Buffer::importString(string const & format, docstring const & contents, ErrorList & errorList)
1012 Format const * fmt = formats.getFormat(format);
1015 // It is important to use the correct extension here, since some
1016 // converters create a wrong output file otherwise (e.g. html2latex)
1017 TempFile const tempfile("Buffer_importStringXXXXXX." + fmt->extension());
1018 FileName const name(tempfile.name());
1019 ofdocstream os(name.toFilesystemEncoding().c_str());
1020 // Do not convert os implicitly to bool, since that is forbidden in C++11.
1021 bool const success = !(os << contents).fail();
1024 bool converted = false;
1026 params().compressed = false;
1028 // remove dummy empty par
1029 paragraphs().clear();
1031 converted = importFile(format, name, errorList);
1040 bool Buffer::importFile(string const & format, FileName const & name, ErrorList & errorList)
1042 if (!theConverters().isReachable(format, "lyx"))
1045 TempFile const tempfile("Buffer_importFileXXXXXX.lyx");
1046 FileName const lyx(tempfile.name());
1047 if (theConverters().convert(0, name, lyx, name, format, "lyx", errorList))
1048 return readFile(lyx) == ReadSuccess;
1054 bool Buffer::readString(string const & s)
1056 params().compressed = false;
1059 istringstream is(s);
1061 TempFile tempfile("Buffer_readStringXXXXXX.lyx");
1062 FileName const fn = tempfile.name();
1065 bool success = parseLyXFormat(lex, fn, file_format) == ReadSuccess;
1067 if (success && file_format != LYX_FORMAT) {
1068 // We need to call lyx2lyx, so write the input to a file
1069 ofstream os(fn.toFilesystemEncoding().c_str());
1072 // lyxvc in readFile
1073 if (readFile(fn) != ReadSuccess)
1077 if (readDocument(lex))
1083 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
1087 if (!lex.setFile(fname)) {
1088 Alert::error(_("File Not Found"),
1089 bformat(_("Unable to open file `%1$s'."),
1090 from_utf8(fn.absFileName())));
1091 return ReadFileNotFound;
1095 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
1096 if (ret_plf != ReadSuccess)
1099 if (file_format != LYX_FORMAT) {
1101 ReadStatus const ret_clf = convertLyXFormat(fn, tmpFile, file_format);
1102 if (ret_clf != ReadSuccess)
1104 return readFile(tmpFile);
1107 // FIXME: InsetInfo needs to know whether the file is under VCS
1108 // during the parse process, so this has to be done before.
1109 lyxvc().file_found_hook(d->filename);
1111 if (readDocument(lex)) {
1112 Alert::error(_("Document format failure"),
1113 bformat(_("%1$s ended unexpectedly, which means"
1114 " that it is probably corrupted."),
1115 from_utf8(fn.absFileName())));
1116 return ReadDocumentFailure;
1119 d->file_fully_loaded = true;
1120 d->read_only = !d->filename.isWritable();
1121 params().compressed = formats.isZippedFile(d->filename);
1127 bool Buffer::isFullyLoaded() const
1129 return d->file_fully_loaded;
1133 void Buffer::setFullyLoaded(bool value)
1135 d->file_fully_loaded = value;
1139 PreviewLoader * Buffer::loader() const
1141 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1143 if (!d->preview_loader_)
1144 d->preview_loader_ = new PreviewLoader(*this);
1145 return d->preview_loader_;
1149 void Buffer::removePreviews() const
1151 delete d->preview_loader_;
1152 d->preview_loader_ = 0;
1156 void Buffer::updatePreviews() const
1158 PreviewLoader * ploader = loader();
1162 InsetIterator it = inset_iterator_begin(*d->inset);
1163 InsetIterator const end = inset_iterator_end(*d->inset);
1164 for (; it != end; ++it)
1165 it->addPreview(it, *ploader);
1167 ploader->startLoading();
1171 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1172 FileName const & fn, int & file_format) const
1174 if(!lex.checkFor("\\lyxformat")) {
1175 Alert::error(_("Document format failure"),
1176 bformat(_("%1$s is not a readable LyX document."),
1177 from_utf8(fn.absFileName())));
1178 return ReadNoLyXFormat;
1184 // LyX formats 217 and earlier were written as 2.17. This corresponds
1185 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1186 // these cases. See also: www.lyx.org/trac/changeset/1313.
1187 size_t dot = tmp_format.find_first_of(".,");
1188 if (dot != string::npos)
1189 tmp_format.erase(dot, 1);
1191 file_format = convert<int>(tmp_format);
1196 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1197 FileName & tmpfile, int from_format)
1199 TempFile tempfile("Buffer_convertLyXFormatXXXXXX.lyx");
1200 tempfile.setAutoRemove(false);
1201 tmpfile = tempfile.name();
1202 if(tmpfile.empty()) {
1203 Alert::error(_("Conversion failed"),
1204 bformat(_("%1$s is from a different"
1205 " version of LyX, but a temporary"
1206 " file for converting it could"
1207 " not be created."),
1208 from_utf8(fn.absFileName())));
1209 return LyX2LyXNoTempFile;
1212 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1213 if (lyx2lyx.empty()) {
1214 Alert::error(_("Conversion script not found"),
1215 bformat(_("%1$s is from a different"
1216 " version of LyX, but the"
1217 " conversion script lyx2lyx"
1218 " could not be found."),
1219 from_utf8(fn.absFileName())));
1220 return LyX2LyXNotFound;
1224 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1225 ostringstream command;
1226 command << os::python()
1227 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1228 << " -t " << convert<string>(LYX_FORMAT)
1229 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
1230 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1231 string const command_str = command.str();
1233 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1235 cmd_ret const ret = runCommand(command_str);
1236 if (ret.first != 0) {
1237 if (from_format < LYX_FORMAT) {
1238 Alert::error(_("Conversion script failed"),
1239 bformat(_("%1$s is from an older version"
1240 " of LyX and the lyx2lyx script"
1241 " failed to convert it."),
1242 from_utf8(fn.absFileName())));
1243 return LyX2LyXOlderFormat;
1245 Alert::error(_("Conversion script failed"),
1246 bformat(_("%1$s is from a newer version"
1247 " of LyX and the lyx2lyx script"
1248 " failed to convert it."),
1249 from_utf8(fn.absFileName())));
1250 return LyX2LyXNewerFormat;
1257 // Should probably be moved to somewhere else: BufferView? GuiView?
1258 bool Buffer::save() const
1260 docstring const file = makeDisplayPath(absFileName(), 20);
1261 d->filename.refresh();
1263 // check the read-only status before moving the file as a backup
1264 if (d->filename.exists()) {
1265 bool const read_only = !d->filename.isWritable();
1267 Alert::warning(_("File is read-only"),
1268 bformat(_("The file %1$s cannot be written because it "
1269 "is marked as read-only."), file));
1274 // ask if the disk file has been externally modified (use checksum method)
1275 if (fileName().exists() && isExternallyModified(checksum_method)) {
1277 bformat(_("Document %1$s has been externally modified. "
1278 "Are you sure you want to overwrite this file?"), file);
1279 int const ret = Alert::prompt(_("Overwrite modified file?"),
1280 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1285 // We don't need autosaves in the immediate future. (Asger)
1286 resetAutosaveTimers();
1288 // if the file does not yet exist, none of the backup activity
1289 // that follows is necessary
1290 if (!fileName().exists())
1291 return writeFile(fileName());
1293 // we first write the file to a new name, then move it to its
1294 // proper location once that has been done successfully. that
1295 // way we preserve the original file if something goes wrong.
1296 TempFile tempfile(fileName().onlyPath(), "tmpXXXXXX.lyx");
1297 FileName savefile(tempfile.name());
1299 LYXERR(Debug::FILES, "Saving to " << savefile.absFileName());
1300 if (!writeFile(savefile))
1303 // we will set this to false if we fail
1304 bool made_backup = true;
1305 bool const symlink = fileName().isSymLink();
1306 if (lyxrc.make_backup) {
1307 FileName backupName(absFileName() + '~');
1308 if (!lyxrc.backupdir_path.empty()) {
1309 string const mangledName =
1310 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1311 backupName = FileName(addName(lyxrc.backupdir_path,
1315 // Except file is symlink do not copy because of #6587.
1316 // Hard links have bad luck.
1317 made_backup = symlink ?
1318 fileName().copyTo(backupName):
1319 fileName().moveTo(backupName);
1322 Alert::error(_("Backup failure"),
1323 bformat(_("Cannot create backup file %1$s.\n"
1324 "Please check whether the directory exists and is writable."),
1325 from_utf8(backupName.absFileName())));
1326 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1330 // If we have no symlink, we can simply rename the temp file.
1331 // Otherwise, we need to copy it so the symlink stays intact.
1333 tempfile.setAutoRemove(false);
1335 (symlink ? savefile.copyTo(fileName(), true) : savefile.moveTo(fileName()))) {
1336 // saveCheckSum() was already called by writeFile(), but the
1337 // time stamp is invalidated by copying/moving
1343 Alert::error(_("Write failure"),
1344 bformat(_("Cannot move saved file to:\n %1$s.\n"
1345 "But the file has successfully been saved as:\n %2$s."),
1346 from_utf8(fileName().absFileName()),
1347 from_utf8(savefile.absFileName())));
1352 bool Buffer::writeFile(FileName const & fname) const
1354 if (d->read_only && fname == d->filename)
1357 bool retval = false;
1359 docstring const str = bformat(_("Saving document %1$s..."),
1360 makeDisplayPath(fname.absFileName()));
1363 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1365 if (params().compressed) {
1366 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1367 retval = ofs && write(ofs);
1369 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1370 retval = ofs && write(ofs);
1374 message(str + _(" could not write file!"));
1379 // removeAutosaveFile();
1382 message(str + _(" done."));
1388 docstring Buffer::emergencyWrite()
1390 // No need to save if the buffer has not changed.
1394 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1396 docstring user_message = bformat(
1397 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1399 // We try to save three places:
1400 // 1) Same place as document. Unless it is an unnamed doc.
1402 string s = absFileName();
1405 if (writeFile(FileName(s))) {
1407 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1408 return user_message;
1410 user_message += " " + _("Save failed! Trying again...\n");
1414 // 2) In HOME directory.
1415 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1417 lyxerr << ' ' << s << endl;
1418 if (writeFile(FileName(s))) {
1420 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1421 return user_message;
1424 user_message += " " + _("Save failed! Trying yet again...\n");
1426 // 3) In "/tmp" directory.
1427 // MakeAbsPath to prepend the current
1428 // drive letter on OS/2
1429 s = addName(package().temp_dir().absFileName(), absFileName());
1431 lyxerr << ' ' << s << endl;
1432 if (writeFile(FileName(s))) {
1434 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1435 return user_message;
1438 user_message += " " + _("Save failed! Bummer. Document is lost.");
1441 return user_message;
1445 bool Buffer::write(ostream & ofs) const
1448 // Use the standard "C" locale for file output.
1449 ofs.imbue(locale::classic());
1452 // The top of the file should not be written by params().
1454 // write out a comment in the top of the file
1455 // Important: Keep the version formatting in sync with lyx2lyx and
1456 // tex2lyx (bug 7951)
1457 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1458 << " created this file. For more info see http://www.lyx.org/\n"
1459 << "\\lyxformat " << LYX_FORMAT << "\n"
1460 << "\\begin_document\n";
1462 /// For each author, set 'used' to true if there is a change
1463 /// by this author in the document; otherwise set it to 'false'.
1464 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1465 AuthorList::Authors::const_iterator a_end = params().authors().end();
1466 for (; a_it != a_end; ++a_it)
1467 a_it->setUsed(false);
1469 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1470 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1471 for ( ; it != end; ++it)
1472 it->checkAuthors(params().authors());
1474 // now write out the buffer parameters.
1475 ofs << "\\begin_header\n";
1476 params().writeFile(ofs);
1477 ofs << "\\end_header\n";
1480 ofs << "\n\\begin_body\n";
1482 ofs << "\n\\end_body\n";
1484 // Write marker that shows file is complete
1485 ofs << "\\end_document" << endl;
1487 // Shouldn't really be needed....
1490 // how to check if close went ok?
1491 // Following is an attempt... (BE 20001011)
1493 // good() returns false if any error occured, including some
1494 // formatting error.
1495 // bad() returns true if something bad happened in the buffer,
1496 // which should include file system full errors.
1501 lyxerr << "File was not closed properly." << endl;
1508 bool Buffer::makeLaTeXFile(FileName const & fname,
1509 string const & original_path,
1510 OutputParams const & runparams_in,
1511 OutputWhat output) const
1513 OutputParams runparams = runparams_in;
1515 // This is necessary for LuaTeX/XeTeX with tex fonts.
1516 // See FIXME in BufferParams::encoding()
1517 if (runparams.isFullUnicode())
1518 runparams.encoding = encodings.fromLyXName("utf8-plain");
1520 string const encoding = runparams.encoding->iconvName();
1521 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1524 try { ofs.reset(encoding); }
1525 catch (iconv_codecvt_facet_exception const & e) {
1526 lyxerr << "Caught iconv exception: " << e.what() << endl;
1527 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1528 "verify that the support software for your encoding (%1$s) is "
1529 "properly installed"), from_ascii(encoding)));
1532 if (!openFileWrite(ofs, fname))
1535 ErrorList & errorList = d->errorLists["Export"];
1537 bool failed_export = false;
1538 otexstream os(ofs, d->texrow);
1540 // make sure we are ready to export
1541 // this needs to be done before we validate
1542 // FIXME Do we need to do this all the time? I.e., in children
1543 // of a master we are exporting?
1545 updateMacroInstances(OutputUpdate);
1548 os.texrow().reset();
1549 writeLaTeXSource(os, original_path, runparams, output);
1551 catch (EncodingException const & e) {
1552 odocstringstream ods;
1553 ods.put(e.failed_char);
1555 oss << "0x" << hex << e.failed_char << dec;
1556 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1557 " (code point %2$s)"),
1558 ods.str(), from_utf8(oss.str()));
1559 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1560 "representable in the chosen encoding.\n"
1561 "Changing the document encoding to utf8 could help."),
1562 e.par_id, e.pos, e.pos + 1));
1563 failed_export = true;
1565 catch (iconv_codecvt_facet_exception const & e) {
1566 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1567 _(e.what()), -1, 0, 0));
1568 failed_export = true;
1570 catch (exception const & e) {
1571 errorList.push_back(ErrorItem(_("conversion failed"),
1572 _(e.what()), -1, 0, 0));
1573 failed_export = true;
1576 lyxerr << "Caught some really weird exception..." << endl;
1582 failed_export = true;
1583 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1586 if (runparams_in.silent)
1590 return !failed_export;
1594 void Buffer::writeLaTeXSource(otexstream & os,
1595 string const & original_path,
1596 OutputParams const & runparams_in,
1597 OutputWhat output) const
1599 // The child documents, if any, shall be already loaded at this point.
1601 OutputParams runparams = runparams_in;
1603 // If we are compiling a file standalone, even if this is the
1604 // child of some other buffer, let's cut the link here, so the
1605 // file is really independent and no concurring settings from
1606 // the master (e.g. branch state) interfere (see #8100).
1607 if (!runparams.is_child)
1608 d->ignore_parent = true;
1610 // Classify the unicode characters appearing in math insets
1611 BufferEncodings::initUnicodeMath(*this);
1613 // validate the buffer.
1614 LYXERR(Debug::LATEX, " Validating buffer...");
1615 LaTeXFeatures features(*this, params(), runparams);
1617 // This is only set once per document (in master)
1618 if (!runparams.is_child)
1619 runparams.use_polyglossia = features.usePolyglossia();
1620 LYXERR(Debug::LATEX, " Buffer validation done.");
1622 bool const output_preamble =
1623 output == FullSource || output == OnlyPreamble;
1624 bool const output_body =
1625 output == FullSource || output == OnlyBody;
1627 // The starting paragraph of the coming rows is the
1628 // first paragraph of the document. (Asger)
1629 if (output_preamble && runparams.nice) {
1630 os << "%% LyX " << lyx_version << " created this file. "
1631 "For more info, see http://www.lyx.org/.\n"
1632 "%% Do not edit unless you really know what "
1635 LYXERR(Debug::INFO, "lyx document header finished");
1637 // There are a few differences between nice LaTeX and usual files:
1638 // usual files have \batchmode and special input@path to allow
1639 // inclusion of figures specified by an explicitly relative path
1640 // (i.e., a path starting with './' or '../') with either \input or
1641 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1642 // input@path is set when the actual parameter original_path is set.
1643 // This is done for usual tex-file, but not for nice-latex-file.
1644 // (Matthias 250696)
1645 // Note that input@path is only needed for something the user does
1646 // in the preamble, included .tex files or ERT, files included by
1647 // LyX work without it.
1648 if (output_preamble) {
1649 if (!runparams.nice) {
1650 // code for usual, NOT nice-latex-file
1651 os << "\\batchmode\n"; // changed from \nonstopmode
1653 if (!original_path.empty()) {
1655 // We don't know the encoding of inputpath
1656 docstring const inputpath = from_utf8(original_path);
1657 docstring uncodable_glyphs;
1658 Encoding const * const enc = runparams.encoding;
1660 for (size_t n = 0; n < inputpath.size(); ++n) {
1661 if (!enc->encodable(inputpath[n])) {
1662 docstring const glyph(1, inputpath[n]);
1663 LYXERR0("Uncodable character '"
1665 << "' in input path!");
1666 uncodable_glyphs += glyph;
1671 // warn user if we found uncodable glyphs.
1672 if (!uncodable_glyphs.empty()) {
1673 frontend::Alert::warning(
1674 _("Uncodable character in file path"),
1676 _("The path of your document\n"
1678 "contains glyphs that are unknown "
1679 "in the current document encoding "
1680 "(namely %2$s). This may result in "
1681 "incomplete output, unless "
1682 "TEXINPUTS contains the document "
1683 "directory and you don't use "
1684 "explicitly relative paths (i.e., "
1685 "paths starting with './' or "
1686 "'../') in the preamble or in ERT."
1687 "\n\nIn case of problems, choose "
1688 "an appropriate document encoding\n"
1689 "(such as utf8) or change the "
1691 inputpath, uncodable_glyphs));
1694 support::latex_path(original_path);
1695 if (contains(docdir, '#')) {
1696 docdir = subst(docdir, "#", "\\#");
1697 os << "\\catcode`\\#=11"
1698 "\\def\\#{#}\\catcode`\\#=6\n";
1700 if (contains(docdir, '%')) {
1701 docdir = subst(docdir, "%", "\\%");
1702 os << "\\catcode`\\%=11"
1703 "\\def\\%{%}\\catcode`\\%=14\n";
1705 os << "\\makeatletter\n"
1706 << "\\def\\input@path{{"
1707 << docdir << "/}}\n"
1708 << "\\makeatother\n";
1712 // get parent macros (if this buffer has a parent) which will be
1713 // written at the document begin further down.
1714 MacroSet parentMacros;
1715 listParentMacros(parentMacros, features);
1717 // Write the preamble
1718 runparams.use_babel = params().writeLaTeX(os, features,
1719 d->filename.onlyPath());
1721 // Japanese might be required only in some children of a document,
1722 // but once required, we must keep use_japanese true.
1723 runparams.use_japanese |= features.isRequired("japanese");
1726 // Restore the parenthood if needed
1727 if (!runparams.is_child)
1728 d->ignore_parent = false;
1733 os << "\\begin{document}\n";
1735 // output the parent macros
1736 MacroSet::iterator it = parentMacros.begin();
1737 MacroSet::iterator end = parentMacros.end();
1738 for (; it != end; ++it) {
1739 int num_lines = (*it)->write(os.os(), true);
1740 os.texrow().newlines(num_lines);
1743 } // output_preamble
1745 os.texrow().start(paragraphs().begin()->id(), 0);
1747 LYXERR(Debug::INFO, "preamble finished, now the body.");
1750 latexParagraphs(*this, text(), os, runparams);
1752 // Restore the parenthood if needed
1753 if (!runparams.is_child)
1754 d->ignore_parent = false;
1756 // add this just in case after all the paragraphs
1759 if (output_preamble) {
1760 os << "\\end{document}\n";
1761 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1763 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1765 runparams_in.encoding = runparams.encoding;
1767 // Just to be sure. (Asger)
1768 os.texrow().newline();
1770 //for (int i = 0; i<d->texrow.rows(); i++) {
1772 // if (d->texrow.getIdFromRow(i+1,id,pos) && id>0)
1773 // lyxerr << i+1 << ":" << id << ":" << getParFromID(id).paragraph().asString()<<"\n";
1776 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1777 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
1781 void Buffer::makeDocBookFile(FileName const & fname,
1782 OutputParams const & runparams,
1783 OutputWhat output) const
1785 LYXERR(Debug::LATEX, "makeDocBookFile...");
1788 if (!openFileWrite(ofs, fname))
1791 // make sure we are ready to export
1792 // this needs to be done before we validate
1794 updateMacroInstances(OutputUpdate);
1796 writeDocBookSource(ofs, fname.absFileName(), runparams, output);
1800 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1804 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1805 OutputParams const & runparams,
1806 OutputWhat output) const
1808 LaTeXFeatures features(*this, params(), runparams);
1813 DocumentClass const & tclass = params().documentClass();
1814 string const top_element = tclass.latexname();
1816 bool const output_preamble =
1817 output == FullSource || output == OnlyPreamble;
1818 bool const output_body =
1819 output == FullSource || output == OnlyBody;
1821 if (output_preamble) {
1822 if (runparams.flavor == OutputParams::XML)
1823 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1826 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1829 if (! tclass.class_header().empty())
1830 os << from_ascii(tclass.class_header());
1831 else if (runparams.flavor == OutputParams::XML)
1832 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1833 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1835 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1837 docstring preamble = from_utf8(params().preamble);
1838 if (runparams.flavor != OutputParams::XML ) {
1839 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1840 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1841 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1842 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1845 string const name = runparams.nice
1846 ? changeExtension(absFileName(), ".sgml") : fname;
1847 preamble += features.getIncludedFiles(name);
1848 preamble += features.getLyXSGMLEntities();
1850 if (!preamble.empty()) {
1851 os << "\n [ " << preamble << " ]";
1857 string top = top_element;
1859 if (runparams.flavor == OutputParams::XML)
1860 top += params().language->code();
1862 top += params().language->code().substr(0, 2);
1865 if (!params().options.empty()) {
1867 top += params().options;
1870 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1871 << " file was created by LyX " << lyx_version
1872 << "\n See http://www.lyx.org/ for more information -->\n";
1874 params().documentClass().counters().reset();
1876 sgml::openTag(os, top);
1878 docbookParagraphs(text(), *this, os, runparams);
1879 sgml::closeTag(os, top_element);
1884 void Buffer::makeLyXHTMLFile(FileName const & fname,
1885 OutputParams const & runparams) const
1887 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1890 if (!openFileWrite(ofs, fname))
1893 // make sure we are ready to export
1894 // this has to be done before we validate
1895 updateBuffer(UpdateMaster, OutputUpdate);
1896 updateMacroInstances(OutputUpdate);
1898 writeLyXHTMLSource(ofs, runparams, FullSource);
1902 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1906 void Buffer::writeLyXHTMLSource(odocstream & os,
1907 OutputParams const & runparams,
1908 OutputWhat output) const
1910 LaTeXFeatures features(*this, params(), runparams);
1912 d->bibinfo_.makeCitationLabels(*this);
1914 bool const output_preamble =
1915 output == FullSource || output == OnlyPreamble;
1916 bool const output_body =
1917 output == FullSource || output == OnlyBody || output == IncludedFile;
1919 if (output_preamble) {
1920 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1921 << "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1 plus MathML 2.0//EN\" \"http://www.w3.org/Math/DTD/mathml2/xhtml-math11-f.dtd\">\n"
1922 // FIXME Language should be set properly.
1923 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
1925 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
1926 // FIXME Presumably need to set this right
1927 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1929 docstring const & doctitle = features.htmlTitle();
1931 << (doctitle.empty() ?
1932 from_ascii("LyX Document") :
1933 html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
1936 docstring styles = features.getTClassHTMLPreamble();
1937 if (!styles.empty())
1938 os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
1940 styles = from_utf8(features.getPreambleSnippets());
1941 if (!styles.empty())
1942 os << "\n<!-- Preamble Snippets -->\n" << styles << '\n';
1944 // we will collect CSS information in a stream, and then output it
1945 // either here, as part of the header, or else in a separate file.
1946 odocstringstream css;
1947 styles = from_utf8(features.getCSSSnippets());
1948 if (!styles.empty())
1949 css << "/* LyX Provided Styles */\n" << styles << '\n';
1951 styles = features.getTClassHTMLStyles();
1952 if (!styles.empty())
1953 css << "/* Layout-provided Styles */\n" << styles << '\n';
1955 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
1956 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
1957 if (needfg || needbg) {
1958 css << "\nbody {\n";
1961 << from_ascii(X11hexname(params().fontcolor))
1964 css << " background-color: "
1965 << from_ascii(X11hexname(params().backgroundcolor))
1970 docstring const dstyles = css.str();
1971 if (!dstyles.empty()) {
1972 bool written = false;
1973 if (params().html_css_as_file) {
1974 // open a file for CSS info
1976 string const fcssname = addName(temppath(), "docstyle.css");
1977 FileName const fcssfile = FileName(fcssname);
1978 if (openFileWrite(ocss, fcssfile)) {
1982 // write link to header
1983 os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
1985 runparams.exportdata->addExternalFile("xhtml", fcssfile);
1988 // we are here if the CSS is supposed to be written to the header
1989 // or if we failed to write it to an external file.
1991 os << "<style type='text/css'>\n"
2000 bool const output_body_tag = (output != IncludedFile);
2001 if (output_body_tag)
2004 if (output != IncludedFile)
2005 // if we're an included file, the counters are in the master.
2006 params().documentClass().counters().reset();
2007 xhtmlParagraphs(text(), *this, xs, runparams);
2008 if (output_body_tag)
2012 if (output_preamble)
2017 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
2018 // Other flags: -wall -v0 -x
2019 int Buffer::runChktex()
2023 // get LaTeX-Filename
2024 FileName const path(temppath());
2025 string const name = addName(path.absFileName(), latexName());
2026 string const org_path = filePath();
2028 PathChanger p(path); // path to LaTeX file
2029 message(_("Running chktex..."));
2031 // Generate the LaTeX file if neccessary
2032 OutputParams runparams(¶ms().encoding());
2033 runparams.flavor = OutputParams::LATEX;
2034 runparams.nice = false;
2035 runparams.linelen = lyxrc.plaintext_linelen;
2036 makeLaTeXFile(FileName(name), org_path, runparams);
2039 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
2040 int const res = chktex.run(terr); // run chktex
2043 Alert::error(_("chktex failure"),
2044 _("Could not run chktex successfully."));
2046 ErrorList & errlist = d->errorLists["ChkTeX"];
2048 bufferErrors(terr, errlist);
2053 if (runparams.silent)
2054 d->errorLists["ChkTeX"].clear();
2062 void Buffer::validate(LaTeXFeatures & features) const
2064 // Validate the buffer params, but not for included
2065 // files, since they also use the parent buffer's
2067 if (!features.runparams().is_child)
2068 params().validate(features);
2070 for_each(paragraphs().begin(), paragraphs().end(),
2071 bind(&Paragraph::validate, _1, ref(features)));
2073 if (lyxerr.debugging(Debug::LATEX)) {
2074 features.showStruct();
2079 void Buffer::getLabelList(vector<docstring> & list) const
2081 // If this is a child document, use the master's list instead.
2083 masterBuffer()->getLabelList(list);
2088 Toc & toc = d->toc_backend.toc("label");
2089 TocIterator toc_it = toc.begin();
2090 TocIterator end = toc.end();
2091 for (; toc_it != end; ++toc_it) {
2092 if (toc_it->depth() == 0)
2093 list.push_back(toc_it->str());
2098 void Buffer::updateBibfilesCache(UpdateScope scope) const
2100 // FIXME This is probably unnecssary, given where we call this.
2101 // If this is a child document, use the parent's cache instead.
2102 if (parent() && scope != UpdateChildOnly) {
2103 masterBuffer()->updateBibfilesCache();
2107 d->bibfiles_cache_.clear();
2108 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2109 if (it->lyxCode() == BIBTEX_CODE) {
2110 InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
2111 support::FileNameList const bibfiles = inset.getBibFiles();
2112 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2115 } else if (it->lyxCode() == INCLUDE_CODE) {
2116 InsetInclude & inset = static_cast<InsetInclude &>(*it);
2117 Buffer const * const incbuf = inset.getChildBuffer();
2120 support::FileNameList const & bibfiles =
2121 incbuf->getBibfilesCache(UpdateChildOnly);
2122 if (!bibfiles.empty()) {
2123 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2129 d->bibfile_cache_valid_ = true;
2130 d->bibinfo_cache_valid_ = false;
2131 d->cite_labels_valid_ = false;
2135 void Buffer::invalidateBibinfoCache() const
2137 d->bibinfo_cache_valid_ = false;
2138 d->cite_labels_valid_ = false;
2139 // also invalidate the cache for the parent buffer
2140 Buffer const * const pbuf = d->parent();
2142 pbuf->invalidateBibinfoCache();
2146 void Buffer::invalidateBibfileCache() const
2148 d->bibfile_cache_valid_ = false;
2149 d->bibinfo_cache_valid_ = false;
2150 d->cite_labels_valid_ = false;
2151 // also invalidate the cache for the parent buffer
2152 Buffer const * const pbuf = d->parent();
2154 pbuf->invalidateBibfileCache();
2158 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
2160 // FIXME This is probably unnecessary, given where we call this.
2161 // If this is a child document, use the master's cache instead.
2162 Buffer const * const pbuf = masterBuffer();
2163 if (pbuf != this && scope != UpdateChildOnly)
2164 return pbuf->getBibfilesCache();
2166 if (!d->bibfile_cache_valid_)
2167 this->updateBibfilesCache(scope);
2169 return d->bibfiles_cache_;
2173 BiblioInfo const & Buffer::masterBibInfo() const
2175 Buffer const * const tmp = masterBuffer();
2177 return tmp->masterBibInfo();
2182 void Buffer::checkIfBibInfoCacheIsValid() const
2184 // use the master's cache
2185 Buffer const * const tmp = masterBuffer();
2187 tmp->checkIfBibInfoCacheIsValid();
2191 // compare the cached timestamps with the actual ones.
2192 FileNameList const & bibfiles_cache = getBibfilesCache();
2193 FileNameList::const_iterator ei = bibfiles_cache.begin();
2194 FileNameList::const_iterator en = bibfiles_cache.end();
2195 for (; ei != en; ++ ei) {
2196 time_t lastw = ei->lastModified();
2197 time_t prevw = d->bibfile_status_[*ei];
2198 if (lastw != prevw) {
2199 d->bibinfo_cache_valid_ = false;
2200 d->cite_labels_valid_ = false;
2201 d->bibfile_status_[*ei] = lastw;
2207 void Buffer::reloadBibInfoCache() const
2209 // use the master's cache
2210 Buffer const * const tmp = masterBuffer();
2212 tmp->reloadBibInfoCache();
2216 checkIfBibInfoCacheIsValid();
2217 if (d->bibinfo_cache_valid_)
2220 d->bibinfo_.clear();
2222 d->bibinfo_cache_valid_ = true;
2226 void Buffer::collectBibKeys() const
2228 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2229 it->collectBibKeys(it);
2233 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
2235 Buffer const * tmp = masterBuffer();
2236 BiblioInfo & masterbi = (tmp == this) ?
2237 d->bibinfo_ : tmp->d->bibinfo_;
2238 masterbi.mergeBiblioInfo(bi);
2242 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
2244 Buffer const * tmp = masterBuffer();
2245 BiblioInfo & masterbi = (tmp == this) ?
2246 d->bibinfo_ : tmp->d->bibinfo_;
2251 void Buffer::makeCitationLabels() const
2253 Buffer const * const master = masterBuffer();
2254 return d->bibinfo_.makeCitationLabels(*master);
2258 bool Buffer::citeLabelsValid() const
2260 return masterBuffer()->d->cite_labels_valid_;
2264 void Buffer::removeBiblioTempFiles() const
2266 // We remove files that contain LaTeX commands specific to the
2267 // particular bibliographic style being used, in order to avoid
2268 // LaTeX errors when we switch style.
2269 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2270 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2271 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2272 aux_file.removeFile();
2273 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2274 bbl_file.removeFile();
2275 // Also for the parent buffer
2276 Buffer const * const pbuf = parent();
2278 pbuf->removeBiblioTempFiles();
2282 bool Buffer::isDepClean(string const & name) const
2284 DepClean::const_iterator const it = d->dep_clean.find(name);
2285 if (it == d->dep_clean.end())
2291 void Buffer::markDepClean(string const & name)
2293 d->dep_clean[name] = true;
2297 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2300 // FIXME? if there is an Buffer LFUN that can be dispatched even
2301 // if internal, put a switch '(cmd.action)' here.
2307 switch (cmd.action()) {
2309 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2310 flag.setOnOff(isReadonly());
2313 // FIXME: There is need for a command-line import.
2314 //case LFUN_BUFFER_IMPORT:
2316 case LFUN_BUFFER_AUTO_SAVE:
2319 case LFUN_BUFFER_EXPORT_CUSTOM:
2320 // FIXME: Nothing to check here?
2323 case LFUN_BUFFER_EXPORT: {
2324 docstring const arg = cmd.argument();
2325 if (arg == "custom") {
2329 string format = to_utf8(arg);
2330 size_t pos = format.find(' ');
2331 if (pos != string::npos)
2332 format = format.substr(0, pos);
2333 enable = params().isExportable(format);
2335 flag.message(bformat(
2336 _("Don't know how to export to format: %1$s"), arg));
2340 case LFUN_BUFFER_CHKTEX:
2341 enable = params().isLatex() && !lyxrc.chktex_command.empty();
2344 case LFUN_BUILD_PROGRAM:
2345 enable = params().isExportable("program");
2348 case LFUN_BRANCH_ACTIVATE:
2349 case LFUN_BRANCH_DEACTIVATE:
2350 case LFUN_BRANCH_MASTER_ACTIVATE:
2351 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2352 bool const master = (cmd.action() == LFUN_BRANCH_MASTER_ACTIVATE
2353 || cmd.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2354 BranchList const & branchList = master ? masterBuffer()->params().branchlist()
2355 : params().branchlist();
2356 docstring const branchName = cmd.argument();
2357 flag.setEnabled(!branchName.empty() && branchList.find(branchName));
2361 case LFUN_BRANCH_ADD:
2362 case LFUN_BRANCHES_RENAME:
2363 case LFUN_BUFFER_PRINT:
2364 // if no Buffer is present, then of course we won't be called!
2367 case LFUN_BUFFER_LANGUAGE:
2368 enable = !isReadonly();
2374 flag.setEnabled(enable);
2379 void Buffer::dispatch(string const & command, DispatchResult & result)
2381 return dispatch(lyxaction.lookupFunc(command), result);
2385 // NOTE We can end up here even if we have no GUI, because we are called
2386 // by LyX::exec to handled command-line requests. So we may need to check
2387 // whether we have a GUI or not. The boolean use_gui holds this information.
2388 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2391 // FIXME? if there is an Buffer LFUN that can be dispatched even
2392 // if internal, put a switch '(cmd.action())' here.
2393 dr.dispatched(false);
2396 string const argument = to_utf8(func.argument());
2397 // We'll set this back to false if need be.
2398 bool dispatched = true;
2399 undo().beginUndoGroup();
2401 switch (func.action()) {
2402 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2403 if (lyxvc().inUse()) {
2404 string log = lyxvc().toggleReadOnly();
2409 setReadonly(!isReadonly());
2412 case LFUN_BUFFER_EXPORT: {
2413 ExportStatus const status = doExport(argument, false);
2414 dr.setError(status != ExportSuccess);
2415 if (status != ExportSuccess)
2416 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2421 case LFUN_BUILD_PROGRAM: {
2422 ExportStatus const status = doExport("program", true);
2423 dr.setError(status != ExportSuccess);
2424 if (status != ExportSuccess)
2425 dr.setMessage(_("Error generating literate programming code."));
2429 case LFUN_BUFFER_CHKTEX:
2433 case LFUN_BUFFER_EXPORT_CUSTOM: {
2435 string command = split(argument, format_name, ' ');
2436 Format const * format = formats.getFormat(format_name);
2438 lyxerr << "Format \"" << format_name
2439 << "\" not recognized!"
2444 // The name of the file created by the conversion process
2447 // Output to filename
2448 if (format->name() == "lyx") {
2449 string const latexname = latexName(false);
2450 filename = changeExtension(latexname,
2451 format->extension());
2452 filename = addName(temppath(), filename);
2454 if (!writeFile(FileName(filename)))
2458 doExport(format_name, true, filename);
2461 // Substitute $$FName for filename
2462 if (!contains(command, "$$FName"))
2463 command = "( " + command + " ) < $$FName";
2464 command = subst(command, "$$FName", filename);
2466 // Execute the command in the background
2468 call.startscript(Systemcall::DontWait, command, filePath());
2472 // FIXME: There is need for a command-line import.
2474 case LFUN_BUFFER_IMPORT:
2479 case LFUN_BUFFER_AUTO_SAVE:
2481 resetAutosaveTimers();
2484 case LFUN_BRANCH_ACTIVATE:
2485 case LFUN_BRANCH_DEACTIVATE:
2486 case LFUN_BRANCH_MASTER_ACTIVATE:
2487 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2488 bool const master = (func.action() == LFUN_BRANCH_MASTER_ACTIVATE
2489 || func.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2490 Buffer * buf = master ? const_cast<Buffer *>(masterBuffer())
2493 docstring const branch_name = func.argument();
2494 // the case without a branch name is handled elsewhere
2495 if (branch_name.empty()) {
2499 Branch * branch = buf->params().branchlist().find(branch_name);
2501 LYXERR0("Branch " << branch_name << " does not exist.");
2503 docstring const msg =
2504 bformat(_("Branch \"%1$s\" does not exist."), branch_name);
2508 bool const activate = (func.action() == LFUN_BRANCH_ACTIVATE
2509 || func.action() == LFUN_BRANCH_MASTER_ACTIVATE);
2510 if (branch->isSelected() != activate) {
2511 buf->undo().recordUndoFullDocument(CursorData());
2512 branch->setSelected(activate);
2514 dr.screenUpdate(Update::Force);
2515 dr.forceBufferUpdate();
2520 case LFUN_BRANCH_ADD: {
2521 docstring branch_name = func.argument();
2522 if (branch_name.empty()) {
2526 BranchList & branch_list = params().branchlist();
2527 vector<docstring> const branches =
2528 getVectorFromString(branch_name, branch_list.separator());
2530 for (vector<docstring>::const_iterator it = branches.begin();
2531 it != branches.end(); ++it) {
2533 Branch * branch = branch_list.find(branch_name);
2535 LYXERR0("Branch " << branch_name << " already exists.");
2539 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2541 undo().recordUndoFullDocument(CursorData());
2542 branch_list.add(branch_name);
2543 branch = branch_list.find(branch_name);
2544 string const x11hexname = X11hexname(branch->color());
2545 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2546 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2548 dr.screenUpdate(Update::Force);
2556 case LFUN_BRANCHES_RENAME: {
2557 if (func.argument().empty())
2560 docstring const oldname = from_utf8(func.getArg(0));
2561 docstring const newname = from_utf8(func.getArg(1));
2562 InsetIterator it = inset_iterator_begin(inset());
2563 InsetIterator const end = inset_iterator_end(inset());
2564 bool success = false;
2565 for (; it != end; ++it) {
2566 if (it->lyxCode() == BRANCH_CODE) {
2567 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2568 if (ins.branch() == oldname) {
2569 undo().recordUndo(CursorData(it));
2570 ins.rename(newname);
2575 if (it->lyxCode() == INCLUDE_CODE) {
2576 // get buffer of external file
2577 InsetInclude const & ins =
2578 static_cast<InsetInclude const &>(*it);
2579 Buffer * child = ins.getChildBuffer();
2582 child->dispatch(func, dr);
2587 dr.screenUpdate(Update::Force);
2588 dr.forceBufferUpdate();
2593 case LFUN_BUFFER_PRINT: {
2594 // we'll assume there's a problem until we succeed
2596 string target = func.getArg(0);
2597 string target_name = func.getArg(1);
2598 string command = func.getArg(2);
2601 || target_name.empty()
2602 || command.empty()) {
2603 LYXERR0("Unable to parse " << func.argument());
2604 docstring const msg =
2605 bformat(_("Unable to parse \"%1$s\""), func.argument());
2609 if (target != "printer" && target != "file") {
2610 LYXERR0("Unrecognized target \"" << target << '"');
2611 docstring const msg =
2612 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2617 if (doExport("dvi", true) != ExportSuccess) {
2618 showPrintError(absFileName());
2619 dr.setMessage(_("Error exporting to DVI."));
2623 // Push directory path.
2624 string const path = temppath();
2625 // Prevent the compiler from optimizing away p
2629 // there are three cases here:
2630 // 1. we print to a file
2631 // 2. we print directly to a printer
2632 // 3. we print using a spool command (print to file first)
2635 string const dviname = changeExtension(latexName(true), "dvi");
2637 if (target == "printer") {
2638 if (!lyxrc.print_spool_command.empty()) {
2639 // case 3: print using a spool
2640 string const psname = changeExtension(dviname,".ps");
2641 command += ' ' + lyxrc.print_to_file
2644 + quoteName(dviname);
2646 string command2 = lyxrc.print_spool_command + ' ';
2647 if (target_name != "default") {
2648 command2 += lyxrc.print_spool_printerprefix
2652 command2 += quoteName(psname);
2654 // If successful, then spool command
2655 res = one.startscript(Systemcall::Wait, command,
2659 // If there's no GUI, we have to wait on this command. Otherwise,
2660 // LyX deletes the temporary directory, and with it the spooled
2661 // file, before it can be printed!!
2662 Systemcall::Starttype stype = use_gui ?
2663 Systemcall::DontWait : Systemcall::Wait;
2664 res = one.startscript(stype, command2,
2668 // case 2: print directly to a printer
2669 if (target_name != "default")
2670 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2672 Systemcall::Starttype stype = use_gui ?
2673 Systemcall::DontWait : Systemcall::Wait;
2674 res = one.startscript(stype, command +
2675 quoteName(dviname), filePath());
2679 // case 1: print to a file
2680 FileName const filename(makeAbsPath(target_name, filePath()));
2681 FileName const dvifile(makeAbsPath(dviname, path));
2682 if (filename.exists()) {
2683 docstring text = bformat(
2684 _("The file %1$s already exists.\n\n"
2685 "Do you want to overwrite that file?"),
2686 makeDisplayPath(filename.absFileName()));
2687 if (Alert::prompt(_("Overwrite file?"),
2688 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2691 command += ' ' + lyxrc.print_to_file
2692 + quoteName(filename.toFilesystemEncoding())
2694 + quoteName(dvifile.toFilesystemEncoding());
2696 Systemcall::Starttype stype = use_gui ?
2697 Systemcall::DontWait : Systemcall::Wait;
2698 res = one.startscript(stype, command, filePath());
2704 dr.setMessage(_("Error running external commands."));
2705 showPrintError(absFileName());
2714 dr.dispatched(dispatched);
2715 undo().endUndoGroup();
2719 void Buffer::changeLanguage(Language const * from, Language const * to)
2721 LASSERT(from, return);
2722 LASSERT(to, return);
2724 for_each(par_iterator_begin(),
2726 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2730 bool Buffer::isMultiLingual() const
2732 ParConstIterator end = par_iterator_end();
2733 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2734 if (it->isMultiLingual(params()))
2741 std::set<Language const *> Buffer::getLanguages() const
2743 std::set<Language const *> languages;
2744 getLanguages(languages);
2749 void Buffer::getLanguages(std::set<Language const *> & languages) const
2751 ParConstIterator end = par_iterator_end();
2752 // add the buffer language, even if it's not actively used
2753 languages.insert(language());
2754 // iterate over the paragraphs
2755 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2756 it->getLanguages(languages);
2758 ListOfBuffers clist = getDescendents();
2759 ListOfBuffers::const_iterator cit = clist.begin();
2760 ListOfBuffers::const_iterator const cen = clist.end();
2761 for (; cit != cen; ++cit)
2762 (*cit)->getLanguages(languages);
2766 DocIterator Buffer::getParFromID(int const id) const
2768 Buffer * buf = const_cast<Buffer *>(this);
2770 // John says this is called with id == -1 from undo
2771 lyxerr << "getParFromID(), id: " << id << endl;
2772 return doc_iterator_end(buf);
2775 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2776 if (it.paragraph().id() == id)
2779 return doc_iterator_end(buf);
2783 bool Buffer::hasParWithID(int const id) const
2785 return !getParFromID(id).atEnd();
2789 ParIterator Buffer::par_iterator_begin()
2791 return ParIterator(doc_iterator_begin(this));
2795 ParIterator Buffer::par_iterator_end()
2797 return ParIterator(doc_iterator_end(this));
2801 ParConstIterator Buffer::par_iterator_begin() const
2803 return ParConstIterator(doc_iterator_begin(this));
2807 ParConstIterator Buffer::par_iterator_end() const
2809 return ParConstIterator(doc_iterator_end(this));
2813 Language const * Buffer::language() const
2815 return params().language;
2819 docstring const Buffer::B_(string const & l10n) const
2821 return params().B_(l10n);
2825 bool Buffer::isClean() const
2827 return d->lyx_clean;
2831 bool Buffer::isExternallyModified(CheckMethod method) const
2833 LASSERT(d->filename.exists(), return false);
2834 // if method == timestamp, check timestamp before checksum
2835 return (method == checksum_method
2836 || d->timestamp_ != d->filename.lastModified())
2837 && d->checksum_ != d->filename.checksum();
2841 void Buffer::saveCheckSum() const
2843 FileName const & file = d->filename;
2846 if (file.exists()) {
2847 d->timestamp_ = file.lastModified();
2848 d->checksum_ = file.checksum();
2850 // in the case of save to a new file.
2857 void Buffer::markClean() const
2859 if (!d->lyx_clean) {
2860 d->lyx_clean = true;
2863 // if the .lyx file has been saved, we don't need an
2865 d->bak_clean = true;
2866 d->undo_.markDirty();
2870 void Buffer::setUnnamed(bool flag)
2876 bool Buffer::isUnnamed() const
2883 /// Don't check unnamed, here: isInternal() is used in
2884 /// newBuffer(), where the unnamed flag has not been set by anyone
2885 /// yet. Also, for an internal buffer, there should be no need for
2886 /// retrieving fileName() nor for checking if it is unnamed or not.
2887 bool Buffer::isInternal() const
2889 return d->internal_buffer;
2893 void Buffer::setInternal(bool flag)
2895 d->internal_buffer = flag;
2899 void Buffer::markDirty()
2902 d->lyx_clean = false;
2905 d->bak_clean = false;
2907 DepClean::iterator it = d->dep_clean.begin();
2908 DepClean::const_iterator const end = d->dep_clean.end();
2910 for (; it != end; ++it)
2915 FileName Buffer::fileName() const
2921 string Buffer::absFileName() const
2923 return d->filename.absFileName();
2927 string Buffer::filePath() const
2929 string const abs = d->filename.onlyPath().absFileName();
2932 int last = abs.length() - 1;
2934 return abs[last] == '/' ? abs : abs + '/';
2938 bool Buffer::isReadonly() const
2940 return d->read_only;
2944 void Buffer::setParent(Buffer const * buffer)
2946 // Avoids recursive include.
2947 d->setParent(buffer == this ? 0 : buffer);
2952 Buffer const * Buffer::parent() const
2958 ListOfBuffers Buffer::allRelatives() const
2960 ListOfBuffers lb = masterBuffer()->getDescendents();
2961 lb.push_front(const_cast<Buffer *>(masterBuffer()));
2966 Buffer const * Buffer::masterBuffer() const
2968 // FIXME Should be make sure we are not in some kind
2969 // of recursive include? A -> B -> A will crash this.
2970 Buffer const * const pbuf = d->parent();
2974 return pbuf->masterBuffer();
2978 bool Buffer::isChild(Buffer * child) const
2980 return d->children_positions.find(child) != d->children_positions.end();
2984 DocIterator Buffer::firstChildPosition(Buffer const * child)
2986 Impl::BufferPositionMap::iterator it;
2987 it = d->children_positions.find(child);
2988 if (it == d->children_positions.end())
2989 return DocIterator(this);
2994 bool Buffer::hasChildren() const
2996 return !d->children_positions.empty();
3000 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
3002 // loop over children
3003 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3004 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3005 for (; it != end; ++it) {
3006 Buffer * child = const_cast<Buffer *>(it->first);
3008 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
3009 if (bit != clist.end())
3011 clist.push_back(child);
3013 // there might be grandchildren
3014 child->collectChildren(clist, true);
3019 ListOfBuffers Buffer::getChildren() const
3022 collectChildren(v, false);
3023 // Make sure we have not included ourselves.
3024 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3025 if (bit != v.end()) {
3026 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3033 ListOfBuffers Buffer::getDescendents() const
3036 collectChildren(v, true);
3037 // Make sure we have not included ourselves.
3038 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3039 if (bit != v.end()) {
3040 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3047 template<typename M>
3048 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
3053 typename M::const_iterator it = m.lower_bound(x);
3054 if (it == m.begin())
3062 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
3063 DocIterator const & pos) const
3065 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
3067 // if paragraphs have no macro context set, pos will be empty
3071 // we haven't found anything yet
3072 DocIterator bestPos = owner_->par_iterator_begin();
3073 MacroData const * bestData = 0;
3075 // find macro definitions for name
3076 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
3077 if (nameIt != macros.end()) {
3078 // find last definition in front of pos or at pos itself
3079 PositionScopeMacroMap::const_iterator it
3080 = greatest_below(nameIt->second, pos);
3081 if (it != nameIt->second.end()) {
3083 // scope ends behind pos?
3084 if (pos < it->second.first) {
3085 // Looks good, remember this. If there
3086 // is no external macro behind this,
3087 // we found the right one already.
3088 bestPos = it->first;
3089 bestData = &it->second.second;
3093 // try previous macro if there is one
3094 if (it == nameIt->second.begin())
3101 // find macros in included files
3102 PositionScopeBufferMap::const_iterator it
3103 = greatest_below(position_to_children, pos);
3104 if (it == position_to_children.end())
3105 // no children before
3109 // do we know something better (i.e. later) already?
3110 if (it->first < bestPos )
3113 // scope ends behind pos?
3114 if (pos < it->second.first
3115 && (cloned_buffer_ ||
3116 theBufferList().isLoaded(it->second.second))) {
3117 // look for macro in external file
3119 MacroData const * data
3120 = it->second.second->getMacro(name, false);
3123 bestPos = it->first;
3129 // try previous file if there is one
3130 if (it == position_to_children.begin())
3135 // return the best macro we have found
3140 MacroData const * Buffer::getMacro(docstring const & name,
3141 DocIterator const & pos, bool global) const
3146 // query buffer macros
3147 MacroData const * data = d->getBufferMacro(name, pos);
3151 // If there is a master buffer, query that
3152 Buffer const * const pbuf = d->parent();
3154 d->macro_lock = true;
3155 MacroData const * macro = pbuf->getMacro(
3156 name, *this, false);
3157 d->macro_lock = false;
3163 data = MacroTable::globalMacros().get(name);
3172 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3174 // set scope end behind the last paragraph
3175 DocIterator scope = par_iterator_begin();
3176 scope.pit() = scope.lastpit() + 1;
3178 return getMacro(name, scope, global);
3182 MacroData const * Buffer::getMacro(docstring const & name,
3183 Buffer const & child, bool global) const
3185 // look where the child buffer is included first
3186 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3187 if (it == d->children_positions.end())
3190 // check for macros at the inclusion position
3191 return getMacro(name, it->second, global);
3195 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3197 pit_type const lastpit = it.lastpit();
3199 // look for macros in each paragraph
3200 while (it.pit() <= lastpit) {
3201 Paragraph & par = it.paragraph();
3203 // iterate over the insets of the current paragraph
3204 InsetList const & insets = par.insetList();
3205 InsetList::const_iterator iit = insets.begin();
3206 InsetList::const_iterator end = insets.end();
3207 for (; iit != end; ++iit) {
3208 it.pos() = iit->pos;
3210 // is it a nested text inset?
3211 if (iit->inset->asInsetText()) {
3212 // Inset needs its own scope?
3213 InsetText const * itext = iit->inset->asInsetText();
3214 bool newScope = itext->isMacroScope();
3216 // scope which ends just behind the inset
3217 DocIterator insetScope = it;
3220 // collect macros in inset
3221 it.push_back(CursorSlice(*iit->inset));
3222 updateMacros(it, newScope ? insetScope : scope);
3227 if (iit->inset->asInsetTabular()) {
3228 CursorSlice slice(*iit->inset);
3229 size_t const numcells = slice.nargs();
3230 for (; slice.idx() < numcells; slice.forwardIdx()) {
3231 it.push_back(slice);
3232 updateMacros(it, scope);
3238 // is it an external file?
3239 if (iit->inset->lyxCode() == INCLUDE_CODE) {
3240 // get buffer of external file
3241 InsetInclude const & inset =
3242 static_cast<InsetInclude const &>(*iit->inset);
3244 Buffer * child = inset.getChildBuffer();
3249 // register its position, but only when it is
3250 // included first in the buffer
3251 if (children_positions.find(child) ==
3252 children_positions.end())
3253 children_positions[child] = it;
3255 // register child with its scope
3256 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3260 InsetMath * im = iit->inset->asInsetMath();
3261 if (doing_export && im) {
3262 InsetMathHull * hull = im->asHullInset();
3264 hull->recordLocation(it);
3267 if (iit->inset->lyxCode() != MATHMACRO_CODE)
3271 MathMacroTemplate & macroTemplate =
3272 *iit->inset->asInsetMath()->asMacroTemplate();
3273 MacroContext mc(owner_, it);
3274 macroTemplate.updateToContext(mc);
3277 bool valid = macroTemplate.validMacro();
3278 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3279 // then the BufferView's cursor will be invalid in
3280 // some cases which leads to crashes.
3285 // FIXME (Abdel), I don't understandt why we pass 'it' here
3286 // instead of 'macroTemplate' defined above... is this correct?
3287 macros[macroTemplate.name()][it] =
3288 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3298 void Buffer::updateMacros() const
3303 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3305 // start with empty table
3307 d->children_positions.clear();
3308 d->position_to_children.clear();
3310 // Iterate over buffer, starting with first paragraph
3311 // The scope must be bigger than any lookup DocIterator
3312 // later. For the global lookup, lastpit+1 is used, hence
3313 // we use lastpit+2 here.
3314 DocIterator it = par_iterator_begin();
3315 DocIterator outerScope = it;
3316 outerScope.pit() = outerScope.lastpit() + 2;
3317 d->updateMacros(it, outerScope);
3321 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3323 InsetIterator it = inset_iterator_begin(inset());
3324 InsetIterator const end = inset_iterator_end(inset());
3325 for (; it != end; ++it) {
3326 if (it->lyxCode() == BRANCH_CODE) {
3327 InsetBranch & br = static_cast<InsetBranch &>(*it);
3328 docstring const name = br.branch();
3329 if (!from_master && !params().branchlist().find(name))
3330 result.push_back(name);
3331 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3332 result.push_back(name);
3335 if (it->lyxCode() == INCLUDE_CODE) {
3336 // get buffer of external file
3337 InsetInclude const & ins =
3338 static_cast<InsetInclude const &>(*it);
3339 Buffer * child = ins.getChildBuffer();
3342 child->getUsedBranches(result, true);
3345 // remove duplicates
3350 void Buffer::updateMacroInstances(UpdateType utype) const
3352 LYXERR(Debug::MACROS, "updateMacroInstances for "
3353 << d->filename.onlyFileName());
3354 DocIterator it = doc_iterator_begin(this);
3356 DocIterator const end = doc_iterator_end(this);
3357 for (; it != end; it.forwardInset()) {
3358 // look for MathData cells in InsetMathNest insets
3359 InsetMath * minset = it.nextInset()->asInsetMath();
3363 // update macro in all cells of the InsetMathNest
3364 DocIterator::idx_type n = minset->nargs();
3365 MacroContext mc = MacroContext(this, it);
3366 for (DocIterator::idx_type i = 0; i < n; ++i) {
3367 MathData & data = minset->cell(i);
3368 data.updateMacros(0, mc, utype);
3374 void Buffer::listMacroNames(MacroNameSet & macros) const
3379 d->macro_lock = true;
3381 // loop over macro names
3382 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3383 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3384 for (; nameIt != nameEnd; ++nameIt)
3385 macros.insert(nameIt->first);
3387 // loop over children
3388 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3389 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3390 for (; it != end; ++it)
3391 it->first->listMacroNames(macros);
3394 Buffer const * const pbuf = d->parent();
3396 pbuf->listMacroNames(macros);
3398 d->macro_lock = false;
3402 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3404 Buffer const * const pbuf = d->parent();
3409 pbuf->listMacroNames(names);
3412 MacroNameSet::iterator it = names.begin();
3413 MacroNameSet::iterator end = names.end();
3414 for (; it != end; ++it) {
3416 MacroData const * data =
3417 pbuf->getMacro(*it, *this, false);
3419 macros.insert(data);
3421 // we cannot access the original MathMacroTemplate anymore
3422 // here to calls validate method. So we do its work here manually.
3423 // FIXME: somehow make the template accessible here.
3424 if (data->optionals() > 0)
3425 features.require("xargs");
3431 Buffer::References & Buffer::getReferenceCache(docstring const & label)
3434 return const_cast<Buffer *>(masterBuffer())->getReferenceCache(label);
3436 RefCache::iterator it = d->ref_cache_.find(label);
3437 if (it != d->ref_cache_.end())
3438 return it->second.second;
3440 static InsetLabel const * dummy_il = 0;
3441 static References const dummy_refs;
3442 it = d->ref_cache_.insert(
3443 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3444 return it->second.second;
3448 Buffer::References const & Buffer::references(docstring const & label) const
3450 return const_cast<Buffer *>(this)->getReferenceCache(label);
3454 void Buffer::addReference(docstring const & label, Inset * inset, ParIterator it)
3456 References & refs = getReferenceCache(label);
3457 refs.push_back(make_pair(inset, it));
3461 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3463 masterBuffer()->d->ref_cache_[label].first = il;
3467 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3469 return masterBuffer()->d->ref_cache_[label].first;
3473 void Buffer::clearReferenceCache() const
3476 d->ref_cache_.clear();
3480 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to)
3482 //FIXME: This does not work for child documents yet.
3483 reloadBibInfoCache();
3485 // Check if the label 'from' appears more than once
3486 BiblioInfo const & keys = masterBibInfo();
3487 BiblioInfo::const_iterator bit = keys.begin();
3488 BiblioInfo::const_iterator bend = keys.end();
3489 vector<docstring> labels;
3491 for (; bit != bend; ++bit)
3493 labels.push_back(bit->first);
3495 if (count(labels.begin(), labels.end(), from) > 1)
3498 string const paramName = "key";
3499 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3500 if (it->lyxCode() != CITE_CODE)
3502 InsetCommand * inset = it->asInsetCommand();
3503 docstring const oldValue = inset->getParam(paramName);
3504 if (oldValue == from)
3505 inset->setParam(paramName, to);
3510 void Buffer::getSourceCode(odocstream & os, string const & format,
3511 pit_type par_begin, pit_type par_end,
3512 OutputWhat output, bool master) const
3514 OutputParams runparams(¶ms().encoding());
3515 runparams.nice = true;
3516 runparams.flavor = params().getOutputFlavor(format);
3517 runparams.linelen = lyxrc.plaintext_linelen;
3518 // No side effect of file copying and image conversion
3519 runparams.dryrun = true;
3521 if (output == CurrentParagraph) {
3522 runparams.par_begin = par_begin;
3523 runparams.par_end = par_end;
3524 if (par_begin + 1 == par_end) {
3526 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3530 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3531 convert<docstring>(par_begin),
3532 convert<docstring>(par_end - 1))
3535 // output paragraphs
3536 if (runparams.flavor == OutputParams::LYX) {
3537 Paragraph const & par = text().paragraphs()[par_begin];
3539 depth_type dt = par.getDepth();
3540 par.write(ods, params(), dt);
3541 os << from_utf8(ods.str());
3542 } else if (runparams.flavor == OutputParams::HTML) {
3544 setMathFlavor(runparams);
3545 xhtmlParagraphs(text(), *this, xs, runparams);
3546 } else if (runparams.flavor == OutputParams::TEXT) {
3548 // FIXME Handles only one paragraph, unlike the others.
3549 // Probably should have some routine with a signature like them.
3550 writePlaintextParagraph(*this,
3551 text().paragraphs()[par_begin], os, runparams, dummy);
3552 } else if (params().isDocBook()) {
3553 docbookParagraphs(text(), *this, os, runparams);
3555 // If we are previewing a paragraph, even if this is the
3556 // child of some other buffer, let's cut the link here,
3557 // so that no concurring settings from the master
3558 // (e.g. branch state) interfere (see #8101).
3560 d->ignore_parent = true;
3561 // We need to validate the Buffer params' features here
3562 // in order to know if we should output polyglossia
3563 // macros (instead of babel macros)
3564 LaTeXFeatures features(*this, params(), runparams);
3565 params().validate(features);
3566 runparams.use_polyglossia = features.usePolyglossia();
3571 // latex or literate
3572 otexstream ots(os, texrow);
3575 latexParagraphs(*this, text(), ots, runparams);
3577 // Restore the parenthood
3579 d->ignore_parent = false;
3583 if (output == FullSource)
3584 os << _("Preview source code");
3585 else if (output == OnlyPreamble)
3586 os << _("Preview preamble");
3587 else if (output == OnlyBody)
3588 os << _("Preview body");
3590 if (runparams.flavor == OutputParams::LYX) {
3592 if (output == FullSource)
3594 else if (output == OnlyPreamble)
3595 params().writeFile(ods);
3596 else if (output == OnlyBody)
3598 os << from_utf8(ods.str());
3599 } else if (runparams.flavor == OutputParams::HTML) {
3600 writeLyXHTMLSource(os, runparams, output);
3601 } else if (runparams.flavor == OutputParams::TEXT) {
3602 if (output == OnlyPreamble) {
3603 os << "% "<< _("Plain text does not have a preamble.");
3605 writePlaintextFile(*this, os, runparams);
3606 } else if (params().isDocBook()) {
3607 writeDocBookSource(os, absFileName(), runparams, output);
3609 // latex or literate
3611 d->texrow.newline();
3612 d->texrow.newline();
3613 otexstream ots(os, d->texrow);
3615 runparams.is_child = true;
3616 writeLaTeXSource(ots, string(), runparams, output);
3622 ErrorList & Buffer::errorList(string const & type) const
3624 return d->errorLists[type];
3628 void Buffer::updateTocItem(std::string const & type,
3629 DocIterator const & dit) const
3632 d->gui_->updateTocItem(type, dit);
3636 void Buffer::structureChanged() const
3639 d->gui_->structureChanged();
3643 void Buffer::errors(string const & err, bool from_master) const
3646 d->gui_->errors(err, from_master);
3650 void Buffer::message(docstring const & msg) const
3653 d->gui_->message(msg);
3657 void Buffer::setBusy(bool on) const
3660 d->gui_->setBusy(on);
3664 void Buffer::updateTitles() const
3667 d->wa_->updateTitles();
3671 void Buffer::resetAutosaveTimers() const
3674 d->gui_->resetAutosaveTimers();
3678 bool Buffer::hasGuiDelegate() const
3684 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3693 class AutoSaveBuffer : public ForkedProcess {
3696 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3697 : buffer_(buffer), fname_(fname) {}
3699 virtual shared_ptr<ForkedProcess> clone() const
3701 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3706 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3707 from_utf8(fname_.absFileName())));
3708 return run(DontWait);
3712 virtual int generateChild();
3714 Buffer const & buffer_;
3719 int AutoSaveBuffer::generateChild()
3721 #if defined(__APPLE__)
3722 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3723 * We should use something else like threads.
3725 * Since I do not know how to determine at run time what is the OS X
3726 * version, I just disable forking altogether for now (JMarc)
3728 pid_t const pid = -1;
3730 // tmp_ret will be located (usually) in /tmp
3731 // will that be a problem?
3732 // Note that this calls ForkedCalls::fork(), so it's
3733 // ok cross-platform.
3734 pid_t const pid = fork();
3735 // If you want to debug the autosave
3736 // you should set pid to -1, and comment out the fork.
3737 if (pid != 0 && pid != -1)
3741 // pid = -1 signifies that lyx was unable
3742 // to fork. But we will do the save
3744 bool failed = false;
3745 TempFile tempfile("lyxautoXXXXXX.lyx");
3746 tempfile.setAutoRemove(false);
3747 FileName const tmp_ret = tempfile.name();
3748 if (!tmp_ret.empty()) {
3749 if (!buffer_.writeFile(tmp_ret))
3751 else if (!tmp_ret.moveTo(fname_))
3757 // failed to write/rename tmp_ret so try writing direct
3758 if (!buffer_.writeFile(fname_)) {
3759 // It is dangerous to do this in the child,
3760 // but safe in the parent, so...
3761 if (pid == -1) // emit message signal.
3762 buffer_.message(_("Autosave failed!"));
3766 if (pid == 0) // we are the child so...
3775 FileName Buffer::getEmergencyFileName() const
3777 return FileName(d->filename.absFileName() + ".emergency");
3781 FileName Buffer::getAutosaveFileName() const
3783 // if the document is unnamed try to save in the backup dir, else
3784 // in the default document path, and as a last try in the filePath,
3785 // which will most often be the temporary directory
3788 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3789 : lyxrc.backupdir_path;
3790 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3793 string const fname = "#" + d->filename.onlyFileName() + "#";
3795 return makeAbsPath(fname, fpath);
3799 void Buffer::removeAutosaveFile() const
3801 FileName const f = getAutosaveFileName();
3807 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3809 FileName const newauto = getAutosaveFileName();
3811 if (newauto != oldauto && oldauto.exists())
3812 if (!oldauto.moveTo(newauto))
3813 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3817 bool Buffer::autoSave() const
3819 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
3820 if (buf->d->bak_clean || isReadonly())
3823 message(_("Autosaving current document..."));
3824 buf->d->bak_clean = true;
3826 FileName const fname = getAutosaveFileName();
3827 LASSERT(d->cloned_buffer_, return false);
3829 // If this buffer is cloned, we assume that
3830 // we are running in a separate thread already.
3831 TempFile tempfile("lyxautoXXXXXX.lyx");
3832 tempfile.setAutoRemove(false);
3833 FileName const tmp_ret = tempfile.name();
3834 if (!tmp_ret.empty()) {
3836 // assume successful write of tmp_ret
3837 if (tmp_ret.moveTo(fname))
3840 // failed to write/rename tmp_ret so try writing direct
3841 return writeFile(fname);
3845 void Buffer::setExportStatus(bool e) const
3847 d->doing_export = e;
3848 ListOfBuffers clist = getDescendents();
3849 ListOfBuffers::const_iterator cit = clist.begin();
3850 ListOfBuffers::const_iterator const cen = clist.end();
3851 for (; cit != cen; ++cit)
3852 (*cit)->d->doing_export = e;
3856 bool Buffer::isExporting() const
3858 return d->doing_export;
3862 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
3866 return doExport(target, put_in_tempdir, result_file);
3869 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3870 string & result_file) const
3872 bool const update_unincluded =
3873 params().maintain_unincluded_children
3874 && !params().getIncludedChildren().empty();
3876 // (1) export with all included children (omit \includeonly)
3877 if (update_unincluded) {
3878 ExportStatus const status =
3879 doExport(target, put_in_tempdir, true, result_file);
3880 if (status != ExportSuccess)
3883 // (2) export with included children only
3884 return doExport(target, put_in_tempdir, false, result_file);
3888 void Buffer::setMathFlavor(OutputParams & op) const
3890 switch (params().html_math_output) {
3891 case BufferParams::MathML:
3892 op.math_flavor = OutputParams::MathAsMathML;
3894 case BufferParams::HTML:
3895 op.math_flavor = OutputParams::MathAsHTML;
3897 case BufferParams::Images:
3898 op.math_flavor = OutputParams::MathAsImages;
3900 case BufferParams::LaTeX:
3901 op.math_flavor = OutputParams::MathAsLaTeX;
3907 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3908 bool includeall, string & result_file) const
3910 LYXERR(Debug::FILES, "target=" << target);
3911 OutputParams runparams(¶ms().encoding());
3912 string format = target;
3913 string dest_filename;
3914 size_t pos = target.find(' ');
3915 if (pos != string::npos) {
3916 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
3917 format = target.substr(0, pos);
3918 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
3919 FileName(dest_filename).onlyPath().createPath();
3920 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
3922 MarkAsExporting exporting(this);
3923 string backend_format;
3924 runparams.flavor = OutputParams::LATEX;
3925 runparams.linelen = lyxrc.plaintext_linelen;
3926 runparams.includeall = includeall;
3927 vector<string> backs = params().backends();
3928 Converters converters = theConverters();
3929 bool need_nice_file = false;
3930 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3931 // Get shortest path to format
3932 converters.buildGraph();
3933 Graph::EdgePath path;
3934 for (vector<string>::const_iterator it = backs.begin();
3935 it != backs.end(); ++it) {
3936 Graph::EdgePath p = converters.getPath(*it, format);
3937 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3938 backend_format = *it;
3943 if (!put_in_tempdir) {
3944 // Only show this alert if this is an export to a non-temporary
3945 // file (not for previewing).
3946 Alert::error(_("Couldn't export file"), bformat(
3947 _("No information for exporting the format %1$s."),
3948 formats.prettyName(format)));
3950 return ExportNoPathToFormat;
3952 runparams.flavor = converters.getFlavor(path, this);
3953 Graph::EdgePath::const_iterator it = path.begin();
3954 Graph::EdgePath::const_iterator en = path.end();
3955 for (; it != en; ++it)
3956 if (theConverters().get(*it).nice) {
3957 need_nice_file = true;
3962 backend_format = format;
3963 LYXERR(Debug::FILES, "backend_format=" << backend_format);
3964 // FIXME: Don't hardcode format names here, but use a flag
3965 if (backend_format == "pdflatex")
3966 runparams.flavor = OutputParams::PDFLATEX;
3967 else if (backend_format == "luatex")
3968 runparams.flavor = OutputParams::LUATEX;
3969 else if (backend_format == "dviluatex")
3970 runparams.flavor = OutputParams::DVILUATEX;
3971 else if (backend_format == "xetex")
3972 runparams.flavor = OutputParams::XETEX;
3975 string filename = latexName(false);
3976 filename = addName(temppath(), filename);
3977 filename = changeExtension(filename,
3978 formats.extension(backend_format));
3979 LYXERR(Debug::FILES, "filename=" << filename);
3981 // Plain text backend
3982 if (backend_format == "text") {
3983 runparams.flavor = OutputParams::TEXT;
3984 writePlaintextFile(*this, FileName(filename), runparams);
3987 else if (backend_format == "xhtml") {
3988 runparams.flavor = OutputParams::HTML;
3989 setMathFlavor(runparams);
3990 makeLyXHTMLFile(FileName(filename), runparams);
3991 } else if (backend_format == "lyx")
3992 writeFile(FileName(filename));
3994 else if (params().isDocBook()) {
3995 runparams.nice = !put_in_tempdir;
3996 makeDocBookFile(FileName(filename), runparams);
3999 else if (backend_format == format || need_nice_file) {
4000 runparams.nice = true;
4001 bool const success = makeLaTeXFile(FileName(filename), string(), runparams);
4002 if (d->cloned_buffer_)
4003 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4006 } else if (!lyxrc.tex_allows_spaces
4007 && contains(filePath(), ' ')) {
4008 Alert::error(_("File name error"),
4009 _("The directory path to the document cannot contain spaces."));
4010 return ExportTexPathHasSpaces;
4012 runparams.nice = false;
4013 bool const success = makeLaTeXFile(
4014 FileName(filename), filePath(), runparams);
4015 if (d->cloned_buffer_)
4016 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4021 string const error_type = (format == "program")
4022 ? "Build" : params().bufferFormat();
4023 ErrorList & error_list = d->errorLists[error_type];
4024 string const ext = formats.extension(format);
4025 FileName const tmp_result_file(changeExtension(filename, ext));
4026 bool const success = converters.convert(this, FileName(filename),
4027 tmp_result_file, FileName(absFileName()), backend_format, format,
4030 // Emit the signal to show the error list or copy it back to the
4031 // cloned Buffer so that it can be emitted afterwards.
4032 if (format != backend_format) {
4033 if (runparams.silent)
4035 else if (d->cloned_buffer_)
4036 d->cloned_buffer_->d->errorLists[error_type] =
4037 d->errorLists[error_type];
4040 // also to the children, in case of master-buffer-view
4041 ListOfBuffers clist = getDescendents();
4042 ListOfBuffers::const_iterator cit = clist.begin();
4043 ListOfBuffers::const_iterator const cen = clist.end();
4044 for (; cit != cen; ++cit) {
4045 if (runparams.silent)
4046 (*cit)->d->errorLists[error_type].clear();
4047 else if (d->cloned_buffer_) {
4048 // Enable reverse search by copying back the
4049 // texrow object to the cloned buffer.
4050 // FIXME: this is not thread safe.
4051 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
4052 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
4053 (*cit)->d->errorLists[error_type];
4055 (*cit)->errors(error_type, true);
4059 if (d->cloned_buffer_) {
4060 // Enable reverse dvi or pdf to work by copying back the texrow
4061 // object to the cloned buffer.
4062 // FIXME: There is a possibility of concurrent access to texrow
4063 // here from the main GUI thread that should be securized.
4064 d->cloned_buffer_->d->texrow = d->texrow;
4065 string const error_type = params().bufferFormat();
4066 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
4070 return ExportConverterError;
4072 if (put_in_tempdir) {
4073 result_file = tmp_result_file.absFileName();
4074 return ExportSuccess;
4077 if (dest_filename.empty())
4078 result_file = changeExtension(d->exportFileName().absFileName(), ext);
4080 result_file = dest_filename;
4081 // We need to copy referenced files (e. g. included graphics
4082 // if format == "dvi") to the result dir.
4083 vector<ExportedFile> const files =
4084 runparams.exportdata->externalFiles(format);
4085 string const dest = runparams.export_folder.empty() ?
4086 onlyPath(result_file) : runparams.export_folder;
4087 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
4088 : force_overwrite == ALL_FILES;
4089 CopyStatus status = use_force ? FORCE : SUCCESS;
4091 vector<ExportedFile>::const_iterator it = files.begin();
4092 vector<ExportedFile>::const_iterator const en = files.end();
4093 for (; it != en && status != CANCEL; ++it) {
4094 string const fmt = formats.getFormatFromFile(it->sourceName);
4095 string fixedName = it->exportName;
4096 if (!runparams.export_folder.empty()) {
4097 // Relative pathnames starting with ../ will be sanitized
4098 // if exporting to a different folder
4099 while (fixedName.substr(0, 3) == "../")
4100 fixedName = fixedName.substr(3, fixedName.length() - 3);
4102 FileName fixedFileName = makeAbsPath(fixedName, dest);
4103 fixedFileName.onlyPath().createPath();
4104 status = copyFile(fmt, it->sourceName,
4106 it->exportName, status == FORCE,
4107 runparams.export_folder.empty());
4110 if (status == CANCEL) {
4111 message(_("Document export cancelled."));
4112 return ExportCancel;
4115 if (tmp_result_file.exists()) {
4116 // Finally copy the main file
4117 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
4118 : force_overwrite != NO_FILES;
4119 if (status == SUCCESS && use_force)
4121 status = copyFile(format, tmp_result_file,
4122 FileName(result_file), result_file,
4124 if (status == CANCEL) {
4125 message(_("Document export cancelled."));
4126 return ExportCancel;
4128 message(bformat(_("Document exported as %1$s "
4130 formats.prettyName(format),
4131 makeDisplayPath(result_file)));
4134 // This must be a dummy converter like fax (bug 1888)
4135 message(bformat(_("Document exported as %1$s"),
4136 formats.prettyName(format)));
4139 return ExportSuccess;
4143 Buffer::ExportStatus Buffer::preview(string const & format) const
4145 bool const update_unincluded =
4146 params().maintain_unincluded_children
4147 && !params().getIncludedChildren().empty();
4148 return preview(format, update_unincluded);
4151 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4153 MarkAsExporting exporting(this);
4155 // (1) export with all included children (omit \includeonly)
4157 ExportStatus const status = doExport(format, true, true, result_file);
4158 if (status != ExportSuccess)
4161 // (2) export with included children only
4162 ExportStatus const status = doExport(format, true, false, result_file);
4163 if (status != ExportSuccess)
4165 if (!formats.view(*this, FileName(result_file), format))
4166 return PreviewError;
4167 return PreviewSuccess;
4171 Buffer::ReadStatus Buffer::extractFromVC()
4173 bool const found = LyXVC::file_not_found_hook(d->filename);
4175 return ReadFileNotFound;
4176 if (!d->filename.isReadableFile())
4182 Buffer::ReadStatus Buffer::loadEmergency()
4184 FileName const emergencyFile = getEmergencyFileName();
4185 if (!emergencyFile.exists()
4186 || emergencyFile.lastModified() <= d->filename.lastModified())
4187 return ReadFileNotFound;
4189 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4190 docstring const text = bformat(_("An emergency save of the document "
4191 "%1$s exists.\n\nRecover emergency save?"), file);
4193 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4194 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4200 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4201 bool const success = (ret_llf == ReadSuccess);
4204 Alert::warning(_("File is read-only"),
4205 bformat(_("An emergency file is successfully loaded, "
4206 "but the original file %1$s is marked read-only. "
4207 "Please make sure to save the document as a different "
4208 "file."), from_utf8(d->filename.absFileName())));
4211 lyxvc().file_found_hook(d->filename);
4212 str = _("Document was successfully recovered.");
4214 str = _("Document was NOT successfully recovered.");
4215 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4216 makeDisplayPath(emergencyFile.absFileName()));
4218 int const del_emerg =
4219 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4220 _("&Remove"), _("&Keep"));
4221 if (del_emerg == 0) {
4222 emergencyFile.removeFile();
4224 Alert::warning(_("Emergency file deleted"),
4225 _("Do not forget to save your file now!"), true);
4227 return success ? ReadSuccess : ReadEmergencyFailure;
4230 int const del_emerg =
4231 Alert::prompt(_("Delete emergency file?"),
4232 _("Remove emergency file now?"), 1, 1,
4233 _("&Remove"), _("&Keep"));
4235 emergencyFile.removeFile();
4236 return ReadOriginal;
4246 Buffer::ReadStatus Buffer::loadAutosave()
4248 // Now check if autosave file is newer.
4249 FileName const autosaveFile = getAutosaveFileName();
4250 if (!autosaveFile.exists()
4251 || autosaveFile.lastModified() <= d->filename.lastModified())
4252 return ReadFileNotFound;
4254 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4255 docstring const text = bformat(_("The backup of the document %1$s "
4256 "is newer.\n\nLoad the backup instead?"), file);
4257 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4258 _("&Load backup"), _("Load &original"), _("&Cancel"));
4263 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4264 // the file is not saved if we load the autosave file.
4265 if (ret_llf == ReadSuccess) {
4267 Alert::warning(_("File is read-only"),
4268 bformat(_("A backup file is successfully loaded, "
4269 "but the original file %1$s is marked read-only. "
4270 "Please make sure to save the document as a "
4272 from_utf8(d->filename.absFileName())));
4275 lyxvc().file_found_hook(d->filename);
4278 return ReadAutosaveFailure;
4281 // Here we delete the autosave
4282 autosaveFile.removeFile();
4283 return ReadOriginal;
4291 Buffer::ReadStatus Buffer::loadLyXFile()
4293 if (!d->filename.isReadableFile()) {
4294 ReadStatus const ret_rvc = extractFromVC();
4295 if (ret_rvc != ReadSuccess)
4299 ReadStatus const ret_re = loadEmergency();
4300 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4303 ReadStatus const ret_ra = loadAutosave();
4304 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4307 return loadThisLyXFile(d->filename);
4311 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4313 return readFile(fn);
4317 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4319 TeXErrors::Errors::const_iterator it = terr.begin();
4320 TeXErrors::Errors::const_iterator end = terr.end();
4321 ListOfBuffers clist = getDescendents();
4322 ListOfBuffers::const_iterator cen = clist.end();
4324 for (; it != end; ++it) {
4327 int errorRow = it->error_in_line;
4328 Buffer const * buf = 0;
4330 if (it->child_name.empty())
4331 p->texrow.getIdFromRow(errorRow, id_start, pos_start);
4333 // The error occurred in a child
4334 ListOfBuffers::const_iterator cit = clist.begin();
4335 for (; cit != cen; ++cit) {
4336 string const child_name =
4337 DocFileName(changeExtension(
4338 (*cit)->absFileName(), "tex")).
4340 if (it->child_name != child_name)
4342 (*cit)->d->texrow.getIdFromRow(errorRow,
4343 id_start, pos_start);
4344 if (id_start != -1) {
4345 buf = d->cloned_buffer_
4346 ? (*cit)->d->cloned_buffer_->d->owner_
4347 : (*cit)->d->owner_;
4358 found = p->texrow.getIdFromRow(errorRow, id_end, pos_end);
4359 } while (found && id_start == id_end && pos_start == pos_end);
4361 if (id_start != id_end) {
4362 // Next registered position is outside the inset where
4363 // the error occurred, so signal end-of-paragraph
4367 errorList.push_back(ErrorItem(it->error_desc,
4368 it->error_text, id_start, pos_start, pos_end, buf));
4373 void Buffer::setBuffersForInsets() const
4375 inset().setBuffer(const_cast<Buffer &>(*this));
4379 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4381 LBUFERR(!text().paragraphs().empty());
4383 // Use the master text class also for child documents
4384 Buffer const * const master = masterBuffer();
4385 DocumentClass const & textclass = master->params().documentClass();
4387 // do this only if we are the top-level Buffer
4388 if (master == this) {
4389 textclass.counters().reset(from_ascii("bibitem"));
4390 reloadBibInfoCache();
4393 // keep the buffers to be children in this set. If the call from the
4394 // master comes back we can see which of them were actually seen (i.e.
4395 // via an InsetInclude). The remaining ones in the set need still be updated.
4396 static std::set<Buffer const *> bufToUpdate;
4397 if (scope == UpdateMaster) {
4398 // If this is a child document start with the master
4399 if (master != this) {
4400 bufToUpdate.insert(this);
4401 master->updateBuffer(UpdateMaster, utype);
4402 // If the master buffer has no gui associated with it, then the TocModel is
4403 // not updated during the updateBuffer call and TocModel::toc_ is invalid
4404 // (bug 5699). The same happens if the master buffer is open in a different
4405 // window. This test catches both possibilities.
4406 // See: http://marc.info/?l=lyx-devel&m=138590578911716&w=2
4407 // There remains a problem here: If there is another child open in yet a third
4408 // window, that TOC is not updated. So some more general solution is needed at
4410 if (master->d->gui_ != d->gui_)
4413 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4414 if (bufToUpdate.find(this) == bufToUpdate.end())
4418 // start over the counters in the master
4419 textclass.counters().reset();
4422 // update will be done below for this buffer
4423 bufToUpdate.erase(this);
4425 // update all caches
4426 clearReferenceCache();
4429 Buffer & cbuf = const_cast<Buffer &>(*this);
4432 ParIterator parit = cbuf.par_iterator_begin();
4433 updateBuffer(parit, utype);
4436 // TocBackend update will be done later.
4439 d->bibinfo_cache_valid_ = true;
4440 d->cite_labels_valid_ = true;
4441 cbuf.tocBackend().update(utype == OutputUpdate);
4442 if (scope == UpdateMaster)
4443 cbuf.structureChanged();
4447 static depth_type getDepth(DocIterator const & it)
4449 depth_type depth = 0;
4450 for (size_t i = 0 ; i < it.depth() ; ++i)
4451 if (!it[i].inset().inMathed())
4452 depth += it[i].paragraph().getDepth() + 1;
4453 // remove 1 since the outer inset does not count
4457 static depth_type getItemDepth(ParIterator const & it)
4459 Paragraph const & par = *it;
4460 LabelType const labeltype = par.layout().labeltype;
4462 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4465 // this will hold the lowest depth encountered up to now.
4466 depth_type min_depth = getDepth(it);
4467 ParIterator prev_it = it;
4470 --prev_it.top().pit();
4472 // start of nested inset: go to outer par
4474 if (prev_it.empty()) {
4475 // start of document: nothing to do
4480 // We search for the first paragraph with same label
4481 // that is not more deeply nested.
4482 Paragraph & prev_par = *prev_it;
4483 depth_type const prev_depth = getDepth(prev_it);
4484 if (labeltype == prev_par.layout().labeltype) {
4485 if (prev_depth < min_depth)
4486 return prev_par.itemdepth + 1;
4487 if (prev_depth == min_depth)
4488 return prev_par.itemdepth;
4490 min_depth = min(min_depth, prev_depth);
4491 // small optimization: if we are at depth 0, we won't
4492 // find anything else
4493 if (prev_depth == 0)
4499 static bool needEnumCounterReset(ParIterator const & it)
4501 Paragraph const & par = *it;
4502 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, return false);
4503 depth_type const cur_depth = par.getDepth();
4504 ParIterator prev_it = it;
4505 while (prev_it.pit()) {
4506 --prev_it.top().pit();
4507 Paragraph const & prev_par = *prev_it;
4508 if (prev_par.getDepth() <= cur_depth)
4509 return prev_par.layout().labeltype != LABEL_ENUMERATE;
4511 // start of nested inset: reset
4516 // set the label of a paragraph. This includes the counters.
4517 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4519 BufferParams const & bp = owner_->masterBuffer()->params();
4520 DocumentClass const & textclass = bp.documentClass();
4521 Paragraph & par = it.paragraph();
4522 Layout const & layout = par.layout();
4523 Counters & counters = textclass.counters();
4525 if (par.params().startOfAppendix()) {
4526 // We want to reset the counter corresponding to toplevel sectioning
4527 Layout const & lay = textclass.getTOCLayout();
4528 docstring const cnt = lay.counter;
4530 counters.reset(cnt);
4531 counters.appendix(true);
4533 par.params().appendix(counters.appendix());
4535 // Compute the item depth of the paragraph
4536 par.itemdepth = getItemDepth(it);
4538 if (layout.margintype == MARGIN_MANUAL) {
4539 if (par.params().labelWidthString().empty())
4540 par.params().labelWidthString(par.expandLabel(layout, bp));
4541 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4542 // we do not need to do anything here, since the empty case is
4543 // handled during export.
4545 par.params().labelWidthString(docstring());
4548 switch(layout.labeltype) {
4549 case LABEL_ITEMIZE: {
4550 // At some point of time we should do something more
4551 // clever here, like:
4552 // par.params().labelString(
4553 // bp.user_defined_bullet(par.itemdepth).getText());
4554 // for now, use a simple hardcoded label
4555 docstring itemlabel;
4556 switch (par.itemdepth) {
4558 itemlabel = char_type(0x2022);
4561 itemlabel = char_type(0x2013);
4564 itemlabel = char_type(0x2217);
4567 itemlabel = char_type(0x2219); // or 0x00b7
4570 par.params().labelString(itemlabel);
4574 case LABEL_ENUMERATE: {
4575 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4577 switch (par.itemdepth) {
4586 enumcounter += "iv";
4589 // not a valid enumdepth...
4593 // Maybe we have to reset the enumeration counter.
4594 if (needEnumCounterReset(it))
4595 counters.reset(enumcounter);
4596 counters.step(enumcounter, utype);
4598 string const & lang = par.getParLanguage(bp)->code();
4599 par.params().labelString(counters.theCounter(enumcounter, lang));
4604 case LABEL_SENSITIVE: {
4605 string const & type = counters.current_float();
4606 docstring full_label;
4608 full_label = owner_->B_("Senseless!!! ");
4610 docstring name = owner_->B_(textclass.floats().getType(type).name());
4611 if (counters.hasCounter(from_utf8(type))) {
4612 string const & lang = par.getParLanguage(bp)->code();
4613 counters.step(from_utf8(type), utype);
4614 full_label = bformat(from_ascii("%1$s %2$s:"),
4616 counters.theCounter(from_utf8(type), lang));
4618 full_label = bformat(from_ascii("%1$s #:"), name);
4620 par.params().labelString(full_label);
4624 case LABEL_NO_LABEL:
4625 par.params().labelString(docstring());
4629 case LABEL_CENTERED:
4630 case LABEL_STATIC: {
4631 docstring const & lcounter = layout.counter;
4632 if (!lcounter.empty()) {
4633 if (layout.toclevel <= bp.secnumdepth
4634 && (layout.latextype != LATEX_ENVIRONMENT
4635 || it.text()->isFirstInSequence(it.pit()))) {
4636 if (counters.hasCounter(lcounter))
4637 counters.step(lcounter, utype);
4638 par.params().labelString(par.expandLabel(layout, bp));
4640 par.params().labelString(docstring());
4642 par.params().labelString(par.expandLabel(layout, bp));
4648 par.params().labelString(par.expandLabel(layout, bp));
4653 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4655 // LASSERT: Is it safe to continue here, or should we just return?
4656 LASSERT(parit.pit() == 0, /**/);
4658 // Set the position of the text in the buffer to be able
4659 // to resolve macros in it.
4660 parit.text()->setMacrocontextPosition(parit);
4662 depth_type maxdepth = 0;
4663 pit_type const lastpit = parit.lastpit();
4664 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4665 // reduce depth if necessary
4666 if (parit->params().depth() > maxdepth) {
4667 /** FIXME: this function is const, but
4668 * nevertheless it modifies the buffer. To be
4669 * cleaner, one should modify the buffer in
4670 * another function, which is actually
4671 * non-const. This would however be costly in
4672 * terms of code duplication.
4674 const_cast<Buffer *>(this)->undo().recordUndo(CursorData(parit));
4675 parit->params().depth(maxdepth);
4677 maxdepth = parit->getMaxDepthAfter();
4679 if (utype == OutputUpdate) {
4680 // track the active counters
4681 // we have to do this for the master buffer, since the local
4682 // buffer isn't tracking anything.
4683 masterBuffer()->params().documentClass().counters().
4684 setActiveLayout(parit->layout());
4687 // set the counter for this paragraph
4688 d->setLabel(parit, utype);
4691 InsetList::const_iterator iit = parit->insetList().begin();
4692 InsetList::const_iterator end = parit->insetList().end();
4693 for (; iit != end; ++iit) {
4694 parit.pos() = iit->pos;
4695 iit->inset->updateBuffer(parit, utype);
4701 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4702 WordLangTuple & word_lang, docstring_list & suggestions) const
4706 suggestions.clear();
4707 word_lang = WordLangTuple();
4708 bool const to_end = to.empty();
4709 DocIterator const end = to_end ? doc_iterator_end(this) : to;
4710 // OK, we start from here.
4711 for (; from != end; from.forwardPos()) {
4712 // We are only interested in text so remove the math CursorSlice.
4713 while (from.inMathed()) {
4717 // If from is at the end of the document (which is possible
4718 // when leaving the mathed) LyX will crash later otherwise.
4719 if (from.atEnd() || (!to_end && from >= end))
4722 from.paragraph().spellCheck();
4723 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4724 if (SpellChecker::misspelled(res)) {
4729 // Do not increase progress when from == to, otherwise the word
4730 // count will be wrong.
4740 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
4742 bool inword = false;
4747 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
4748 if (!dit.inTexted()) {
4753 Paragraph const & par = dit.paragraph();
4754 pos_type const pos = dit.pos();
4756 // Copied and adapted from isWordSeparator() in Paragraph
4757 if (pos == dit.lastpos()) {
4760 Inset const * ins = par.getInset(pos);
4761 if (ins && skipNoOutput && !ins->producesOutput()) {
4764 // stop if end of range was skipped
4765 if (!to.atEnd() && dit >= to)
4768 } else if (!par.isDeleted(pos)) {
4769 if (par.isWordSeparator(pos))
4775 if (ins && ins->isLetter())
4777 else if (ins && ins->isSpace())
4780 char_type const c = par.getChar(pos);
4781 if (isPrintableNonspace(c))
4783 else if (isSpace(c))
4793 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
4795 d->updateStatistics(from, to, skipNoOutput);
4799 int Buffer::wordCount() const
4801 return d->wordCount();
4805 int Buffer::charCount(bool with_blanks) const
4807 return d->charCount(with_blanks);
4811 Buffer::ReadStatus Buffer::reload()
4814 // c.f. bug http://www.lyx.org/trac/ticket/6587
4815 removeAutosaveFile();
4816 // e.g., read-only status could have changed due to version control
4817 d->filename.refresh();
4818 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4820 // clear parent. this will get reset if need be.
4822 ReadStatus const status = loadLyXFile();
4823 if (status == ReadSuccess) {
4828 message(bformat(_("Document %1$s reloaded."), disp_fn));
4831 message(bformat(_("Could not reload document %1$s."), disp_fn));
4841 bool Buffer::saveAs(FileName const & fn)
4843 FileName const old_name = fileName();
4844 FileName const old_auto = getAutosaveFileName();
4845 bool const old_unnamed = isUnnamed();
4852 // bring the autosave file with us, just in case.
4853 moveAutosaveFile(old_auto);
4854 // validate version control data and
4855 // correct buffer title
4856 lyxvc().file_found_hook(fileName());
4858 // the file has now been saved to the new location.
4859 // we need to check that the locations of child buffers
4861 checkChildBuffers();
4862 checkMasterBuffer();
4866 // reset the old filename and unnamed state
4867 setFileName(old_name);
4868 setUnnamed(old_unnamed);
4874 // FIXME We could do better here, but it is complicated. What would be
4875 // nice is to offer either (a) to save the child buffer to an appropriate
4876 // location, so that it would "move with the master", or else (b) to update
4877 // the InsetInclude so that it pointed to the same file. But (a) is a bit
4878 // complicated, because the code for this lives in GuiView.
4879 void Buffer::checkChildBuffers()
4881 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4882 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4883 for (; it != en; ++it) {
4884 DocIterator dit = it->second;
4885 Buffer * cbuf = const_cast<Buffer *>(it->first);
4886 if (!cbuf || !theBufferList().isLoaded(cbuf))
4888 Inset * inset = dit.nextInset();
4889 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4890 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4891 docstring const & incfile = inset_inc->getParam("filename");
4892 string oldloc = cbuf->absFileName();
4893 string newloc = makeAbsPath(to_utf8(incfile),
4894 onlyPath(absFileName())).absFileName();
4895 if (oldloc == newloc)
4897 // the location of the child file is incorrect.
4898 Alert::warning(_("Included File Invalid"),
4899 bformat(_("Saving this document to a new location has made the file:\n"
4901 "inaccessible. You will need to update the included filename."),
4902 from_utf8(oldloc)));
4904 inset_inc->setChildBuffer(0);
4906 // invalidate cache of children
4907 d->children_positions.clear();
4908 d->position_to_children.clear();
4912 // If a child has been saved under a different name/path, it might have been
4913 // orphaned. Therefore the master needs to be reset (bug 8161).
4914 void Buffer::checkMasterBuffer()
4916 Buffer const * const master = masterBuffer();
4920 // necessary to re-register the child (bug 5873)
4921 // FIXME: clean up updateMacros (here, only
4922 // child registering is needed).
4923 master->updateMacros();
4924 // (re)set master as master buffer, but only
4925 // if we are a real child
4926 if (master->isChild(this))