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"
61 #include "TexStream.h"
63 #include "TextClass.h"
64 #include "TocBackend.h"
66 #include "VCBackend.h"
68 #include "WordLangTuple.h"
71 #include "insets/InsetBibtex.h"
72 #include "insets/InsetBranch.h"
73 #include "insets/InsetInclude.h"
74 #include "insets/InsetTabular.h"
75 #include "insets/InsetText.h"
77 #include "mathed/InsetMathHull.h"
78 #include "mathed/MacroTable.h"
79 #include "mathed/MathMacroTemplate.h"
80 #include "mathed/MathSupport.h"
82 #include "graphics/PreviewLoader.h"
84 #include "frontends/alert.h"
85 #include "frontends/Delegates.h"
86 #include "frontends/WorkAreaManager.h"
88 #include "support/lassert.h"
89 #include "support/convert.h"
90 #include "support/debug.h"
91 #include "support/docstring_list.h"
92 #include "support/ExceptionMessage.h"
93 #include "support/FileName.h"
94 #include "support/FileNameList.h"
95 #include "support/filetools.h"
96 #include "support/ForkedCalls.h"
97 #include "support/gettext.h"
98 #include "support/gzstream.h"
99 #include "support/lstrings.h"
100 #include "support/lyxalgo.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()
358 // We are in our own directory. Why bother to mangle name?
359 // In fact I wrote this code to circumvent a problematic behaviour
360 // (bug?) of EMX mkstemp().
361 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
362 convert<string>(count++));
364 if (!tmpfl.createDirectory(0777)) {
365 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
366 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
367 from_utf8(tmpfl.absFileName())));
373 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
374 Buffer const * cloned_buffer)
375 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
376 internal_buffer(false), read_only(readonly_), filename(file),
377 file_fully_loaded(false), ignore_parent(false), toc_backend(owner),
378 macro_lock(false), timestamp_(0), checksum_(0), wa_(0), gui_(0),
379 undo_(*owner), bibinfo_cache_valid_(false), bibfile_cache_valid_(false),
380 cite_labels_valid_(false), preview_loader_(0),
381 cloned_buffer_(cloned_buffer), clone_list_(0),
382 doing_export(false), parent_buffer(0)
384 if (!cloned_buffer_) {
385 temppath = createBufferTmpDir();
386 lyxvc.setBuffer(owner_);
388 wa_ = new frontend::WorkAreaManager;
391 temppath = cloned_buffer_->d->temppath;
392 file_fully_loaded = true;
393 params = cloned_buffer_->d->params;
394 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
395 bibinfo_ = cloned_buffer_->d->bibinfo_;
396 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
397 bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
398 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
399 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
400 unnamed = cloned_buffer_->d->unnamed;
401 internal_buffer = cloned_buffer_->d->internal_buffer;
405 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
406 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
408 LYXERR(Debug::INFO, "Buffer::Buffer()");
410 d->inset = new InsetText(*cloned_buffer->d->inset);
411 d->inset->setBuffer(*this);
412 // FIXME: optimize this loop somewhat, maybe by creating a new
413 // general recursive Inset::setId().
414 DocIterator it = doc_iterator_begin(this);
415 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
416 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
417 it.paragraph().setId(cloned_it.paragraph().id());
419 d->inset = new InsetText(this);
420 d->inset->setAutoBreakRows(true);
421 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
427 LYXERR(Debug::INFO, "Buffer::~Buffer()");
428 // here the buffer should take care that it is
429 // saved properly, before it goes into the void.
431 // GuiView already destroyed
435 // No need to do additional cleanups for internal buffer.
441 // this is in case of recursive includes: we won't try to delete
442 // ourselves as a child.
443 d->clone_list_->erase(this);
444 // loop over children
445 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
446 Impl::BufferPositionMap::iterator end = d->children_positions.end();
447 for (; it != end; ++it) {
448 Buffer * child = const_cast<Buffer *>(it->first);
449 if (d->clone_list_->erase(child))
452 // if we're the master buffer, then we should get rid of the list
455 // If this is not empty, we have leaked something. Worse, one of the
456 // children still has a reference to this list. But we will try to
457 // continue, rather than shut down.
458 LATTEST(d->clone_list_->empty());
459 list<CloneList *>::iterator it =
460 find(cloned_buffers.begin(), cloned_buffers.end(), d->clone_list_);
461 if (it == cloned_buffers.end()) {
462 // We will leak in this case, but it is safe to continue.
465 cloned_buffers.erase(it);
466 delete d->clone_list_;
468 // FIXME Do we really need to do this right before we delete d?
469 // clear references to children in macro tables
470 d->children_positions.clear();
471 d->position_to_children.clear();
473 // loop over children
474 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
475 Impl::BufferPositionMap::iterator end = d->children_positions.end();
476 for (; it != end; ++it) {
477 Buffer * child = const_cast<Buffer *>(it->first);
478 if (theBufferList().isLoaded(child))
479 theBufferList().releaseChild(this, child);
483 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
484 msg += emergencyWrite();
485 Alert::warning(_("Attempting to close changed document!"), msg);
488 // FIXME Do we really need to do this right before we delete d?
489 // clear references to children in macro tables
490 d->children_positions.clear();
491 d->position_to_children.clear();
493 if (!d->temppath.destroyDirectory()) {
494 Alert::warning(_("Could not remove temporary directory"),
495 bformat(_("Could not remove the temporary directory %1$s"),
496 from_utf8(d->temppath.absFileName())));
505 Buffer * Buffer::cloneFromMaster() const
508 cloned_buffers.push_back(new CloneList);
509 CloneList * clones = cloned_buffers.back();
511 masterBuffer()->cloneWithChildren(bufmap, clones);
513 // make sure we got cloned
514 BufferMap::const_iterator bit = bufmap.find(this);
515 LASSERT(bit != bufmap.end(), return 0);
516 Buffer * cloned_buffer = bit->second;
518 return cloned_buffer;
522 void Buffer::cloneWithChildren(BufferMap & bufmap, CloneList * clones) const
524 // have we already been cloned?
525 if (bufmap.find(this) != bufmap.end())
528 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
530 // The clone needs its own DocumentClass, since running updateBuffer() will
531 // modify it, and we would otherwise be sharing it with the original Buffer.
532 buffer_clone->params().makeDocumentClass(true);
534 cap::switchBetweenClasses(
535 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
536 static_cast<InsetText &>(buffer_clone->inset()), el);
538 bufmap[this] = buffer_clone;
539 clones->insert(buffer_clone);
540 buffer_clone->d->clone_list_ = clones;
541 buffer_clone->d->macro_lock = true;
542 buffer_clone->d->children_positions.clear();
544 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
545 // math macro caches need to be rethought and simplified.
546 // I am not sure wether we should handle Buffer cloning here or in BufferList.
547 // Right now BufferList knows nothing about buffer clones.
548 Impl::PositionScopeBufferMap::iterator it = d->position_to_children.begin();
549 Impl::PositionScopeBufferMap::iterator end = d->position_to_children.end();
550 for (; it != end; ++it) {
551 DocIterator dit = it->first.clone(buffer_clone);
552 dit.setBuffer(buffer_clone);
553 Buffer * child = const_cast<Buffer *>(it->second.second);
555 child->cloneWithChildren(bufmap, clones);
556 BufferMap::iterator const bit = bufmap.find(child);
557 LASSERT(bit != bufmap.end(), continue);
558 Buffer * child_clone = bit->second;
560 Inset * inset = dit.nextInset();
561 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
562 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
563 inset_inc->setChildBuffer(child_clone);
564 child_clone->d->setParent(buffer_clone);
565 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
566 buffer_clone->setChild(dit, child_clone);
568 buffer_clone->d->macro_lock = false;
573 Buffer * Buffer::cloneBufferOnly() const {
574 cloned_buffers.push_back(new CloneList);
575 CloneList * clones = cloned_buffers.back();
576 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
578 // The clone needs its own DocumentClass, since running updateBuffer() will
579 // modify it, and we would otherwise be sharing it with the original Buffer.
580 buffer_clone->params().makeDocumentClass(true);
582 cap::switchBetweenClasses(
583 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
584 static_cast<InsetText &>(buffer_clone->inset()), el);
586 clones->insert(buffer_clone);
587 buffer_clone->d->clone_list_ = clones;
589 // we won't be cloning the children
590 buffer_clone->d->children_positions.clear();
595 bool Buffer::isClone() const
597 return d->cloned_buffer_;
601 void Buffer::changed(bool update_metrics) const
604 d->wa_->redrawAll(update_metrics);
608 frontend::WorkAreaManager & Buffer::workAreaManager() const
615 Text & Buffer::text() const
617 return d->inset->text();
621 Inset & Buffer::inset() const
627 BufferParams & Buffer::params()
633 BufferParams const & Buffer::params() const
639 ParagraphList & Buffer::paragraphs()
641 return text().paragraphs();
645 ParagraphList const & Buffer::paragraphs() const
647 return text().paragraphs();
651 LyXVC & Buffer::lyxvc()
657 LyXVC const & Buffer::lyxvc() const
663 string const Buffer::temppath() const
665 return d->temppath.absFileName();
669 TexRow & Buffer::texrow()
675 TexRow const & Buffer::texrow() const
681 TocBackend & Buffer::tocBackend() const
683 return d->toc_backend;
687 Undo & Buffer::undo()
693 void Buffer::setChild(DocIterator const & dit, Buffer * child)
695 d->children_positions[child] = dit;
699 string Buffer::latexName(bool const no_path) const
701 FileName latex_name =
702 makeLatexName(d->exportFileName());
703 return no_path ? latex_name.onlyFileName()
704 : latex_name.absFileName();
708 FileName Buffer::Impl::exportFileName() const
710 docstring const branch_suffix =
711 params.branchlist().getFileNameSuffix();
712 if (branch_suffix.empty())
715 string const name = filename.onlyFileNameWithoutExt()
716 + to_utf8(branch_suffix);
717 FileName res(filename.onlyPath().absFileName() + "/" + name);
718 res.changeExtension(filename.extension());
724 string Buffer::logName(LogType * type) const
726 string const filename = latexName(false);
728 if (filename.empty()) {
734 string const path = temppath();
736 FileName const fname(addName(temppath(),
737 onlyFileName(changeExtension(filename,
740 // FIXME: how do we know this is the name of the build log?
741 FileName const bname(
742 addName(path, onlyFileName(
743 changeExtension(filename,
744 formats.extension(params().bufferFormat()) + ".out"))));
746 // Also consider the master buffer log file
747 FileName masterfname = fname;
749 if (masterBuffer() != this) {
750 string const mlogfile = masterBuffer()->logName(&mtype);
751 masterfname = FileName(mlogfile);
754 // If no Latex log or Build log is newer, show Build log
755 if (bname.exists() &&
756 ((!fname.exists() && !masterfname.exists())
757 || (fname.lastModified() < bname.lastModified()
758 && masterfname.lastModified() < bname.lastModified()))) {
759 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
762 return bname.absFileName();
763 // If we have a newer master file log or only a master log, show this
764 } else if (fname != masterfname
765 && (!fname.exists() && (masterfname.exists()
766 || fname.lastModified() < masterfname.lastModified()))) {
767 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
770 return masterfname.absFileName();
772 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
775 return fname.absFileName();
779 void Buffer::setReadonly(bool const flag)
781 if (d->read_only != flag) {
788 void Buffer::setFileName(FileName const & fname)
790 bool const changed = fname != d->filename;
793 lyxvc().file_found_hook(fname);
794 setReadonly(d->filename.isReadOnly());
800 int Buffer::readHeader(Lexer & lex)
802 int unknown_tokens = 0;
804 int begin_header_line = -1;
806 // Initialize parameters that may be/go lacking in header:
807 params().branchlist().clear();
808 params().preamble.erase();
809 params().options.erase();
810 params().master.erase();
811 params().float_placement.erase();
812 params().paperwidth.erase();
813 params().paperheight.erase();
814 params().leftmargin.erase();
815 params().rightmargin.erase();
816 params().topmargin.erase();
817 params().bottommargin.erase();
818 params().headheight.erase();
819 params().headsep.erase();
820 params().footskip.erase();
821 params().columnsep.erase();
822 params().fonts_cjk.erase();
823 params().listings_params.clear();
824 params().clearLayoutModules();
825 params().clearRemovedModules();
826 params().clearIncludedChildren();
827 params().pdfoptions().clear();
828 params().indiceslist().clear();
829 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
830 params().isbackgroundcolor = false;
831 params().fontcolor = RGBColor(0, 0, 0);
832 params().isfontcolor = false;
833 params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
834 params().boxbgcolor = RGBColor(0xFF, 0, 0);
835 params().html_latex_start.clear();
836 params().html_latex_end.clear();
837 params().html_math_img_scale = 1.0;
838 params().output_sync_macro.erase();
839 params().setLocalLayout(string(), false);
840 params().setLocalLayout(string(), true);
842 for (int i = 0; i < 4; ++i) {
843 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
844 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
847 ErrorList & errorList = d->errorLists["Parse"];
856 if (token == "\\end_header")
860 if (token == "\\begin_header") {
861 begin_header_line = line;
865 LYXERR(Debug::PARSER, "Handling document header token: `"
868 string unknown = params().readToken(lex, token, d->filename.onlyPath());
869 if (!unknown.empty()) {
870 if (unknown[0] != '\\' && token == "\\textclass") {
871 Alert::warning(_("Unknown document class"),
872 bformat(_("Using the default document class, because the "
873 "class %1$s is unknown."), from_utf8(unknown)));
876 docstring const s = bformat(_("Unknown token: "
880 errorList.push_back(ErrorItem(_("Document header error"),
885 if (begin_header_line) {
886 docstring const s = _("\\begin_header is missing");
887 errorList.push_back(ErrorItem(_("Document header error"),
891 params().makeDocumentClass();
893 return unknown_tokens;
898 // changed to be public and have one parameter
899 // Returns true if "\end_document" is not read (Asger)
900 bool Buffer::readDocument(Lexer & lex)
902 ErrorList & errorList = d->errorLists["Parse"];
905 // remove dummy empty par
906 paragraphs().clear();
908 if (!lex.checkFor("\\begin_document")) {
909 docstring const s = _("\\begin_document is missing");
910 errorList.push_back(ErrorItem(_("Document header error"),
916 if (params().outputChanges) {
917 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
918 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
919 LaTeXFeatures::isAvailable("xcolor");
921 if (!dvipost && !xcolorulem) {
922 Alert::warning(_("Changes not shown in LaTeX output"),
923 _("Changes will not be highlighted in LaTeX output, "
924 "because neither dvipost nor xcolor/ulem are installed.\n"
925 "Please install these packages or redefine "
926 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
927 } else if (!xcolorulem) {
928 Alert::warning(_("Changes not shown in LaTeX output"),
929 _("Changes will not be highlighted in LaTeX output "
930 "when using pdflatex, because xcolor and ulem are not installed.\n"
931 "Please install both packages or redefine "
932 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
936 if (!parent() && !params().master.empty()) {
937 FileName const master_file = makeAbsPath(params().master,
938 onlyPath(absFileName()));
939 if (isLyXFileName(master_file.absFileName())) {
941 checkAndLoadLyXFile(master_file, true);
943 // necessary e.g. after a reload
944 // to re-register the child (bug 5873)
945 // FIXME: clean up updateMacros (here, only
946 // child registering is needed).
947 master->updateMacros();
948 // set master as master buffer, but only
949 // if we are a real child
950 if (master->isChild(this))
952 // if the master is not fully loaded
953 // it is probably just loading this
954 // child. No warning needed then.
955 else if (master->isFullyLoaded())
956 LYXERR0("The master '"
958 << "' assigned to this document ("
960 << ") does not include "
961 "this document. Ignoring the master assignment.");
966 // assure we have a default index
967 params().indiceslist().addDefault(B_("Index"));
970 bool const res = text().read(lex, errorList, d->inset);
972 // inform parent buffer about local macros
974 Buffer const * pbuf = parent();
975 UserMacroSet::const_iterator cit = usermacros.begin();
976 UserMacroSet::const_iterator end = usermacros.end();
977 for (; cit != end; ++cit)
978 pbuf->usermacros.insert(*cit);
982 updateMacroInstances(InternalUpdate);
987 bool Buffer::importString(string const & format, docstring const & contents, ErrorList & errorList)
989 Format const * fmt = formats.getFormat(format);
992 // It is important to use the correct extension here, since some
993 // converters create a wrong output file otherwise (e.g. html2latex)
994 TempFile const tempfile("Buffer_importStringXXXXXX." + fmt->extension());
995 FileName const name(tempfile.name());
996 ofdocstream os(name.toFilesystemEncoding().c_str());
997 bool const success = (os << contents);
1000 bool converted = false;
1002 params().compressed = false;
1004 // remove dummy empty par
1005 paragraphs().clear();
1007 converted = importFile(format, name, errorList);
1016 bool Buffer::importFile(string const & format, FileName const & name, ErrorList & errorList)
1018 if (!theConverters().isReachable(format, "lyx"))
1021 TempFile const tempfile("Buffer_importFileXXXXXX.lyx");
1022 FileName const lyx(tempfile.name());
1023 if (theConverters().convert(0, name, lyx, name, format, "lyx", errorList))
1024 return readFile(lyx) == ReadSuccess;
1030 bool Buffer::readString(string const & s)
1032 params().compressed = false;
1035 istringstream is(s);
1037 FileName const fn = FileName::tempName("Buffer_readString");
1040 bool success = parseLyXFormat(lex, fn, file_format) == ReadSuccess;
1042 if (success && file_format != LYX_FORMAT) {
1043 // We need to call lyx2lyx, so write the input to a file
1044 ofstream os(fn.toFilesystemEncoding().c_str());
1047 // lyxvc in readFile
1048 if (readFile(fn) != ReadSuccess)
1052 if (readDocument(lex))
1060 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
1064 if (!lex.setFile(fname)) {
1065 Alert::error(_("File Not Found"),
1066 bformat(_("Unable to open file `%1$s'."),
1067 from_utf8(fn.absFileName())));
1068 return ReadFileNotFound;
1072 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
1073 if (ret_plf != ReadSuccess)
1076 if (file_format != LYX_FORMAT) {
1078 ReadStatus const ret_clf = convertLyXFormat(fn, tmpFile, file_format);
1079 if (ret_clf != ReadSuccess)
1081 return readFile(tmpFile);
1084 // FIXME: InsetInfo needs to know whether the file is under VCS
1085 // during the parse process, so this has to be done before.
1086 lyxvc().file_found_hook(d->filename);
1088 if (readDocument(lex)) {
1089 Alert::error(_("Document format failure"),
1090 bformat(_("%1$s ended unexpectedly, which means"
1091 " that it is probably corrupted."),
1092 from_utf8(fn.absFileName())));
1093 return ReadDocumentFailure;
1096 d->file_fully_loaded = true;
1097 d->read_only = !d->filename.isWritable();
1098 params().compressed = formats.isZippedFile(d->filename);
1104 bool Buffer::isFullyLoaded() const
1106 return d->file_fully_loaded;
1110 void Buffer::setFullyLoaded(bool value)
1112 d->file_fully_loaded = value;
1116 PreviewLoader * Buffer::loader() const
1118 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1120 if (!d->preview_loader_)
1121 d->preview_loader_ = new PreviewLoader(*this);
1122 return d->preview_loader_;
1126 void Buffer::removePreviews() const
1128 delete d->preview_loader_;
1129 d->preview_loader_ = 0;
1133 void Buffer::updatePreviews() const
1135 PreviewLoader * ploader = loader();
1139 InsetIterator it = inset_iterator_begin(*d->inset);
1140 InsetIterator const end = inset_iterator_end(*d->inset);
1141 for (; it != end; ++it)
1142 it->addPreview(it, *ploader);
1144 ploader->startLoading();
1148 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1149 FileName const & fn, int & file_format) const
1151 if(!lex.checkFor("\\lyxformat")) {
1152 Alert::error(_("Document format failure"),
1153 bformat(_("%1$s is not a readable LyX document."),
1154 from_utf8(fn.absFileName())));
1155 return ReadNoLyXFormat;
1161 // LyX formats 217 and earlier were written as 2.17. This corresponds
1162 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1163 // these cases. See also: www.lyx.org/trac/changeset/1313.
1164 size_t dot = tmp_format.find_first_of(".,");
1165 if (dot != string::npos)
1166 tmp_format.erase(dot, 1);
1168 file_format = convert<int>(tmp_format);
1173 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1174 FileName & tmpfile, int from_format)
1176 tmpfile = FileName::tempName("Buffer_convertLyXFormatXXXXXX.lyx");
1177 if(tmpfile.empty()) {
1178 Alert::error(_("Conversion failed"),
1179 bformat(_("%1$s is from a different"
1180 " version of LyX, but a temporary"
1181 " file for converting it could"
1182 " not be created."),
1183 from_utf8(fn.absFileName())));
1184 return LyX2LyXNoTempFile;
1187 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1188 if (lyx2lyx.empty()) {
1189 Alert::error(_("Conversion script not found"),
1190 bformat(_("%1$s is from a different"
1191 " version of LyX, but the"
1192 " conversion script lyx2lyx"
1193 " could not be found."),
1194 from_utf8(fn.absFileName())));
1195 return LyX2LyXNotFound;
1199 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1200 ostringstream command;
1201 command << os::python()
1202 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1203 << " -t " << convert<string>(LYX_FORMAT)
1204 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
1205 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1206 string const command_str = command.str();
1208 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1210 cmd_ret const ret = runCommand(command_str);
1211 if (ret.first != 0) {
1212 if (from_format < LYX_FORMAT) {
1213 Alert::error(_("Conversion script failed"),
1214 bformat(_("%1$s is from an older version"
1215 " of LyX and the lyx2lyx script"
1216 " failed to convert it."),
1217 from_utf8(fn.absFileName())));
1218 return LyX2LyXOlderFormat;
1220 Alert::error(_("Conversion script failed"),
1221 bformat(_("%1$s is from a newer version"
1222 " of LyX and the lyx2lyx script"
1223 " failed to convert it."),
1224 from_utf8(fn.absFileName())));
1225 return LyX2LyXNewerFormat;
1232 // Should probably be moved to somewhere else: BufferView? GuiView?
1233 bool Buffer::save() const
1235 docstring const file = makeDisplayPath(absFileName(), 20);
1236 d->filename.refresh();
1238 // check the read-only status before moving the file as a backup
1239 if (d->filename.exists()) {
1240 bool const read_only = !d->filename.isWritable();
1242 Alert::warning(_("File is read-only"),
1243 bformat(_("The file %1$s cannot be written because it "
1244 "is marked as read-only."), file));
1249 // ask if the disk file has been externally modified (use checksum method)
1250 if (fileName().exists() && isExternallyModified(checksum_method)) {
1252 bformat(_("Document %1$s has been externally modified. "
1253 "Are you sure you want to overwrite this file?"), file);
1254 int const ret = Alert::prompt(_("Overwrite modified file?"),
1255 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1260 // We don't need autosaves in the immediate future. (Asger)
1261 resetAutosaveTimers();
1263 FileName backupName;
1264 bool madeBackup = false;
1266 // make a backup if the file already exists
1267 if (lyxrc.make_backup && fileName().exists()) {
1268 backupName = FileName(absFileName() + '~');
1269 if (!lyxrc.backupdir_path.empty()) {
1270 string const mangledName =
1271 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1272 backupName = FileName(addName(lyxrc.backupdir_path,
1276 // Except file is symlink do not copy because of #6587.
1277 // Hard links have bad luck.
1278 if (fileName().isSymLink())
1279 madeBackup = fileName().copyTo(backupName);
1281 madeBackup = fileName().moveTo(backupName);
1284 Alert::error(_("Backup failure"),
1285 bformat(_("Cannot create backup file %1$s.\n"
1286 "Please check whether the directory exists and is writable."),
1287 from_utf8(backupName.absFileName())));
1288 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1292 if (writeFile(d->filename)) {
1296 // Saving failed, so backup is not backup
1298 backupName.moveTo(d->filename);
1304 bool Buffer::writeFile(FileName const & fname) const
1306 if (d->read_only && fname == d->filename)
1309 bool retval = false;
1311 docstring const str = bformat(_("Saving document %1$s..."),
1312 makeDisplayPath(fname.absFileName()));
1315 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1317 if (params().compressed) {
1318 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1319 retval = ofs && write(ofs);
1321 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1322 retval = ofs && write(ofs);
1326 message(str + _(" could not write file!"));
1331 // removeAutosaveFile();
1334 message(str + _(" done."));
1340 docstring Buffer::emergencyWrite()
1342 // No need to save if the buffer has not changed.
1346 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1348 docstring user_message = bformat(
1349 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1351 // We try to save three places:
1352 // 1) Same place as document. Unless it is an unnamed doc.
1354 string s = absFileName();
1357 if (writeFile(FileName(s))) {
1359 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1360 return user_message;
1362 user_message += " " + _("Save failed! Trying again...\n");
1366 // 2) In HOME directory.
1367 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1369 lyxerr << ' ' << s << endl;
1370 if (writeFile(FileName(s))) {
1372 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1373 return user_message;
1376 user_message += " " + _("Save failed! Trying yet again...\n");
1378 // 3) In "/tmp" directory.
1379 // MakeAbsPath to prepend the current
1380 // drive letter on OS/2
1381 s = addName(package().temp_dir().absFileName(), absFileName());
1383 lyxerr << ' ' << s << endl;
1384 if (writeFile(FileName(s))) {
1386 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1387 return user_message;
1390 user_message += " " + _("Save failed! Bummer. Document is lost.");
1393 return user_message;
1397 bool Buffer::write(ostream & ofs) const
1400 // Use the standard "C" locale for file output.
1401 ofs.imbue(locale::classic());
1404 // The top of the file should not be written by params().
1406 // write out a comment in the top of the file
1407 // Important: Keep the version formatting in sync with lyx2lyx and
1408 // tex2lyx (bug 7951)
1409 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1410 << " created this file. For more info see http://www.lyx.org/\n"
1411 << "\\lyxformat " << LYX_FORMAT << "\n"
1412 << "\\begin_document\n";
1414 /// For each author, set 'used' to true if there is a change
1415 /// by this author in the document; otherwise set it to 'false'.
1416 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1417 AuthorList::Authors::const_iterator a_end = params().authors().end();
1418 for (; a_it != a_end; ++a_it)
1419 a_it->setUsed(false);
1421 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1422 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1423 for ( ; it != end; ++it)
1424 it->checkAuthors(params().authors());
1426 // now write out the buffer parameters.
1427 ofs << "\\begin_header\n";
1428 params().writeFile(ofs);
1429 ofs << "\\end_header\n";
1432 ofs << "\n\\begin_body\n";
1434 ofs << "\n\\end_body\n";
1436 // Write marker that shows file is complete
1437 ofs << "\\end_document" << endl;
1439 // Shouldn't really be needed....
1442 // how to check if close went ok?
1443 // Following is an attempt... (BE 20001011)
1445 // good() returns false if any error occured, including some
1446 // formatting error.
1447 // bad() returns true if something bad happened in the buffer,
1448 // which should include file system full errors.
1453 lyxerr << "File was not closed properly." << endl;
1460 bool Buffer::makeLaTeXFile(FileName const & fname,
1461 string const & original_path,
1462 OutputParams const & runparams_in,
1463 OutputWhat output) const
1465 OutputParams runparams = runparams_in;
1467 // This is necessary for LuaTeX/XeTeX with tex fonts.
1468 // See FIXME in BufferParams::encoding()
1469 if (runparams.isFullUnicode())
1470 runparams.encoding = encodings.fromLyXName("utf8-plain");
1472 string const encoding = runparams.encoding->iconvName();
1473 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1476 try { ofs.reset(encoding); }
1477 catch (iconv_codecvt_facet_exception const & e) {
1478 lyxerr << "Caught iconv exception: " << e.what() << endl;
1479 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1480 "verify that the support software for your encoding (%1$s) is "
1481 "properly installed"), from_ascii(encoding)));
1484 if (!openFileWrite(ofs, fname))
1487 //TexStream ts(ofs.rdbuf(), &texrow());
1488 ErrorList & errorList = d->errorLists["Export"];
1490 bool failed_export = false;
1491 otexstream os(ofs, d->texrow);
1493 // make sure we are ready to export
1494 // this needs to be done before we validate
1495 // FIXME Do we need to do this all the time? I.e., in children
1496 // of a master we are exporting?
1498 updateMacroInstances(OutputUpdate);
1501 os.texrow().reset();
1502 writeLaTeXSource(os, original_path, runparams, output);
1504 catch (EncodingException const & e) {
1505 odocstringstream ods;
1506 ods.put(e.failed_char);
1508 oss << "0x" << hex << e.failed_char << dec;
1509 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1510 " (code point %2$s)"),
1511 ods.str(), from_utf8(oss.str()));
1512 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1513 "representable in the chosen encoding.\n"
1514 "Changing the document encoding to utf8 could help."),
1515 e.par_id, e.pos, e.pos + 1));
1516 failed_export = true;
1518 catch (iconv_codecvt_facet_exception const & e) {
1519 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1520 _(e.what()), -1, 0, 0));
1521 failed_export = true;
1523 catch (exception const & e) {
1524 errorList.push_back(ErrorItem(_("conversion failed"),
1525 _(e.what()), -1, 0, 0));
1526 failed_export = true;
1529 lyxerr << "Caught some really weird exception..." << endl;
1535 failed_export = true;
1536 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1539 if (runparams_in.silent)
1543 return !failed_export;
1547 void Buffer::writeLaTeXSource(otexstream & os,
1548 string const & original_path,
1549 OutputParams const & runparams_in,
1550 OutputWhat output) const
1552 // The child documents, if any, shall be already loaded at this point.
1554 OutputParams runparams = runparams_in;
1556 // If we are compiling a file standalone, even if this is the
1557 // child of some other buffer, let's cut the link here, so the
1558 // file is really independent and no concurring settings from
1559 // the master (e.g. branch state) interfere (see #8100).
1560 if (!runparams.is_child)
1561 d->ignore_parent = true;
1563 // Classify the unicode characters appearing in math insets
1564 BufferEncodings::initUnicodeMath(*this);
1566 // validate the buffer.
1567 LYXERR(Debug::LATEX, " Validating buffer...");
1568 LaTeXFeatures features(*this, params(), runparams);
1570 // This is only set once per document (in master)
1571 if (!runparams.is_child)
1572 runparams.use_polyglossia = features.usePolyglossia();
1573 LYXERR(Debug::LATEX, " Buffer validation done.");
1575 bool const output_preamble =
1576 output == FullSource || output == OnlyPreamble;
1577 bool const output_body =
1578 output == FullSource || output == OnlyBody;
1580 // The starting paragraph of the coming rows is the
1581 // first paragraph of the document. (Asger)
1582 if (output_preamble && runparams.nice) {
1583 os << "%% LyX " << lyx_version << " created this file. "
1584 "For more info, see http://www.lyx.org/.\n"
1585 "%% Do not edit unless you really know what "
1588 LYXERR(Debug::INFO, "lyx document header finished");
1590 // There are a few differences between nice LaTeX and usual files:
1591 // usual files have \batchmode and special input@path to allow
1592 // inclusion of figures specified by an explicitly relative path
1593 // (i.e., a path starting with './' or '../') with either \input or
1594 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1595 // input@path is set when the actual parameter original_path is set.
1596 // This is done for usual tex-file, but not for nice-latex-file.
1597 // (Matthias 250696)
1598 // Note that input@path is only needed for something the user does
1599 // in the preamble, included .tex files or ERT, files included by
1600 // LyX work without it.
1601 if (output_preamble) {
1602 if (!runparams.nice) {
1603 // code for usual, NOT nice-latex-file
1604 os << "\\batchmode\n"; // changed from \nonstopmode
1606 if (!original_path.empty()) {
1608 // We don't know the encoding of inputpath
1609 docstring const inputpath = from_utf8(original_path);
1610 docstring uncodable_glyphs;
1611 Encoding const * const enc = runparams.encoding;
1613 for (size_t n = 0; n < inputpath.size(); ++n) {
1614 if (!enc->encodable(inputpath[n])) {
1615 docstring const glyph(1, inputpath[n]);
1616 LYXERR0("Uncodable character '"
1618 << "' in input path!");
1619 uncodable_glyphs += glyph;
1624 // warn user if we found uncodable glyphs.
1625 if (!uncodable_glyphs.empty()) {
1626 frontend::Alert::warning(
1627 _("Uncodable character in file path"),
1629 _("The path of your document\n"
1631 "contains glyphs that are unknown "
1632 "in the current document encoding "
1633 "(namely %2$s). This may result in "
1634 "incomplete output, unless "
1635 "TEXINPUTS contains the document "
1636 "directory and you don't use "
1637 "explicitly relative paths (i.e., "
1638 "paths starting with './' or "
1639 "'../') in the preamble or in ERT."
1640 "\n\nIn case of problems, choose "
1641 "an appropriate document encoding\n"
1642 "(such as utf8) or change the "
1644 inputpath, uncodable_glyphs));
1647 support::latex_path(original_path);
1648 if (contains(docdir, '#')) {
1649 docdir = subst(docdir, "#", "\\#");
1650 os << "\\catcode`\\#=11"
1651 "\\def\\#{#}\\catcode`\\#=6\n";
1653 if (contains(docdir, '%')) {
1654 docdir = subst(docdir, "%", "\\%");
1655 os << "\\catcode`\\%=11"
1656 "\\def\\%{%}\\catcode`\\%=14\n";
1658 os << "\\makeatletter\n"
1659 << "\\def\\input@path{{"
1660 << docdir << "/}}\n"
1661 << "\\makeatother\n";
1665 // get parent macros (if this buffer has a parent) which will be
1666 // written at the document begin further down.
1667 MacroSet parentMacros;
1668 listParentMacros(parentMacros, features);
1670 // Write the preamble
1671 runparams.use_babel = params().writeLaTeX(os, features,
1672 d->filename.onlyPath());
1674 // Japanese might be required only in some children of a document,
1675 // but once required, we must keep use_japanese true.
1676 runparams.use_japanese |= features.isRequired("japanese");
1679 // Restore the parenthood if needed
1680 if (!runparams.is_child)
1681 d->ignore_parent = false;
1686 os << "\\begin{document}\n";
1688 // output the parent macros
1689 MacroSet::iterator it = parentMacros.begin();
1690 MacroSet::iterator end = parentMacros.end();
1691 for (; it != end; ++it) {
1692 int num_lines = (*it)->write(os.os(), true);
1693 os.texrow().newlines(num_lines);
1696 } // output_preamble
1698 os.texrow().start(paragraphs().begin()->id(), 0);
1700 LYXERR(Debug::INFO, "preamble finished, now the body.");
1703 latexParagraphs(*this, text(), os, runparams);
1705 // Restore the parenthood if needed
1706 if (!runparams.is_child)
1707 d->ignore_parent = false;
1709 // add this just in case after all the paragraphs
1712 if (output_preamble) {
1713 os << "\\end{document}\n";
1714 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1716 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1718 runparams_in.encoding = runparams.encoding;
1720 // Just to be sure. (Asger)
1721 os.texrow().newline();
1723 //for (int i = 0; i<d->texrow.rows(); i++) {
1725 // if (d->texrow.getIdFromRow(i+1,id,pos) && id>0)
1726 // lyxerr << i+1 << ":" << id << ":" << getParFromID(id).paragraph().asString()<<"\n";
1729 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1730 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
1734 void Buffer::makeDocBookFile(FileName const & fname,
1735 OutputParams const & runparams,
1736 OutputWhat output) const
1738 LYXERR(Debug::LATEX, "makeDocBookFile...");
1741 if (!openFileWrite(ofs, fname))
1744 // make sure we are ready to export
1745 // this needs to be done before we validate
1747 updateMacroInstances(OutputUpdate);
1749 writeDocBookSource(ofs, fname.absFileName(), runparams, output);
1753 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1757 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1758 OutputParams const & runparams,
1759 OutputWhat output) const
1761 LaTeXFeatures features(*this, params(), runparams);
1766 DocumentClass const & tclass = params().documentClass();
1767 string const top_element = tclass.latexname();
1769 bool const output_preamble =
1770 output == FullSource || output == OnlyPreamble;
1771 bool const output_body =
1772 output == FullSource || output == OnlyBody;
1774 if (output_preamble) {
1775 if (runparams.flavor == OutputParams::XML)
1776 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1779 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1782 if (! tclass.class_header().empty())
1783 os << from_ascii(tclass.class_header());
1784 else if (runparams.flavor == OutputParams::XML)
1785 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1786 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1788 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1790 docstring preamble = from_utf8(params().preamble);
1791 if (runparams.flavor != OutputParams::XML ) {
1792 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1793 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1794 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1795 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1798 string const name = runparams.nice
1799 ? changeExtension(absFileName(), ".sgml") : fname;
1800 preamble += features.getIncludedFiles(name);
1801 preamble += features.getLyXSGMLEntities();
1803 if (!preamble.empty()) {
1804 os << "\n [ " << preamble << " ]";
1810 string top = top_element;
1812 if (runparams.flavor == OutputParams::XML)
1813 top += params().language->code();
1815 top += params().language->code().substr(0, 2);
1818 if (!params().options.empty()) {
1820 top += params().options;
1823 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1824 << " file was created by LyX " << lyx_version
1825 << "\n See http://www.lyx.org/ for more information -->\n";
1827 params().documentClass().counters().reset();
1829 sgml::openTag(os, top);
1831 docbookParagraphs(text(), *this, os, runparams);
1832 sgml::closeTag(os, top_element);
1837 void Buffer::makeLyXHTMLFile(FileName const & fname,
1838 OutputParams const & runparams) const
1840 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1843 if (!openFileWrite(ofs, fname))
1846 // make sure we are ready to export
1847 // this has to be done before we validate
1848 updateBuffer(UpdateMaster, OutputUpdate);
1849 updateMacroInstances(OutputUpdate);
1851 writeLyXHTMLSource(ofs, runparams, FullSource);
1855 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1859 void Buffer::writeLyXHTMLSource(odocstream & os,
1860 OutputParams const & runparams,
1861 OutputWhat output) const
1863 LaTeXFeatures features(*this, params(), runparams);
1865 d->bibinfo_.makeCitationLabels(*this);
1867 bool const output_preamble =
1868 output == FullSource || output == OnlyPreamble;
1869 bool const output_body =
1870 output == FullSource || output == OnlyBody || output == IncludedFile;
1872 if (output_preamble) {
1873 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1874 << "<!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"
1875 // FIXME Language should be set properly.
1876 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
1878 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
1879 // FIXME Presumably need to set this right
1880 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1882 docstring const & doctitle = features.htmlTitle();
1884 << (doctitle.empty() ?
1885 from_ascii("LyX Document") :
1886 html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
1889 docstring styles = features.getTClassHTMLPreamble();
1890 if (!styles.empty())
1891 os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
1893 styles = from_utf8(features.getPreambleSnippets());
1894 if (!styles.empty())
1895 os << "\n<!-- Preamble Snippets -->\n" << styles << '\n';
1897 // we will collect CSS information in a stream, and then output it
1898 // either here, as part of the header, or else in a separate file.
1899 odocstringstream css;
1900 styles = from_utf8(features.getCSSSnippets());
1901 if (!styles.empty())
1902 css << "/* LyX Provided Styles */\n" << styles << '\n';
1904 styles = features.getTClassHTMLStyles();
1905 if (!styles.empty())
1906 css << "/* Layout-provided Styles */\n" << styles << '\n';
1908 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
1909 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
1910 if (needfg || needbg) {
1911 css << "\nbody {\n";
1914 << from_ascii(X11hexname(params().fontcolor))
1917 css << " background-color: "
1918 << from_ascii(X11hexname(params().backgroundcolor))
1923 docstring const dstyles = css.str();
1924 if (!dstyles.empty()) {
1925 bool written = false;
1926 if (params().html_css_as_file) {
1927 // open a file for CSS info
1929 string const fcssname = addName(temppath(), "docstyle.css");
1930 FileName const fcssfile = FileName(fcssname);
1931 if (openFileWrite(ocss, fcssfile)) {
1935 // write link to header
1936 os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
1938 runparams.exportdata->addExternalFile("xhtml", fcssfile);
1941 // we are here if the CSS is supposed to be written to the header
1942 // or if we failed to write it to an external file.
1944 os << "<style type='text/css'>\n"
1953 bool const output_body_tag = (output != IncludedFile);
1954 if (output_body_tag)
1957 if (output != IncludedFile)
1958 // if we're an included file, the counters are in the master.
1959 params().documentClass().counters().reset();
1960 xhtmlParagraphs(text(), *this, xs, runparams);
1961 if (output_body_tag)
1965 if (output_preamble)
1970 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1971 // Other flags: -wall -v0 -x
1972 int Buffer::runChktex()
1976 // get LaTeX-Filename
1977 FileName const path(temppath());
1978 string const name = addName(path.absFileName(), latexName());
1979 string const org_path = filePath();
1981 PathChanger p(path); // path to LaTeX file
1982 message(_("Running chktex..."));
1984 // Generate the LaTeX file if neccessary
1985 OutputParams runparams(¶ms().encoding());
1986 runparams.flavor = OutputParams::LATEX;
1987 runparams.nice = false;
1988 runparams.linelen = lyxrc.plaintext_linelen;
1989 makeLaTeXFile(FileName(name), org_path, runparams);
1992 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
1993 int const res = chktex.run(terr); // run chktex
1996 Alert::error(_("chktex failure"),
1997 _("Could not run chktex successfully."));
1999 ErrorList & errlist = d->errorLists["ChkTeX"];
2001 bufferErrors(terr, errlist);
2006 if (runparams.silent)
2007 d->errorLists["ChkTeX"].clear();
2015 void Buffer::validate(LaTeXFeatures & features) const
2017 // Validate the buffer params, but not for included
2018 // files, since they also use the parent buffer's
2020 if (!features.runparams().is_child)
2021 params().validate(features);
2023 for_each(paragraphs().begin(), paragraphs().end(),
2024 bind(&Paragraph::validate, _1, ref(features)));
2026 if (lyxerr.debugging(Debug::LATEX)) {
2027 features.showStruct();
2032 void Buffer::getLabelList(vector<docstring> & list) const
2034 // If this is a child document, use the master's list instead.
2036 masterBuffer()->getLabelList(list);
2041 Toc & toc = d->toc_backend.toc("label");
2042 TocIterator toc_it = toc.begin();
2043 TocIterator end = toc.end();
2044 for (; toc_it != end; ++toc_it) {
2045 if (toc_it->depth() == 0)
2046 list.push_back(toc_it->str());
2051 void Buffer::updateBibfilesCache(UpdateScope scope) const
2053 // FIXME This is probably unnecssary, given where we call this.
2054 // If this is a child document, use the parent's cache instead.
2055 if (parent() && scope != UpdateChildOnly) {
2056 masterBuffer()->updateBibfilesCache();
2060 d->bibfiles_cache_.clear();
2061 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2062 if (it->lyxCode() == BIBTEX_CODE) {
2063 InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
2064 support::FileNameList const bibfiles = inset.getBibFiles();
2065 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2068 } else if (it->lyxCode() == INCLUDE_CODE) {
2069 InsetInclude & inset = static_cast<InsetInclude &>(*it);
2070 Buffer const * const incbuf = inset.getChildBuffer();
2073 support::FileNameList const & bibfiles =
2074 incbuf->getBibfilesCache(UpdateChildOnly);
2075 if (!bibfiles.empty()) {
2076 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2082 d->bibfile_cache_valid_ = true;
2083 d->bibinfo_cache_valid_ = false;
2084 d->cite_labels_valid_ = false;
2088 void Buffer::invalidateBibinfoCache() const
2090 d->bibinfo_cache_valid_ = false;
2091 d->cite_labels_valid_ = false;
2092 // also invalidate the cache for the parent buffer
2093 Buffer const * const pbuf = d->parent();
2095 pbuf->invalidateBibinfoCache();
2099 void Buffer::invalidateBibfileCache() const
2101 d->bibfile_cache_valid_ = false;
2102 d->bibinfo_cache_valid_ = false;
2103 d->cite_labels_valid_ = false;
2104 // also invalidate the cache for the parent buffer
2105 Buffer const * const pbuf = d->parent();
2107 pbuf->invalidateBibfileCache();
2111 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
2113 // FIXME This is probably unnecessary, given where we call this.
2114 // If this is a child document, use the master's cache instead.
2115 Buffer const * const pbuf = masterBuffer();
2116 if (pbuf != this && scope != UpdateChildOnly)
2117 return pbuf->getBibfilesCache();
2119 if (!d->bibfile_cache_valid_)
2120 this->updateBibfilesCache(scope);
2122 return d->bibfiles_cache_;
2126 BiblioInfo const & Buffer::masterBibInfo() const
2128 Buffer const * const tmp = masterBuffer();
2130 return tmp->masterBibInfo();
2135 void Buffer::checkIfBibInfoCacheIsValid() const
2137 // use the master's cache
2138 Buffer const * const tmp = masterBuffer();
2140 tmp->checkIfBibInfoCacheIsValid();
2144 // compare the cached timestamps with the actual ones.
2145 FileNameList const & bibfiles_cache = getBibfilesCache();
2146 FileNameList::const_iterator ei = bibfiles_cache.begin();
2147 FileNameList::const_iterator en = bibfiles_cache.end();
2148 for (; ei != en; ++ ei) {
2149 time_t lastw = ei->lastModified();
2150 time_t prevw = d->bibfile_status_[*ei];
2151 if (lastw != prevw) {
2152 d->bibinfo_cache_valid_ = false;
2153 d->cite_labels_valid_ = false;
2154 d->bibfile_status_[*ei] = lastw;
2160 void Buffer::reloadBibInfoCache() const
2162 // use the master's cache
2163 Buffer const * const tmp = masterBuffer();
2165 tmp->reloadBibInfoCache();
2169 checkIfBibInfoCacheIsValid();
2170 if (d->bibinfo_cache_valid_)
2173 d->bibinfo_.clear();
2175 d->bibinfo_cache_valid_ = true;
2179 void Buffer::collectBibKeys() const
2181 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2182 it->collectBibKeys(it);
2186 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
2188 Buffer const * tmp = masterBuffer();
2189 BiblioInfo & masterbi = (tmp == this) ?
2190 d->bibinfo_ : tmp->d->bibinfo_;
2191 masterbi.mergeBiblioInfo(bi);
2195 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
2197 Buffer const * tmp = masterBuffer();
2198 BiblioInfo & masterbi = (tmp == this) ?
2199 d->bibinfo_ : tmp->d->bibinfo_;
2204 void Buffer::makeCitationLabels() const
2206 Buffer const * const master = masterBuffer();
2207 return d->bibinfo_.makeCitationLabels(*master);
2211 bool Buffer::citeLabelsValid() const
2213 return masterBuffer()->d->cite_labels_valid_;
2217 void Buffer::removeBiblioTempFiles() const
2219 // We remove files that contain LaTeX commands specific to the
2220 // particular bibliographic style being used, in order to avoid
2221 // LaTeX errors when we switch style.
2222 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2223 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2224 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2225 aux_file.removeFile();
2226 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2227 bbl_file.removeFile();
2228 // Also for the parent buffer
2229 Buffer const * const pbuf = parent();
2231 pbuf->removeBiblioTempFiles();
2235 bool Buffer::isDepClean(string const & name) const
2237 DepClean::const_iterator const it = d->dep_clean.find(name);
2238 if (it == d->dep_clean.end())
2244 void Buffer::markDepClean(string const & name)
2246 d->dep_clean[name] = true;
2250 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2253 // FIXME? if there is an Buffer LFUN that can be dispatched even
2254 // if internal, put a switch '(cmd.action)' here.
2260 switch (cmd.action()) {
2262 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2263 flag.setOnOff(isReadonly());
2266 // FIXME: There is need for a command-line import.
2267 //case LFUN_BUFFER_IMPORT:
2269 case LFUN_BUFFER_AUTO_SAVE:
2272 case LFUN_BUFFER_EXPORT_CUSTOM:
2273 // FIXME: Nothing to check here?
2276 case LFUN_BUFFER_EXPORT: {
2277 docstring const arg = cmd.argument();
2278 if (arg == "custom") {
2282 string format = to_utf8(arg);
2283 size_t pos = format.find(' ');
2284 if (pos != string::npos)
2285 format = format.substr(0, pos);
2286 enable = params().isExportable(format);
2288 flag.message(bformat(
2289 _("Don't know how to export to format: %1$s"), arg));
2293 case LFUN_BUFFER_CHKTEX:
2294 enable = params().isLatex() && !lyxrc.chktex_command.empty();
2297 case LFUN_BUILD_PROGRAM:
2298 enable = params().isExportable("program");
2301 case LFUN_BRANCH_ACTIVATE:
2302 case LFUN_BRANCH_DEACTIVATE:
2303 case LFUN_BRANCH_MASTER_ACTIVATE:
2304 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2305 bool const master = (cmd.action() == LFUN_BRANCH_MASTER_ACTIVATE
2306 || cmd.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2307 BranchList const & branchList = master ? masterBuffer()->params().branchlist()
2308 : params().branchlist();
2309 docstring const branchName = cmd.argument();
2310 flag.setEnabled(!branchName.empty() && branchList.find(branchName));
2314 case LFUN_BRANCH_ADD:
2315 case LFUN_BRANCHES_RENAME:
2316 case LFUN_BUFFER_PRINT:
2317 // if no Buffer is present, then of course we won't be called!
2320 case LFUN_BUFFER_LANGUAGE:
2321 enable = !isReadonly();
2327 flag.setEnabled(enable);
2332 void Buffer::dispatch(string const & command, DispatchResult & result)
2334 return dispatch(lyxaction.lookupFunc(command), result);
2338 // NOTE We can end up here even if we have no GUI, because we are called
2339 // by LyX::exec to handled command-line requests. So we may need to check
2340 // whether we have a GUI or not. The boolean use_gui holds this information.
2341 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2344 // FIXME? if there is an Buffer LFUN that can be dispatched even
2345 // if internal, put a switch '(cmd.action())' here.
2346 dr.dispatched(false);
2349 string const argument = to_utf8(func.argument());
2350 // We'll set this back to false if need be.
2351 bool dispatched = true;
2352 undo().beginUndoGroup();
2354 switch (func.action()) {
2355 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2356 if (lyxvc().inUse()) {
2357 string log = lyxvc().toggleReadOnly();
2362 setReadonly(!isReadonly());
2365 case LFUN_BUFFER_EXPORT: {
2366 ExportStatus const status = doExport(argument, false);
2367 dr.setError(status != ExportSuccess);
2368 if (status != ExportSuccess)
2369 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2374 case LFUN_BUILD_PROGRAM: {
2375 ExportStatus const status = doExport("program", true);
2376 dr.setError(status != ExportSuccess);
2377 if (status != ExportSuccess)
2378 dr.setMessage(_("Error generating literate programming code."));
2382 case LFUN_BUFFER_CHKTEX:
2386 case LFUN_BUFFER_EXPORT_CUSTOM: {
2388 string command = split(argument, format_name, ' ');
2389 Format const * format = formats.getFormat(format_name);
2391 lyxerr << "Format \"" << format_name
2392 << "\" not recognized!"
2397 // The name of the file created by the conversion process
2400 // Output to filename
2401 if (format->name() == "lyx") {
2402 string const latexname = latexName(false);
2403 filename = changeExtension(latexname,
2404 format->extension());
2405 filename = addName(temppath(), filename);
2407 if (!writeFile(FileName(filename)))
2411 doExport(format_name, true, filename);
2414 // Substitute $$FName for filename
2415 if (!contains(command, "$$FName"))
2416 command = "( " + command + " ) < $$FName";
2417 command = subst(command, "$$FName", filename);
2419 // Execute the command in the background
2421 call.startscript(Systemcall::DontWait, command, filePath());
2425 // FIXME: There is need for a command-line import.
2427 case LFUN_BUFFER_IMPORT:
2432 case LFUN_BUFFER_AUTO_SAVE:
2434 resetAutosaveTimers();
2437 case LFUN_BRANCH_ACTIVATE:
2438 case LFUN_BRANCH_DEACTIVATE:
2439 case LFUN_BRANCH_MASTER_ACTIVATE:
2440 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2441 bool const master = (func.action() == LFUN_BRANCH_MASTER_ACTIVATE
2442 || func.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2443 Buffer * buf = master ? const_cast<Buffer *>(masterBuffer())
2446 docstring const branch_name = func.argument();
2447 // the case without a branch name is handled elsewhere
2448 if (branch_name.empty()) {
2452 Branch * branch = buf->params().branchlist().find(branch_name);
2454 LYXERR0("Branch " << branch_name << " does not exist.");
2456 docstring const msg =
2457 bformat(_("Branch \"%1$s\" does not exist."), branch_name);
2461 bool const activate = (func.action() == LFUN_BRANCH_ACTIVATE
2462 || func.action() == LFUN_BRANCH_MASTER_ACTIVATE);
2463 if (branch->isSelected() != activate) {
2464 buf->undo().recordUndoFullDocument(CursorData());
2465 branch->setSelected(activate);
2467 dr.screenUpdate(Update::Force);
2468 dr.forceBufferUpdate();
2473 case LFUN_BRANCH_ADD: {
2474 docstring branch_name = func.argument();
2475 if (branch_name.empty()) {
2479 BranchList & branch_list = params().branchlist();
2480 vector<docstring> const branches =
2481 getVectorFromString(branch_name, branch_list.separator());
2483 for (vector<docstring>::const_iterator it = branches.begin();
2484 it != branches.end(); ++it) {
2486 Branch * branch = branch_list.find(branch_name);
2488 LYXERR0("Branch " << branch_name << " already exists.");
2492 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2494 undo().recordUndoFullDocument(CursorData());
2495 branch_list.add(branch_name);
2496 branch = branch_list.find(branch_name);
2497 string const x11hexname = X11hexname(branch->color());
2498 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2499 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2501 dr.screenUpdate(Update::Force);
2509 case LFUN_BRANCHES_RENAME: {
2510 if (func.argument().empty())
2513 docstring const oldname = from_utf8(func.getArg(0));
2514 docstring const newname = from_utf8(func.getArg(1));
2515 InsetIterator it = inset_iterator_begin(inset());
2516 InsetIterator const end = inset_iterator_end(inset());
2517 bool success = false;
2518 for (; it != end; ++it) {
2519 if (it->lyxCode() == BRANCH_CODE) {
2520 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2521 if (ins.branch() == oldname) {
2522 undo().recordUndo(CursorData(it));
2523 ins.rename(newname);
2528 if (it->lyxCode() == INCLUDE_CODE) {
2529 // get buffer of external file
2530 InsetInclude const & ins =
2531 static_cast<InsetInclude const &>(*it);
2532 Buffer * child = ins.getChildBuffer();
2535 child->dispatch(func, dr);
2540 dr.screenUpdate(Update::Force);
2541 dr.forceBufferUpdate();
2546 case LFUN_BUFFER_PRINT: {
2547 // we'll assume there's a problem until we succeed
2549 string target = func.getArg(0);
2550 string target_name = func.getArg(1);
2551 string command = func.getArg(2);
2554 || target_name.empty()
2555 || command.empty()) {
2556 LYXERR0("Unable to parse " << func.argument());
2557 docstring const msg =
2558 bformat(_("Unable to parse \"%1$s\""), func.argument());
2562 if (target != "printer" && target != "file") {
2563 LYXERR0("Unrecognized target \"" << target << '"');
2564 docstring const msg =
2565 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2570 if (doExport("dvi", true) != ExportSuccess) {
2571 showPrintError(absFileName());
2572 dr.setMessage(_("Error exporting to DVI."));
2576 // Push directory path.
2577 string const path = temppath();
2578 // Prevent the compiler from optimizing away p
2582 // there are three cases here:
2583 // 1. we print to a file
2584 // 2. we print directly to a printer
2585 // 3. we print using a spool command (print to file first)
2588 string const dviname = changeExtension(latexName(true), "dvi");
2590 if (target == "printer") {
2591 if (!lyxrc.print_spool_command.empty()) {
2592 // case 3: print using a spool
2593 string const psname = changeExtension(dviname,".ps");
2594 command += ' ' + lyxrc.print_to_file
2597 + quoteName(dviname);
2599 string command2 = lyxrc.print_spool_command + ' ';
2600 if (target_name != "default") {
2601 command2 += lyxrc.print_spool_printerprefix
2605 command2 += quoteName(psname);
2607 // If successful, then spool command
2608 res = one.startscript(Systemcall::Wait, command,
2612 // If there's no GUI, we have to wait on this command. Otherwise,
2613 // LyX deletes the temporary directory, and with it the spooled
2614 // file, before it can be printed!!
2615 Systemcall::Starttype stype = use_gui ?
2616 Systemcall::DontWait : Systemcall::Wait;
2617 res = one.startscript(stype, command2,
2621 // case 2: print directly to a printer
2622 if (target_name != "default")
2623 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2625 Systemcall::Starttype stype = use_gui ?
2626 Systemcall::DontWait : Systemcall::Wait;
2627 res = one.startscript(stype, command +
2628 quoteName(dviname), filePath());
2632 // case 1: print to a file
2633 FileName const filename(makeAbsPath(target_name, filePath()));
2634 FileName const dvifile(makeAbsPath(dviname, path));
2635 if (filename.exists()) {
2636 docstring text = bformat(
2637 _("The file %1$s already exists.\n\n"
2638 "Do you want to overwrite that file?"),
2639 makeDisplayPath(filename.absFileName()));
2640 if (Alert::prompt(_("Overwrite file?"),
2641 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2644 command += ' ' + lyxrc.print_to_file
2645 + quoteName(filename.toFilesystemEncoding())
2647 + quoteName(dvifile.toFilesystemEncoding());
2649 Systemcall::Starttype stype = use_gui ?
2650 Systemcall::DontWait : Systemcall::Wait;
2651 res = one.startscript(stype, command, filePath());
2657 dr.setMessage(_("Error running external commands."));
2658 showPrintError(absFileName());
2667 dr.dispatched(dispatched);
2668 undo().endUndoGroup();
2672 void Buffer::changeLanguage(Language const * from, Language const * to)
2674 LASSERT(from, return);
2675 LASSERT(to, return);
2677 for_each(par_iterator_begin(),
2679 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2683 bool Buffer::isMultiLingual() const
2685 ParConstIterator end = par_iterator_end();
2686 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2687 if (it->isMultiLingual(params()))
2694 std::set<Language const *> Buffer::getLanguages() const
2696 std::set<Language const *> languages;
2697 getLanguages(languages);
2702 void Buffer::getLanguages(std::set<Language const *> & languages) const
2704 ParConstIterator end = par_iterator_end();
2705 // add the buffer language, even if it's not actively used
2706 languages.insert(language());
2707 // iterate over the paragraphs
2708 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2709 it->getLanguages(languages);
2711 ListOfBuffers clist = getDescendents();
2712 ListOfBuffers::const_iterator cit = clist.begin();
2713 ListOfBuffers::const_iterator const cen = clist.end();
2714 for (; cit != cen; ++cit)
2715 (*cit)->getLanguages(languages);
2719 DocIterator Buffer::getParFromID(int const id) const
2721 Buffer * buf = const_cast<Buffer *>(this);
2723 // John says this is called with id == -1 from undo
2724 lyxerr << "getParFromID(), id: " << id << endl;
2725 return doc_iterator_end(buf);
2728 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2729 if (it.paragraph().id() == id)
2732 return doc_iterator_end(buf);
2736 bool Buffer::hasParWithID(int const id) const
2738 return !getParFromID(id).atEnd();
2742 ParIterator Buffer::par_iterator_begin()
2744 return ParIterator(doc_iterator_begin(this));
2748 ParIterator Buffer::par_iterator_end()
2750 return ParIterator(doc_iterator_end(this));
2754 ParConstIterator Buffer::par_iterator_begin() const
2756 return ParConstIterator(doc_iterator_begin(this));
2760 ParConstIterator Buffer::par_iterator_end() const
2762 return ParConstIterator(doc_iterator_end(this));
2766 Language const * Buffer::language() const
2768 return params().language;
2772 docstring const Buffer::B_(string const & l10n) const
2774 return params().B_(l10n);
2778 bool Buffer::isClean() const
2780 return d->lyx_clean;
2784 bool Buffer::isExternallyModified(CheckMethod method) const
2786 LASSERT(d->filename.exists(), return false);
2787 // if method == timestamp, check timestamp before checksum
2788 return (method == checksum_method
2789 || d->timestamp_ != d->filename.lastModified())
2790 && d->checksum_ != d->filename.checksum();
2794 void Buffer::saveCheckSum() const
2796 FileName const & file = d->filename;
2799 if (file.exists()) {
2800 d->timestamp_ = file.lastModified();
2801 d->checksum_ = file.checksum();
2803 // in the case of save to a new file.
2810 void Buffer::markClean() const
2812 if (!d->lyx_clean) {
2813 d->lyx_clean = true;
2816 // if the .lyx file has been saved, we don't need an
2818 d->bak_clean = true;
2819 d->undo_.markDirty();
2823 void Buffer::setUnnamed(bool flag)
2829 bool Buffer::isUnnamed() const
2836 /// Don't check unnamed, here: isInternal() is used in
2837 /// newBuffer(), where the unnamed flag has not been set by anyone
2838 /// yet. Also, for an internal buffer, there should be no need for
2839 /// retrieving fileName() nor for checking if it is unnamed or not.
2840 bool Buffer::isInternal() const
2842 return d->internal_buffer;
2846 void Buffer::setInternal(bool flag)
2848 d->internal_buffer = flag;
2852 void Buffer::markDirty()
2855 d->lyx_clean = false;
2858 d->bak_clean = false;
2860 DepClean::iterator it = d->dep_clean.begin();
2861 DepClean::const_iterator const end = d->dep_clean.end();
2863 for (; it != end; ++it)
2868 FileName Buffer::fileName() const
2874 string Buffer::absFileName() const
2876 return d->filename.absFileName();
2880 string Buffer::filePath() const
2882 string const abs = d->filename.onlyPath().absFileName();
2885 int last = abs.length() - 1;
2887 return abs[last] == '/' ? abs : abs + '/';
2891 bool Buffer::isReadonly() const
2893 return d->read_only;
2897 void Buffer::setParent(Buffer const * buffer)
2899 // Avoids recursive include.
2900 d->setParent(buffer == this ? 0 : buffer);
2905 Buffer const * Buffer::parent() const
2911 ListOfBuffers Buffer::allRelatives() const
2913 ListOfBuffers lb = masterBuffer()->getDescendents();
2914 lb.push_front(const_cast<Buffer *>(masterBuffer()));
2919 Buffer const * Buffer::masterBuffer() const
2921 // FIXME Should be make sure we are not in some kind
2922 // of recursive include? A -> B -> A will crash this.
2923 Buffer const * const pbuf = d->parent();
2927 return pbuf->masterBuffer();
2931 bool Buffer::isChild(Buffer * child) const
2933 return d->children_positions.find(child) != d->children_positions.end();
2937 DocIterator Buffer::firstChildPosition(Buffer const * child)
2939 Impl::BufferPositionMap::iterator it;
2940 it = d->children_positions.find(child);
2941 if (it == d->children_positions.end())
2942 return DocIterator(this);
2947 bool Buffer::hasChildren() const
2949 return !d->children_positions.empty();
2953 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
2955 // loop over children
2956 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2957 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2958 for (; it != end; ++it) {
2959 Buffer * child = const_cast<Buffer *>(it->first);
2961 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
2962 if (bit != clist.end())
2964 clist.push_back(child);
2966 // there might be grandchildren
2967 child->collectChildren(clist, true);
2972 ListOfBuffers Buffer::getChildren() const
2975 collectChildren(v, false);
2976 // Make sure we have not included ourselves.
2977 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
2978 if (bit != v.end()) {
2979 LYXERR0("Recursive include detected in `" << fileName() << "'.");
2986 ListOfBuffers Buffer::getDescendents() const
2989 collectChildren(v, true);
2990 // Make sure we have not included ourselves.
2991 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
2992 if (bit != v.end()) {
2993 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3000 template<typename M>
3001 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
3006 typename M::const_iterator it = m.lower_bound(x);
3007 if (it == m.begin())
3015 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
3016 DocIterator const & pos) const
3018 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
3020 // if paragraphs have no macro context set, pos will be empty
3024 // we haven't found anything yet
3025 DocIterator bestPos = owner_->par_iterator_begin();
3026 MacroData const * bestData = 0;
3028 // find macro definitions for name
3029 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
3030 if (nameIt != macros.end()) {
3031 // find last definition in front of pos or at pos itself
3032 PositionScopeMacroMap::const_iterator it
3033 = greatest_below(nameIt->second, pos);
3034 if (it != nameIt->second.end()) {
3036 // scope ends behind pos?
3037 if (pos < it->second.first) {
3038 // Looks good, remember this. If there
3039 // is no external macro behind this,
3040 // we found the right one already.
3041 bestPos = it->first;
3042 bestData = &it->second.second;
3046 // try previous macro if there is one
3047 if (it == nameIt->second.begin())
3054 // find macros in included files
3055 PositionScopeBufferMap::const_iterator it
3056 = greatest_below(position_to_children, pos);
3057 if (it == position_to_children.end())
3058 // no children before
3062 // do we know something better (i.e. later) already?
3063 if (it->first < bestPos )
3066 // scope ends behind pos?
3067 if (pos < it->second.first
3068 && (cloned_buffer_ ||
3069 theBufferList().isLoaded(it->second.second))) {
3070 // look for macro in external file
3072 MacroData const * data
3073 = it->second.second->getMacro(name, false);
3076 bestPos = it->first;
3082 // try previous file if there is one
3083 if (it == position_to_children.begin())
3088 // return the best macro we have found
3093 MacroData const * Buffer::getMacro(docstring const & name,
3094 DocIterator const & pos, bool global) const
3099 // query buffer macros
3100 MacroData const * data = d->getBufferMacro(name, pos);
3104 // If there is a master buffer, query that
3105 Buffer const * const pbuf = d->parent();
3107 d->macro_lock = true;
3108 MacroData const * macro = pbuf->getMacro(
3109 name, *this, false);
3110 d->macro_lock = false;
3116 data = MacroTable::globalMacros().get(name);
3125 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3127 // set scope end behind the last paragraph
3128 DocIterator scope = par_iterator_begin();
3129 scope.pit() = scope.lastpit() + 1;
3131 return getMacro(name, scope, global);
3135 MacroData const * Buffer::getMacro(docstring const & name,
3136 Buffer const & child, bool global) const
3138 // look where the child buffer is included first
3139 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3140 if (it == d->children_positions.end())
3143 // check for macros at the inclusion position
3144 return getMacro(name, it->second, global);
3148 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3150 pit_type const lastpit = it.lastpit();
3152 // look for macros in each paragraph
3153 while (it.pit() <= lastpit) {
3154 Paragraph & par = it.paragraph();
3156 // iterate over the insets of the current paragraph
3157 InsetList const & insets = par.insetList();
3158 InsetList::const_iterator iit = insets.begin();
3159 InsetList::const_iterator end = insets.end();
3160 for (; iit != end; ++iit) {
3161 it.pos() = iit->pos;
3163 // is it a nested text inset?
3164 if (iit->inset->asInsetText()) {
3165 // Inset needs its own scope?
3166 InsetText const * itext = iit->inset->asInsetText();
3167 bool newScope = itext->isMacroScope();
3169 // scope which ends just behind the inset
3170 DocIterator insetScope = it;
3173 // collect macros in inset
3174 it.push_back(CursorSlice(*iit->inset));
3175 updateMacros(it, newScope ? insetScope : scope);
3180 if (iit->inset->asInsetTabular()) {
3181 CursorSlice slice(*iit->inset);
3182 size_t const numcells = slice.nargs();
3183 for (; slice.idx() < numcells; slice.forwardIdx()) {
3184 it.push_back(slice);
3185 updateMacros(it, scope);
3191 // is it an external file?
3192 if (iit->inset->lyxCode() == INCLUDE_CODE) {
3193 // get buffer of external file
3194 InsetInclude const & inset =
3195 static_cast<InsetInclude const &>(*iit->inset);
3197 Buffer * child = inset.getChildBuffer();
3202 // register its position, but only when it is
3203 // included first in the buffer
3204 if (children_positions.find(child) ==
3205 children_positions.end())
3206 children_positions[child] = it;
3208 // register child with its scope
3209 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3213 InsetMath * im = iit->inset->asInsetMath();
3214 if (doing_export && im) {
3215 InsetMathHull * hull = im->asHullInset();
3217 hull->recordLocation(it);
3220 if (iit->inset->lyxCode() != MATHMACRO_CODE)
3224 MathMacroTemplate & macroTemplate =
3225 *iit->inset->asInsetMath()->asMacroTemplate();
3226 MacroContext mc(owner_, it);
3227 macroTemplate.updateToContext(mc);
3230 bool valid = macroTemplate.validMacro();
3231 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3232 // then the BufferView's cursor will be invalid in
3233 // some cases which leads to crashes.
3238 // FIXME (Abdel), I don't understandt why we pass 'it' here
3239 // instead of 'macroTemplate' defined above... is this correct?
3240 macros[macroTemplate.name()][it] =
3241 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3251 void Buffer::updateMacros() const
3256 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3258 // start with empty table
3260 d->children_positions.clear();
3261 d->position_to_children.clear();
3263 // Iterate over buffer, starting with first paragraph
3264 // The scope must be bigger than any lookup DocIterator
3265 // later. For the global lookup, lastpit+1 is used, hence
3266 // we use lastpit+2 here.
3267 DocIterator it = par_iterator_begin();
3268 DocIterator outerScope = it;
3269 outerScope.pit() = outerScope.lastpit() + 2;
3270 d->updateMacros(it, outerScope);
3274 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3276 InsetIterator it = inset_iterator_begin(inset());
3277 InsetIterator const end = inset_iterator_end(inset());
3278 for (; it != end; ++it) {
3279 if (it->lyxCode() == BRANCH_CODE) {
3280 InsetBranch & br = static_cast<InsetBranch &>(*it);
3281 docstring const name = br.branch();
3282 if (!from_master && !params().branchlist().find(name))
3283 result.push_back(name);
3284 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3285 result.push_back(name);
3288 if (it->lyxCode() == INCLUDE_CODE) {
3289 // get buffer of external file
3290 InsetInclude const & ins =
3291 static_cast<InsetInclude const &>(*it);
3292 Buffer * child = ins.getChildBuffer();
3295 child->getUsedBranches(result, true);
3298 // remove duplicates
3303 void Buffer::updateMacroInstances(UpdateType utype) const
3305 LYXERR(Debug::MACROS, "updateMacroInstances for "
3306 << d->filename.onlyFileName());
3307 DocIterator it = doc_iterator_begin(this);
3309 DocIterator const end = doc_iterator_end(this);
3310 for (; it != end; it.forwardInset()) {
3311 // look for MathData cells in InsetMathNest insets
3312 InsetMath * minset = it.nextInset()->asInsetMath();
3316 // update macro in all cells of the InsetMathNest
3317 DocIterator::idx_type n = minset->nargs();
3318 MacroContext mc = MacroContext(this, it);
3319 for (DocIterator::idx_type i = 0; i < n; ++i) {
3320 MathData & data = minset->cell(i);
3321 data.updateMacros(0, mc, utype);
3327 void Buffer::listMacroNames(MacroNameSet & macros) const
3332 d->macro_lock = true;
3334 // loop over macro names
3335 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3336 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3337 for (; nameIt != nameEnd; ++nameIt)
3338 macros.insert(nameIt->first);
3340 // loop over children
3341 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3342 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3343 for (; it != end; ++it)
3344 it->first->listMacroNames(macros);
3347 Buffer const * const pbuf = d->parent();
3349 pbuf->listMacroNames(macros);
3351 d->macro_lock = false;
3355 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3357 Buffer const * const pbuf = d->parent();
3362 pbuf->listMacroNames(names);
3365 MacroNameSet::iterator it = names.begin();
3366 MacroNameSet::iterator end = names.end();
3367 for (; it != end; ++it) {
3369 MacroData const * data =
3370 pbuf->getMacro(*it, *this, false);
3372 macros.insert(data);
3374 // we cannot access the original MathMacroTemplate anymore
3375 // here to calls validate method. So we do its work here manually.
3376 // FIXME: somehow make the template accessible here.
3377 if (data->optionals() > 0)
3378 features.require("xargs");
3384 Buffer::References & Buffer::getReferenceCache(docstring const & label)
3387 return const_cast<Buffer *>(masterBuffer())->getReferenceCache(label);
3389 RefCache::iterator it = d->ref_cache_.find(label);
3390 if (it != d->ref_cache_.end())
3391 return it->second.second;
3393 static InsetLabel const * dummy_il = 0;
3394 static References const dummy_refs;
3395 it = d->ref_cache_.insert(
3396 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3397 return it->second.second;
3401 Buffer::References const & Buffer::references(docstring const & label) const
3403 return const_cast<Buffer *>(this)->getReferenceCache(label);
3407 void Buffer::addReference(docstring const & label, Inset * inset, ParIterator it)
3409 References & refs = getReferenceCache(label);
3410 refs.push_back(make_pair(inset, it));
3414 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3416 masterBuffer()->d->ref_cache_[label].first = il;
3420 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3422 return masterBuffer()->d->ref_cache_[label].first;
3426 void Buffer::clearReferenceCache() const
3429 d->ref_cache_.clear();
3433 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to)
3435 //FIXME: This does not work for child documents yet.
3436 reloadBibInfoCache();
3438 // Check if the label 'from' appears more than once
3439 BiblioInfo const & keys = masterBibInfo();
3440 BiblioInfo::const_iterator bit = keys.begin();
3441 BiblioInfo::const_iterator bend = keys.end();
3442 vector<docstring> labels;
3444 for (; bit != bend; ++bit)
3446 labels.push_back(bit->first);
3448 if (count(labels.begin(), labels.end(), from) > 1)
3451 string const paramName = "key";
3452 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3453 if (it->lyxCode() != CITE_CODE)
3455 InsetCommand * inset = it->asInsetCommand();
3456 docstring const oldValue = inset->getParam(paramName);
3457 if (oldValue == from)
3458 inset->setParam(paramName, to);
3463 void Buffer::getSourceCode(odocstream & os, string const format,
3464 pit_type par_begin, pit_type par_end,
3465 OutputWhat output, bool master) const
3467 OutputParams runparams(¶ms().encoding());
3468 runparams.nice = true;
3469 runparams.flavor = params().getOutputFlavor(format);
3470 runparams.linelen = lyxrc.plaintext_linelen;
3471 // No side effect of file copying and image conversion
3472 runparams.dryrun = true;
3474 if (output == CurrentParagraph) {
3475 runparams.par_begin = par_begin;
3476 runparams.par_end = par_end;
3477 if (par_begin + 1 == par_end) {
3479 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3483 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3484 convert<docstring>(par_begin),
3485 convert<docstring>(par_end - 1))
3488 // output paragraphs
3489 if (runparams.flavor == OutputParams::LYX) {
3490 Paragraph const & par = text().paragraphs()[par_begin];
3492 depth_type dt = par.getDepth();
3493 par.write(ods, params(), dt);
3494 os << from_utf8(ods.str());
3495 } else if (runparams.flavor == OutputParams::HTML) {
3497 setMathFlavor(runparams);
3498 xhtmlParagraphs(text(), *this, xs, runparams);
3499 } else if (runparams.flavor == OutputParams::TEXT) {
3501 // FIXME Handles only one paragraph, unlike the others.
3502 // Probably should have some routine with a signature like them.
3503 writePlaintextParagraph(*this,
3504 text().paragraphs()[par_begin], os, runparams, dummy);
3505 } else if (params().isDocBook()) {
3506 docbookParagraphs(text(), *this, os, runparams);
3508 // If we are previewing a paragraph, even if this is the
3509 // child of some other buffer, let's cut the link here,
3510 // so that no concurring settings from the master
3511 // (e.g. branch state) interfere (see #8101).
3513 d->ignore_parent = true;
3514 // We need to validate the Buffer params' features here
3515 // in order to know if we should output polyglossia
3516 // macros (instead of babel macros)
3517 LaTeXFeatures features(*this, params(), runparams);
3518 params().validate(features);
3519 runparams.use_polyglossia = features.usePolyglossia();
3524 // latex or literate
3525 otexstream ots(os, texrow);
3528 latexParagraphs(*this, text(), ots, runparams);
3530 // Restore the parenthood
3532 d->ignore_parent = false;
3536 if (output == FullSource)
3537 os << _("Preview source code");
3538 else if (output == OnlyPreamble)
3539 os << _("Preview preamble");
3540 else if (output == OnlyBody)
3541 os << _("Preview body");
3543 if (runparams.flavor == OutputParams::LYX) {
3545 if (output == FullSource)
3547 else if (output == OnlyPreamble)
3548 params().writeFile(ods);
3549 else if (output == OnlyBody)
3551 os << from_utf8(ods.str());
3552 } else if (runparams.flavor == OutputParams::HTML) {
3553 writeLyXHTMLSource(os, runparams, output);
3554 } else if (runparams.flavor == OutputParams::TEXT) {
3555 if (output == OnlyPreamble) {
3556 os << "% "<< _("Plain text does not have a preamble.");
3558 writePlaintextFile(*this, os, runparams);
3559 } else if (params().isDocBook()) {
3560 writeDocBookSource(os, absFileName(), runparams, output);
3562 // latex or literate
3564 d->texrow.newline();
3565 d->texrow.newline();
3566 otexstream ots(os, d->texrow);
3568 runparams.is_child = true;
3569 writeLaTeXSource(ots, string(), runparams, output);
3575 ErrorList & Buffer::errorList(string const & type) const
3577 return d->errorLists[type];
3581 void Buffer::updateTocItem(std::string const & type,
3582 DocIterator const & dit) const
3585 d->gui_->updateTocItem(type, dit);
3589 void Buffer::structureChanged() const
3592 d->gui_->structureChanged();
3596 void Buffer::errors(string const & err, bool from_master) const
3599 d->gui_->errors(err, from_master);
3603 void Buffer::message(docstring const & msg) const
3606 d->gui_->message(msg);
3610 void Buffer::setBusy(bool on) const
3613 d->gui_->setBusy(on);
3617 void Buffer::updateTitles() const
3620 d->wa_->updateTitles();
3624 void Buffer::resetAutosaveTimers() const
3627 d->gui_->resetAutosaveTimers();
3631 bool Buffer::hasGuiDelegate() const
3637 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3646 class AutoSaveBuffer : public ForkedProcess {
3649 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3650 : buffer_(buffer), fname_(fname) {}
3652 virtual shared_ptr<ForkedProcess> clone() const
3654 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3659 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3660 from_utf8(fname_.absFileName())));
3661 return run(DontWait);
3665 virtual int generateChild();
3667 Buffer const & buffer_;
3672 int AutoSaveBuffer::generateChild()
3674 #if defined(__APPLE__)
3675 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3676 * We should use something else like threads.
3678 * Since I do not know how to determine at run time what is the OS X
3679 * version, I just disable forking altogether for now (JMarc)
3681 pid_t const pid = -1;
3683 // tmp_ret will be located (usually) in /tmp
3684 // will that be a problem?
3685 // Note that this calls ForkedCalls::fork(), so it's
3686 // ok cross-platform.
3687 pid_t const pid = fork();
3688 // If you want to debug the autosave
3689 // you should set pid to -1, and comment out the fork.
3690 if (pid != 0 && pid != -1)
3694 // pid = -1 signifies that lyx was unable
3695 // to fork. But we will do the save
3697 bool failed = false;
3698 FileName const tmp_ret = FileName::tempName("lyxauto");
3699 if (!tmp_ret.empty()) {
3700 buffer_.writeFile(tmp_ret);
3701 // assume successful write of tmp_ret
3702 if (!tmp_ret.moveTo(fname_))
3708 // failed to write/rename tmp_ret so try writing direct
3709 if (!buffer_.writeFile(fname_)) {
3710 // It is dangerous to do this in the child,
3711 // but safe in the parent, so...
3712 if (pid == -1) // emit message signal.
3713 buffer_.message(_("Autosave failed!"));
3717 if (pid == 0) // we are the child so...
3726 FileName Buffer::getEmergencyFileName() const
3728 return FileName(d->filename.absFileName() + ".emergency");
3732 FileName Buffer::getAutosaveFileName() const
3734 // if the document is unnamed try to save in the backup dir, else
3735 // in the default document path, and as a last try in the filePath,
3736 // which will most often be the temporary directory
3739 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3740 : lyxrc.backupdir_path;
3741 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3744 string const fname = "#" + d->filename.onlyFileName() + "#";
3746 return makeAbsPath(fname, fpath);
3750 void Buffer::removeAutosaveFile() const
3752 FileName const f = getAutosaveFileName();
3758 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3760 FileName const newauto = getAutosaveFileName();
3762 if (newauto != oldauto && oldauto.exists())
3763 if (!oldauto.moveTo(newauto))
3764 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3768 bool Buffer::autoSave() const
3770 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
3771 if (buf->d->bak_clean || isReadonly())
3774 message(_("Autosaving current document..."));
3775 buf->d->bak_clean = true;
3777 FileName const fname = getAutosaveFileName();
3778 LASSERT(d->cloned_buffer_, return false);
3780 // If this buffer is cloned, we assume that
3781 // we are running in a separate thread already.
3782 FileName const tmp_ret = FileName::tempName("lyxauto");
3783 if (!tmp_ret.empty()) {
3785 // assume successful write of tmp_ret
3786 if (tmp_ret.moveTo(fname))
3789 // failed to write/rename tmp_ret so try writing direct
3790 return writeFile(fname);
3794 void Buffer::setExportStatus(bool e) const
3796 d->doing_export = e;
3797 ListOfBuffers clist = getDescendents();
3798 ListOfBuffers::const_iterator cit = clist.begin();
3799 ListOfBuffers::const_iterator const cen = clist.end();
3800 for (; cit != cen; ++cit)
3801 (*cit)->d->doing_export = e;
3805 bool Buffer::isExporting() const
3807 return d->doing_export;
3811 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
3815 return doExport(target, put_in_tempdir, result_file);
3818 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3819 string & result_file) const
3821 bool const update_unincluded =
3822 params().maintain_unincluded_children
3823 && !params().getIncludedChildren().empty();
3825 // (1) export with all included children (omit \includeonly)
3826 if (update_unincluded) {
3827 ExportStatus const status =
3828 doExport(target, put_in_tempdir, true, result_file);
3829 if (status != ExportSuccess)
3832 // (2) export with included children only
3833 return doExport(target, put_in_tempdir, false, result_file);
3837 void Buffer::setMathFlavor(OutputParams & op) const
3839 switch (params().html_math_output) {
3840 case BufferParams::MathML:
3841 op.math_flavor = OutputParams::MathAsMathML;
3843 case BufferParams::HTML:
3844 op.math_flavor = OutputParams::MathAsHTML;
3846 case BufferParams::Images:
3847 op.math_flavor = OutputParams::MathAsImages;
3849 case BufferParams::LaTeX:
3850 op.math_flavor = OutputParams::MathAsLaTeX;
3856 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3857 bool includeall, string & result_file) const
3859 LYXERR(Debug::FILES, "target=" << target);
3860 OutputParams runparams(¶ms().encoding());
3861 string format = target;
3862 string dest_filename;
3863 size_t pos = target.find(' ');
3864 if (pos != string::npos) {
3865 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
3866 format = target.substr(0, pos);
3867 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
3868 FileName(dest_filename).onlyPath().createPath();
3869 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
3871 MarkAsExporting exporting(this);
3872 string backend_format;
3873 runparams.flavor = OutputParams::LATEX;
3874 runparams.linelen = lyxrc.plaintext_linelen;
3875 runparams.includeall = includeall;
3876 vector<string> backs = params().backends();
3877 Converters converters = theConverters();
3878 bool need_nice_file = false;
3879 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3880 // Get shortest path to format
3881 converters.buildGraph();
3882 Graph::EdgePath path;
3883 for (vector<string>::const_iterator it = backs.begin();
3884 it != backs.end(); ++it) {
3885 Graph::EdgePath p = converters.getPath(*it, format);
3886 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3887 backend_format = *it;
3892 if (!put_in_tempdir) {
3893 // Only show this alert if this is an export to a non-temporary
3894 // file (not for previewing).
3895 Alert::error(_("Couldn't export file"), bformat(
3896 _("No information for exporting the format %1$s."),
3897 formats.prettyName(format)));
3899 return ExportNoPathToFormat;
3901 runparams.flavor = converters.getFlavor(path, this);
3902 Graph::EdgePath::const_iterator it = path.begin();
3903 Graph::EdgePath::const_iterator en = path.end();
3904 for (; it != en; ++it)
3905 if (theConverters().get(*it).nice) {
3906 need_nice_file = true;
3911 backend_format = format;
3912 LYXERR(Debug::FILES, "backend_format=" << backend_format);
3913 // FIXME: Don't hardcode format names here, but use a flag
3914 if (backend_format == "pdflatex")
3915 runparams.flavor = OutputParams::PDFLATEX;
3916 else if (backend_format == "luatex")
3917 runparams.flavor = OutputParams::LUATEX;
3918 else if (backend_format == "dviluatex")
3919 runparams.flavor = OutputParams::DVILUATEX;
3920 else if (backend_format == "xetex")
3921 runparams.flavor = OutputParams::XETEX;
3924 string filename = latexName(false);
3925 filename = addName(temppath(), filename);
3926 filename = changeExtension(filename,
3927 formats.extension(backend_format));
3928 LYXERR(Debug::FILES, "filename=" << filename);
3930 // Plain text backend
3931 if (backend_format == "text") {
3932 runparams.flavor = OutputParams::TEXT;
3933 writePlaintextFile(*this, FileName(filename), runparams);
3936 else if (backend_format == "xhtml") {
3937 runparams.flavor = OutputParams::HTML;
3938 setMathFlavor(runparams);
3939 makeLyXHTMLFile(FileName(filename), runparams);
3940 } else if (backend_format == "lyx")
3941 writeFile(FileName(filename));
3943 else if (params().isDocBook()) {
3944 runparams.nice = !put_in_tempdir;
3945 makeDocBookFile(FileName(filename), runparams);
3948 else if (backend_format == format || need_nice_file) {
3949 runparams.nice = true;
3950 bool const success = makeLaTeXFile(FileName(filename), string(), runparams);
3951 if (d->cloned_buffer_)
3952 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
3955 } else if (!lyxrc.tex_allows_spaces
3956 && contains(filePath(), ' ')) {
3957 Alert::error(_("File name error"),
3958 _("The directory path to the document cannot contain spaces."));
3959 return ExportTexPathHasSpaces;
3961 runparams.nice = false;
3962 bool const success = makeLaTeXFile(
3963 FileName(filename), filePath(), runparams);
3964 if (d->cloned_buffer_)
3965 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
3970 string const error_type = (format == "program")
3971 ? "Build" : params().bufferFormat();
3972 ErrorList & error_list = d->errorLists[error_type];
3973 string const ext = formats.extension(format);
3974 FileName const tmp_result_file(changeExtension(filename, ext));
3975 bool const success = converters.convert(this, FileName(filename),
3976 tmp_result_file, FileName(absFileName()), backend_format, format,
3979 // Emit the signal to show the error list or copy it back to the
3980 // cloned Buffer so that it can be emitted afterwards.
3981 if (format != backend_format) {
3982 if (runparams.silent)
3984 else if (d->cloned_buffer_)
3985 d->cloned_buffer_->d->errorLists[error_type] =
3986 d->errorLists[error_type];
3989 // also to the children, in case of master-buffer-view
3990 ListOfBuffers clist = getDescendents();
3991 ListOfBuffers::const_iterator cit = clist.begin();
3992 ListOfBuffers::const_iterator const cen = clist.end();
3993 for (; cit != cen; ++cit) {
3994 if (runparams.silent)
3995 (*cit)->d->errorLists[error_type].clear();
3996 else if (d->cloned_buffer_) {
3997 // Enable reverse search by copying back the
3998 // texrow object to the cloned buffer.
3999 // FIXME: this is not thread safe.
4000 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
4001 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
4002 (*cit)->d->errorLists[error_type];
4004 (*cit)->errors(error_type, true);
4008 if (d->cloned_buffer_) {
4009 // Enable reverse dvi or pdf to work by copying back the texrow
4010 // object to the cloned buffer.
4011 // FIXME: There is a possibility of concurrent access to texrow
4012 // here from the main GUI thread that should be securized.
4013 d->cloned_buffer_->d->texrow = d->texrow;
4014 string const error_type = params().bufferFormat();
4015 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
4019 return ExportConverterError;
4021 if (put_in_tempdir) {
4022 result_file = tmp_result_file.absFileName();
4023 return ExportSuccess;
4026 if (dest_filename.empty())
4027 result_file = changeExtension(d->exportFileName().absFileName(), ext);
4029 result_file = dest_filename;
4030 // We need to copy referenced files (e. g. included graphics
4031 // if format == "dvi") to the result dir.
4032 vector<ExportedFile> const files =
4033 runparams.exportdata->externalFiles(format);
4034 string const dest = runparams.export_folder.empty() ?
4035 onlyPath(result_file) : runparams.export_folder;
4036 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
4037 : force_overwrite == ALL_FILES;
4038 CopyStatus status = use_force ? FORCE : SUCCESS;
4040 vector<ExportedFile>::const_iterator it = files.begin();
4041 vector<ExportedFile>::const_iterator const en = files.end();
4042 for (; it != en && status != CANCEL; ++it) {
4043 string const fmt = formats.getFormatFromFile(it->sourceName);
4044 string fixedName = it->exportName;
4045 if (!runparams.export_folder.empty()) {
4046 // Relative pathnames starting with ../ will be sanitized
4047 // if exporting to a different folder
4048 while (fixedName.substr(0, 3) == "../")
4049 fixedName = fixedName.substr(3, fixedName.length() - 3);
4051 FileName fixedFileName = makeAbsPath(fixedName, dest);
4052 fixedFileName.onlyPath().createPath();
4053 status = copyFile(fmt, it->sourceName,
4055 it->exportName, status == FORCE,
4056 runparams.export_folder.empty());
4059 if (status == CANCEL) {
4060 message(_("Document export cancelled."));
4061 return ExportCancel;
4064 if (tmp_result_file.exists()) {
4065 // Finally copy the main file
4066 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
4067 : force_overwrite != NO_FILES;
4068 if (status == SUCCESS && use_force)
4070 status = copyFile(format, tmp_result_file,
4071 FileName(result_file), result_file,
4073 if (status == CANCEL) {
4074 message(_("Document export cancelled."));
4075 return ExportCancel;
4077 message(bformat(_("Document exported as %1$s "
4079 formats.prettyName(format),
4080 makeDisplayPath(result_file)));
4083 // This must be a dummy converter like fax (bug 1888)
4084 message(bformat(_("Document exported as %1$s"),
4085 formats.prettyName(format)));
4088 return ExportSuccess;
4092 Buffer::ExportStatus Buffer::preview(string const & format) const
4094 bool const update_unincluded =
4095 params().maintain_unincluded_children
4096 && !params().getIncludedChildren().empty();
4097 return preview(format, update_unincluded);
4100 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4102 MarkAsExporting exporting(this);
4104 // (1) export with all included children (omit \includeonly)
4106 ExportStatus const status = doExport(format, true, true, result_file);
4107 if (status != ExportSuccess)
4110 // (2) export with included children only
4111 ExportStatus const status = doExport(format, true, false, result_file);
4112 if (status != ExportSuccess)
4114 if (!formats.view(*this, FileName(result_file), format))
4115 return PreviewError;
4116 return PreviewSuccess;
4120 Buffer::ReadStatus Buffer::extractFromVC()
4122 bool const found = LyXVC::file_not_found_hook(d->filename);
4124 return ReadFileNotFound;
4125 if (!d->filename.isReadableFile())
4131 Buffer::ReadStatus Buffer::loadEmergency()
4133 FileName const emergencyFile = getEmergencyFileName();
4134 if (!emergencyFile.exists()
4135 || emergencyFile.lastModified() <= d->filename.lastModified())
4136 return ReadFileNotFound;
4138 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4139 docstring const text = bformat(_("An emergency save of the document "
4140 "%1$s exists.\n\nRecover emergency save?"), file);
4142 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4143 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4149 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4150 bool const success = (ret_llf == ReadSuccess);
4153 Alert::warning(_("File is read-only"),
4154 bformat(_("An emergency file is successfully loaded, "
4155 "but the original file %1$s is marked read-only. "
4156 "Please make sure to save the document as a different "
4157 "file."), from_utf8(d->filename.absFileName())));
4160 lyxvc().file_found_hook(d->filename);
4161 str = _("Document was successfully recovered.");
4163 str = _("Document was NOT successfully recovered.");
4164 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4165 makeDisplayPath(emergencyFile.absFileName()));
4167 int const del_emerg =
4168 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4169 _("&Remove"), _("&Keep"));
4170 if (del_emerg == 0) {
4171 emergencyFile.removeFile();
4173 Alert::warning(_("Emergency file deleted"),
4174 _("Do not forget to save your file now!"), true);
4176 return success ? ReadSuccess : ReadEmergencyFailure;
4179 int const del_emerg =
4180 Alert::prompt(_("Delete emergency file?"),
4181 _("Remove emergency file now?"), 1, 1,
4182 _("&Remove"), _("&Keep"));
4184 emergencyFile.removeFile();
4185 return ReadOriginal;
4195 Buffer::ReadStatus Buffer::loadAutosave()
4197 // Now check if autosave file is newer.
4198 FileName const autosaveFile = getAutosaveFileName();
4199 if (!autosaveFile.exists()
4200 || autosaveFile.lastModified() <= d->filename.lastModified())
4201 return ReadFileNotFound;
4203 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4204 docstring const text = bformat(_("The backup of the document %1$s "
4205 "is newer.\n\nLoad the backup instead?"), file);
4206 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4207 _("&Load backup"), _("Load &original"), _("&Cancel"));
4212 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4213 // the file is not saved if we load the autosave file.
4214 if (ret_llf == ReadSuccess) {
4216 Alert::warning(_("File is read-only"),
4217 bformat(_("A backup file is successfully loaded, "
4218 "but the original file %1$s is marked read-only. "
4219 "Please make sure to save the document as a "
4221 from_utf8(d->filename.absFileName())));
4224 lyxvc().file_found_hook(d->filename);
4227 return ReadAutosaveFailure;
4230 // Here we delete the autosave
4231 autosaveFile.removeFile();
4232 return ReadOriginal;
4240 Buffer::ReadStatus Buffer::loadLyXFile()
4242 if (!d->filename.isReadableFile()) {
4243 ReadStatus const ret_rvc = extractFromVC();
4244 if (ret_rvc != ReadSuccess)
4248 ReadStatus const ret_re = loadEmergency();
4249 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4252 ReadStatus const ret_ra = loadAutosave();
4253 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4256 return loadThisLyXFile(d->filename);
4260 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4262 return readFile(fn);
4266 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4268 TeXErrors::Errors::const_iterator it = terr.begin();
4269 TeXErrors::Errors::const_iterator end = terr.end();
4270 ListOfBuffers clist = getDescendents();
4271 ListOfBuffers::const_iterator cen = clist.end();
4273 for (; it != end; ++it) {
4276 int errorRow = it->error_in_line;
4277 Buffer const * buf = 0;
4279 if (it->child_name.empty())
4280 p->texrow.getIdFromRow(errorRow, id_start, pos_start);
4282 // The error occurred in a child
4283 ListOfBuffers::const_iterator cit = clist.begin();
4284 for (; cit != cen; ++cit) {
4285 string const child_name =
4286 DocFileName(changeExtension(
4287 (*cit)->absFileName(), "tex")).
4289 if (it->child_name != child_name)
4291 (*cit)->d->texrow.getIdFromRow(errorRow,
4292 id_start, pos_start);
4293 if (id_start != -1) {
4294 buf = d->cloned_buffer_
4295 ? (*cit)->d->cloned_buffer_->d->owner_
4296 : (*cit)->d->owner_;
4307 found = p->texrow.getIdFromRow(errorRow, id_end, pos_end);
4308 } while (found && id_start == id_end && pos_start == pos_end);
4310 if (id_start != id_end) {
4311 // Next registered position is outside the inset where
4312 // the error occurred, so signal end-of-paragraph
4316 errorList.push_back(ErrorItem(it->error_desc,
4317 it->error_text, id_start, pos_start, pos_end, buf));
4322 void Buffer::setBuffersForInsets() const
4324 inset().setBuffer(const_cast<Buffer &>(*this));
4328 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4330 LBUFERR(!text().paragraphs().empty());
4332 // Use the master text class also for child documents
4333 Buffer const * const master = masterBuffer();
4334 DocumentClass const & textclass = master->params().documentClass();
4336 // do this only if we are the top-level Buffer
4337 if (master == this) {
4338 textclass.counters().reset(from_ascii("bibitem"));
4339 reloadBibInfoCache();
4342 // keep the buffers to be children in this set. If the call from the
4343 // master comes back we can see which of them were actually seen (i.e.
4344 // via an InsetInclude). The remaining ones in the set need still be updated.
4345 static std::set<Buffer const *> bufToUpdate;
4346 if (scope == UpdateMaster) {
4347 // If this is a child document start with the master
4348 if (master != this) {
4349 bufToUpdate.insert(this);
4350 master->updateBuffer(UpdateMaster, utype);
4351 // If the master buffer has no gui associated with it, then the TocModel is
4352 // not updated during the updateBuffer call and TocModel::toc_ is invalid
4353 // (bug 5699). The same happens if the master buffer is open in a different
4354 // window. This test catches both possibilities.
4355 // See: http://marc.info/?l=lyx-devel&m=138590578911716&w=2
4356 // There remains a problem here: If there is another child open in yet a third
4357 // window, that TOC is not updated. So some more general solution is needed at
4359 if (master->d->gui_ != d->gui_)
4362 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4363 if (bufToUpdate.find(this) == bufToUpdate.end())
4367 // start over the counters in the master
4368 textclass.counters().reset();
4371 // update will be done below for this buffer
4372 bufToUpdate.erase(this);
4374 // update all caches
4375 clearReferenceCache();
4378 Buffer & cbuf = const_cast<Buffer &>(*this);
4381 ParIterator parit = cbuf.par_iterator_begin();
4382 updateBuffer(parit, utype);
4385 // TocBackend update will be done later.
4388 d->bibinfo_cache_valid_ = true;
4389 d->cite_labels_valid_ = true;
4390 cbuf.tocBackend().update(utype == OutputUpdate);
4391 if (scope == UpdateMaster)
4392 cbuf.structureChanged();
4396 static depth_type getDepth(DocIterator const & it)
4398 depth_type depth = 0;
4399 for (size_t i = 0 ; i < it.depth() ; ++i)
4400 if (!it[i].inset().inMathed())
4401 depth += it[i].paragraph().getDepth() + 1;
4402 // remove 1 since the outer inset does not count
4406 static depth_type getItemDepth(ParIterator const & it)
4408 Paragraph const & par = *it;
4409 LabelType const labeltype = par.layout().labeltype;
4411 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4414 // this will hold the lowest depth encountered up to now.
4415 depth_type min_depth = getDepth(it);
4416 ParIterator prev_it = it;
4419 --prev_it.top().pit();
4421 // start of nested inset: go to outer par
4423 if (prev_it.empty()) {
4424 // start of document: nothing to do
4429 // We search for the first paragraph with same label
4430 // that is not more deeply nested.
4431 Paragraph & prev_par = *prev_it;
4432 depth_type const prev_depth = getDepth(prev_it);
4433 if (labeltype == prev_par.layout().labeltype) {
4434 if (prev_depth < min_depth)
4435 return prev_par.itemdepth + 1;
4436 if (prev_depth == min_depth)
4437 return prev_par.itemdepth;
4439 min_depth = min(min_depth, prev_depth);
4440 // small optimization: if we are at depth 0, we won't
4441 // find anything else
4442 if (prev_depth == 0)
4448 static bool needEnumCounterReset(ParIterator const & it)
4450 Paragraph const & par = *it;
4451 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, return false);
4452 depth_type const cur_depth = par.getDepth();
4453 ParIterator prev_it = it;
4454 while (prev_it.pit()) {
4455 --prev_it.top().pit();
4456 Paragraph const & prev_par = *prev_it;
4457 if (prev_par.getDepth() <= cur_depth)
4458 return prev_par.layout().labeltype != LABEL_ENUMERATE;
4460 // start of nested inset: reset
4465 // set the label of a paragraph. This includes the counters.
4466 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4468 BufferParams const & bp = owner_->masterBuffer()->params();
4469 DocumentClass const & textclass = bp.documentClass();
4470 Paragraph & par = it.paragraph();
4471 Layout const & layout = par.layout();
4472 Counters & counters = textclass.counters();
4474 if (par.params().startOfAppendix()) {
4475 // We want to reset the counter corresponding to toplevel sectioning
4476 Layout const & lay = textclass.getTOCLayout();
4477 docstring const cnt = lay.counter;
4479 counters.reset(cnt);
4480 counters.appendix(true);
4482 par.params().appendix(counters.appendix());
4484 // Compute the item depth of the paragraph
4485 par.itemdepth = getItemDepth(it);
4487 if (layout.margintype == MARGIN_MANUAL) {
4488 if (par.params().labelWidthString().empty())
4489 par.params().labelWidthString(par.expandLabel(layout, bp));
4490 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4491 // we do not need to do anything here, since the empty case is
4492 // handled during export.
4494 par.params().labelWidthString(docstring());
4497 switch(layout.labeltype) {
4498 case LABEL_ITEMIZE: {
4499 // At some point of time we should do something more
4500 // clever here, like:
4501 // par.params().labelString(
4502 // bp.user_defined_bullet(par.itemdepth).getText());
4503 // for now, use a simple hardcoded label
4504 docstring itemlabel;
4505 switch (par.itemdepth) {
4507 itemlabel = char_type(0x2022);
4510 itemlabel = char_type(0x2013);
4513 itemlabel = char_type(0x2217);
4516 itemlabel = char_type(0x2219); // or 0x00b7
4519 par.params().labelString(itemlabel);
4523 case LABEL_ENUMERATE: {
4524 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4526 switch (par.itemdepth) {
4535 enumcounter += "iv";
4538 // not a valid enumdepth...
4542 // Maybe we have to reset the enumeration counter.
4543 if (needEnumCounterReset(it))
4544 counters.reset(enumcounter);
4545 counters.step(enumcounter, utype);
4547 string const & lang = par.getParLanguage(bp)->code();
4548 par.params().labelString(counters.theCounter(enumcounter, lang));
4553 case LABEL_SENSITIVE: {
4554 string const & type = counters.current_float();
4555 docstring full_label;
4557 full_label = owner_->B_("Senseless!!! ");
4559 docstring name = owner_->B_(textclass.floats().getType(type).name());
4560 if (counters.hasCounter(from_utf8(type))) {
4561 string const & lang = par.getParLanguage(bp)->code();
4562 counters.step(from_utf8(type), utype);
4563 full_label = bformat(from_ascii("%1$s %2$s:"),
4565 counters.theCounter(from_utf8(type), lang));
4567 full_label = bformat(from_ascii("%1$s #:"), name);
4569 par.params().labelString(full_label);
4573 case LABEL_NO_LABEL:
4574 par.params().labelString(docstring());
4578 case LABEL_CENTERED:
4579 case LABEL_STATIC: {
4580 docstring const & lcounter = layout.counter;
4581 if (!lcounter.empty()) {
4582 if (layout.toclevel <= bp.secnumdepth
4583 && (layout.latextype != LATEX_ENVIRONMENT
4584 || it.text()->isFirstInSequence(it.pit()))) {
4585 if (counters.hasCounter(lcounter))
4586 counters.step(lcounter, utype);
4587 par.params().labelString(par.expandLabel(layout, bp));
4589 par.params().labelString(docstring());
4591 par.params().labelString(par.expandLabel(layout, bp));
4597 par.params().labelString(par.expandLabel(layout, bp));
4602 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4604 // LASSERT: Is it safe to continue here, or should we just return?
4605 LASSERT(parit.pit() == 0, /**/);
4607 // Set the position of the text in the buffer to be able
4608 // to resolve macros in it.
4609 parit.text()->setMacrocontextPosition(parit);
4611 depth_type maxdepth = 0;
4612 pit_type const lastpit = parit.lastpit();
4613 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4614 // reduce depth if necessary
4615 if (parit->params().depth() > maxdepth) {
4616 /** FIXME: this function is const, but
4617 * nevertheless it modifies the buffer. To be
4618 * cleaner, one should modify the buffer in
4619 * another function, which is actually
4620 * non-const. This would however be costly in
4621 * terms of code duplication.
4623 const_cast<Buffer *>(this)->undo().recordUndo(CursorData(parit));
4624 parit->params().depth(maxdepth);
4626 maxdepth = parit->getMaxDepthAfter();
4628 if (utype == OutputUpdate) {
4629 // track the active counters
4630 // we have to do this for the master buffer, since the local
4631 // buffer isn't tracking anything.
4632 masterBuffer()->params().documentClass().counters().
4633 setActiveLayout(parit->layout());
4636 // set the counter for this paragraph
4637 d->setLabel(parit, utype);
4640 InsetList::const_iterator iit = parit->insetList().begin();
4641 InsetList::const_iterator end = parit->insetList().end();
4642 for (; iit != end; ++iit) {
4643 parit.pos() = iit->pos;
4644 iit->inset->updateBuffer(parit, utype);
4650 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4651 WordLangTuple & word_lang, docstring_list & suggestions) const
4655 suggestions.clear();
4656 word_lang = WordLangTuple();
4657 bool const to_end = to.empty();
4658 DocIterator const end = to_end ? doc_iterator_end(this) : to;
4659 // OK, we start from here.
4660 for (; from != end; from.forwardPos()) {
4661 // We are only interested in text so remove the math CursorSlice.
4662 while (from.inMathed()) {
4666 // If from is at the end of the document (which is possible
4667 // when leaving the mathed) LyX will crash later otherwise.
4668 if (from.atEnd() || (!to_end && from >= end))
4671 from.paragraph().spellCheck();
4672 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4673 if (SpellChecker::misspelled(res)) {
4678 // Do not increase progress when from == to, otherwise the word
4679 // count will be wrong.
4689 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
4691 bool inword = false;
4696 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
4697 if (!dit.inTexted()) {
4702 Paragraph const & par = dit.paragraph();
4703 pos_type const pos = dit.pos();
4705 // Copied and adapted from isWordSeparator() in Paragraph
4706 if (pos == dit.lastpos()) {
4709 Inset const * ins = par.getInset(pos);
4710 if (ins && skipNoOutput && !ins->producesOutput()) {
4713 // stop if end of range was skipped
4714 if (!to.atEnd() && dit >= to)
4717 } else if (!par.isDeleted(pos)) {
4718 if (par.isWordSeparator(pos))
4724 if (ins && ins->isLetter())
4726 else if (ins && ins->isSpace())
4729 char_type const c = par.getChar(pos);
4730 if (isPrintableNonspace(c))
4732 else if (isSpace(c))
4742 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
4744 d->updateStatistics(from, to, skipNoOutput);
4748 int Buffer::wordCount() const
4750 return d->wordCount();
4754 int Buffer::charCount(bool with_blanks) const
4756 return d->charCount(with_blanks);
4760 Buffer::ReadStatus Buffer::reload()
4763 // c.f. bug http://www.lyx.org/trac/ticket/6587
4764 removeAutosaveFile();
4765 // e.g., read-only status could have changed due to version control
4766 d->filename.refresh();
4767 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4769 // clear parent. this will get reset if need be.
4771 ReadStatus const status = loadLyXFile();
4772 if (status == ReadSuccess) {
4777 message(bformat(_("Document %1$s reloaded."), disp_fn));
4780 message(bformat(_("Could not reload document %1$s."), disp_fn));
4790 bool Buffer::saveAs(FileName const & fn)
4792 FileName const old_name = fileName();
4793 FileName const old_auto = getAutosaveFileName();
4794 bool const old_unnamed = isUnnamed();
4801 // bring the autosave file with us, just in case.
4802 moveAutosaveFile(old_auto);
4803 // validate version control data and
4804 // correct buffer title
4805 lyxvc().file_found_hook(fileName());
4807 // the file has now been saved to the new location.
4808 // we need to check that the locations of child buffers
4810 checkChildBuffers();
4811 checkMasterBuffer();
4815 // reset the old filename and unnamed state
4816 setFileName(old_name);
4817 setUnnamed(old_unnamed);
4823 // FIXME We could do better here, but it is complicated. What would be
4824 // nice is to offer either (a) to save the child buffer to an appropriate
4825 // location, so that it would "move with the master", or else (b) to update
4826 // the InsetInclude so that it pointed to the same file. But (a) is a bit
4827 // complicated, because the code for this lives in GuiView.
4828 void Buffer::checkChildBuffers()
4830 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4831 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4832 for (; it != en; ++it) {
4833 DocIterator dit = it->second;
4834 Buffer * cbuf = const_cast<Buffer *>(it->first);
4835 if (!cbuf || !theBufferList().isLoaded(cbuf))
4837 Inset * inset = dit.nextInset();
4838 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4839 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4840 docstring const & incfile = inset_inc->getParam("filename");
4841 string oldloc = cbuf->absFileName();
4842 string newloc = makeAbsPath(to_utf8(incfile),
4843 onlyPath(absFileName())).absFileName();
4844 if (oldloc == newloc)
4846 // the location of the child file is incorrect.
4847 Alert::warning(_("Included File Invalid"),
4848 bformat(_("Saving this document to a new location has made the file:\n"
4850 "inaccessible. You will need to update the included filename."),
4851 from_utf8(oldloc)));
4853 inset_inc->setChildBuffer(0);
4855 // invalidate cache of children
4856 d->children_positions.clear();
4857 d->position_to_children.clear();
4861 // If a child has been saved under a different name/path, it might have been
4862 // orphaned. Therefore the master needs to be reset (bug 8161).
4863 void Buffer::checkMasterBuffer()
4865 Buffer const * const master = masterBuffer();
4869 // necessary to re-register the child (bug 5873)
4870 // FIXME: clean up updateMacros (here, only
4871 // child registering is needed).
4872 master->updateMacros();
4873 // (re)set master as master buffer, but only
4874 // if we are a real child
4875 if (master->isChild(this))