3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
7 * \author Stefan Schimanski
9 * Full author contact details are available in file CREDITS.
17 #include "LayoutFile.h"
18 #include "BiblioInfo.h"
19 #include "BranchList.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
25 #include "Converter.h"
28 #include "CutAndPaste.h"
29 #include "DispatchResult.h"
30 #include "DocIterator.h"
31 #include "BufferEncodings.h"
32 #include "ErrorList.h"
35 #include "FuncRequest.h"
36 #include "FuncStatus.h"
37 #include "IndicesList.h"
38 #include "InsetIterator.h"
39 #include "InsetList.h"
41 #include "LaTeXFeatures.h"
45 #include "LyXAction.h"
49 #include "output_docbook.h"
51 #include "output_latex.h"
52 #include "output_xhtml.h"
53 #include "output_plaintext.h"
54 #include "Paragraph.h"
55 #include "ParagraphParameters.h"
56 #include "ParIterator.h"
57 #include "PDFOptions.h"
58 #include "SpellChecker.h"
62 #include "TextClass.h"
63 #include "TocBackend.h"
65 #include "VCBackend.h"
67 #include "WordLangTuple.h"
70 #include "insets/InsetBibtex.h"
71 #include "insets/InsetBranch.h"
72 #include "insets/InsetInclude.h"
73 #include "insets/InsetTabular.h"
74 #include "insets/InsetText.h"
76 #include "mathed/InsetMathHull.h"
77 #include "mathed/MacroTable.h"
78 #include "mathed/MathMacroTemplate.h"
79 #include "mathed/MathSupport.h"
81 #include "graphics/PreviewLoader.h"
83 #include "frontends/alert.h"
84 #include "frontends/Delegates.h"
85 #include "frontends/WorkAreaManager.h"
87 #include "support/lassert.h"
88 #include "support/convert.h"
89 #include "support/debug.h"
90 #include "support/docstring_list.h"
91 #include "support/ExceptionMessage.h"
92 #include "support/FileName.h"
93 #include "support/FileNameList.h"
94 #include "support/filetools.h"
95 #include "support/ForkedCalls.h"
96 #include "support/gettext.h"
97 #include "support/gzstream.h"
98 #include "support/lstrings.h"
99 #include "support/lyxalgo.h"
100 #include "support/mutex.h"
101 #include "support/os.h"
102 #include "support/Package.h"
103 #include "support/PathChanger.h"
104 #include "support/Systemcall.h"
105 #include "support/TempFile.h"
106 #include "support/textutils.h"
107 #include "support/types.h"
109 #include "support/bind.h"
110 #include "support/shared_ptr.h"
121 using namespace lyx::support;
122 using namespace lyx::graphics;
126 namespace Alert = frontend::Alert;
127 namespace os = support::os;
131 int const LYX_FORMAT = LYX_FORMAT_LYX;
133 typedef map<string, bool> DepClean;
134 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
139 // A storehouse for the cloned buffers.
140 list<CloneList *> cloned_buffers;
146 Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
150 delete preview_loader_;
158 /// search for macro in local (buffer) table or in children
159 MacroData const * getBufferMacro(docstring const & name,
160 DocIterator const & pos) const;
162 /// Update macro table starting with position of it \param it in some
164 void updateMacros(DocIterator & it, DocIterator & scope);
166 void setLabel(ParIterator & it, UpdateType utype) const;
168 /** If we have branches that use the file suffix
169 feature, return the file name with suffix appended.
171 support::FileName exportFileName() const;
178 mutable TexRow texrow;
180 /// need to regenerate .tex?
184 mutable bool lyx_clean;
186 /// is autosave needed?
187 mutable bool bak_clean;
189 /// is this an unnamed file (New...)?
192 /// is this an internal bufffer?
193 bool internal_buffer;
198 /// name of the file the buffer is associated with.
201 /** Set to true only when the file is fully loaded.
202 * Used to prevent the premature generation of previews
203 * and by the citation inset.
205 bool file_fully_loaded;
207 /// Ignore the parent (e.g. when exporting a child standalone)?
211 mutable TocBackend toc_backend;
216 ScopeMacro(DocIterator const & s, MacroData const & m)
217 : scope(s), macro(m) {}
221 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
222 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
223 /// map from the macro name to the position map,
224 /// which maps the macro definition position to the scope and the MacroData.
225 NamePositionScopeMacroMap macros;
226 /// This seem to change the way Buffer::getMacro() works
227 mutable bool macro_lock;
229 /// positions of child buffers in the buffer
230 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
233 ScopeBuffer(DocIterator const & s,Buffer const * b)
234 : scope(s), buffer(b) {}
236 Buffer const * buffer;
238 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
239 /// position of children buffers in this buffer
240 BufferPositionMap children_positions;
241 /// map from children inclusion positions to their scope and their buffer
242 PositionScopeBufferMap position_to_children;
244 /// Contains the old buffer filePath() while saving-as, or the
245 /// directory where the document was last saved while loading.
248 /** Keeps track of the path of local layout files.
249 * If possible, it is always relative to the buffer path.
250 * Empty for layouts in system or user directory.
252 string layout_position;
254 /// Container for all sort of Buffer dependant errors.
255 map<string, ErrorList> errorLists;
257 /// timestamp and checksum used to test if the file has been externally
258 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
260 unsigned long checksum_;
263 frontend::WorkAreaManager * wa_;
265 frontend::GuiBufferDelegate * gui_;
270 /// A cache for the bibfiles (including bibfiles of loaded child
271 /// documents), needed for appropriate update of natbib labels.
272 mutable support::FileNameList bibfiles_cache_;
274 // FIXME The caching mechanism could be improved. At present, we have a
275 // cache for each Buffer, that caches all the bibliography info for that
276 // Buffer. A more efficient solution would be to have a global cache per
277 // file, and then to construct the Buffer's bibinfo from that.
278 /// A cache for bibliography info
279 mutable BiblioInfo bibinfo_;
280 /// whether the bibinfo cache is valid
281 mutable bool bibinfo_cache_valid_;
282 /// whether the bibfile cache is valid
283 mutable bool bibfile_cache_valid_;
284 /// Cache of timestamps of .bib files
285 map<FileName, time_t> bibfile_status_;
286 /// Indicates whether the bibinfo has changed since the last time
287 /// we ran updateBuffer(), i.e., whether citation labels may need
289 mutable bool cite_labels_valid_;
291 /// These two hold the file name and format, written to by
292 /// Buffer::preview and read from by LFUN_BUFFER_VIEW_CACHE.
293 FileName preview_file_;
294 string preview_format_;
295 /// If there was an error when previewing, on the next preview we do
296 /// a fresh compile (e.g. in case the user installed a package that
300 mutable RefCache ref_cache_;
302 /// our Text that should be wrapped in an InsetText
306 PreviewLoader * preview_loader_;
308 /// This is here to force the test to be done whenever parent_buffer
310 Buffer const * parent() const
312 // ignore_parent temporarily "orphans" a buffer
313 // (e.g. if a child is compiled standalone)
316 // if parent_buffer is not loaded, then it has been unloaded,
317 // which means that parent_buffer is an invalid pointer. So we
318 // set it to null in that case.
319 // however, the BufferList doesn't know about cloned buffers, so
320 // they will always be regarded as unloaded. in that case, we hope
322 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
324 return parent_buffer;
328 void setParent(Buffer const * pb)
330 if (parent_buffer == pb)
333 if (!cloned_buffer_ && parent_buffer && pb)
334 LYXERR0("Warning: a buffer should not have two parents!");
336 if (!cloned_buffer_ && parent_buffer) {
337 parent_buffer->invalidateBibfileCache();
338 parent_buffer->invalidateBibinfoCache();
342 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
343 /// This one is useful for preview detached in a thread.
344 Buffer const * cloned_buffer_;
346 CloneList * clone_list_;
347 /// are we in the process of exporting this buffer?
348 mutable bool doing_export;
350 /// compute statistics
351 /// \p from initial position
352 /// \p to points to the end position
353 void updateStatistics(DocIterator & from, DocIterator & to,
354 bool skipNoOutput = true);
355 /// statistics accessor functions
356 int wordCount() const
360 int charCount(bool with_blanks) const
363 + (with_blanks ? blank_count_ : 0);
367 /// So we can force access via the accessors.
368 mutable Buffer const * parent_buffer;
377 /// Creates the per buffer temporary directory
378 static FileName createBufferTmpDir()
380 // FIXME This would be the ideal application for a TempDir class (like
381 // TempFile but for directories)
386 Mutex::Locker locker(&mutex);
387 counter = convert<string>(count++);
389 // We are in our own directory. Why bother to mangle name?
390 // In fact I wrote this code to circumvent a problematic behaviour
391 // (bug?) of EMX mkstemp().
392 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
395 if (!tmpfl.createDirectory(0777)) {
396 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
397 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
398 from_utf8(tmpfl.absFileName())));
404 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
405 Buffer const * cloned_buffer)
406 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
407 internal_buffer(false), read_only(readonly_), filename(file),
408 file_fully_loaded(false), ignore_parent(false), toc_backend(owner),
409 macro_lock(false), timestamp_(0), checksum_(0), wa_(0), gui_(0),
410 undo_(*owner), bibinfo_cache_valid_(false), bibfile_cache_valid_(false),
411 cite_labels_valid_(false), inset(0), preview_loader_(0),
412 cloned_buffer_(cloned_buffer), clone_list_(0),
413 doing_export(false), parent_buffer(0),
414 word_count_(0), char_count_(0), blank_count_(0)
416 if (!cloned_buffer_) {
417 temppath = createBufferTmpDir();
418 lyxvc.setBuffer(owner_);
420 wa_ = new frontend::WorkAreaManager;
423 temppath = cloned_buffer_->d->temppath;
424 file_fully_loaded = true;
425 params = cloned_buffer_->d->params;
426 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
427 bibinfo_ = cloned_buffer_->d->bibinfo_;
428 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
429 bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
430 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
431 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
432 unnamed = cloned_buffer_->d->unnamed;
433 internal_buffer = cloned_buffer_->d->internal_buffer;
434 layout_position = cloned_buffer_->d->layout_position;
435 preview_file_ = cloned_buffer_->d->preview_file_;
436 preview_format_ = cloned_buffer_->d->preview_format_;
437 preview_error_ = cloned_buffer_->d->preview_error_;
441 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
442 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
444 LYXERR(Debug::INFO, "Buffer::Buffer()");
446 d->inset = new InsetText(*cloned_buffer->d->inset);
447 d->inset->setBuffer(*this);
448 // FIXME: optimize this loop somewhat, maybe by creating a new
449 // general recursive Inset::setId().
450 DocIterator it = doc_iterator_begin(this);
451 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
452 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
453 it.paragraph().setId(cloned_it.paragraph().id());
455 d->inset = new InsetText(this);
456 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
462 LYXERR(Debug::INFO, "Buffer::~Buffer()");
463 // here the buffer should take care that it is
464 // saved properly, before it goes into the void.
466 // GuiView already destroyed
470 // No need to do additional cleanups for internal buffer.
476 // this is in case of recursive includes: we won't try to delete
477 // ourselves as a child.
478 d->clone_list_->erase(this);
479 // loop over children
480 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
481 Impl::BufferPositionMap::iterator end = d->children_positions.end();
482 for (; it != end; ++it) {
483 Buffer * child = const_cast<Buffer *>(it->first);
484 if (d->clone_list_->erase(child))
487 // if we're the master buffer, then we should get rid of the list
490 // If this is not empty, we have leaked something. Worse, one of the
491 // children still has a reference to this list. But we will try to
492 // continue, rather than shut down.
493 LATTEST(d->clone_list_->empty());
494 list<CloneList *>::iterator it =
495 find(cloned_buffers.begin(), cloned_buffers.end(), d->clone_list_);
496 if (it == cloned_buffers.end()) {
497 // We will leak in this case, but it is safe to continue.
500 cloned_buffers.erase(it);
501 delete d->clone_list_;
503 // FIXME Do we really need to do this right before we delete d?
504 // clear references to children in macro tables
505 d->children_positions.clear();
506 d->position_to_children.clear();
508 // loop over children
509 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
510 Impl::BufferPositionMap::iterator end = d->children_positions.end();
511 for (; it != end; ++it) {
512 Buffer * child = const_cast<Buffer *>(it->first);
513 if (theBufferList().isLoaded(child))
514 theBufferList().releaseChild(this, child);
518 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
519 msg += emergencyWrite();
520 Alert::warning(_("Attempting to close changed document!"), msg);
523 // FIXME Do we really need to do this right before we delete d?
524 // clear references to children in macro tables
525 d->children_positions.clear();
526 d->position_to_children.clear();
528 if (!d->temppath.destroyDirectory()) {
529 Alert::warning(_("Could not remove temporary directory"),
530 bformat(_("Could not remove the temporary directory %1$s"),
531 from_utf8(d->temppath.absFileName())));
540 Buffer * Buffer::cloneFromMaster() const
543 cloned_buffers.push_back(new CloneList);
544 CloneList * clones = cloned_buffers.back();
546 masterBuffer()->cloneWithChildren(bufmap, clones);
548 // make sure we got cloned
549 BufferMap::const_iterator bit = bufmap.find(this);
550 LASSERT(bit != bufmap.end(), return 0);
551 Buffer * cloned_buffer = bit->second;
553 return cloned_buffer;
557 void Buffer::cloneWithChildren(BufferMap & bufmap, CloneList * clones) const
559 // have we already been cloned?
560 if (bufmap.find(this) != bufmap.end())
563 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
565 // The clone needs its own DocumentClass, since running updateBuffer() will
566 // modify it, and we would otherwise be sharing it with the original Buffer.
567 buffer_clone->params().makeDocumentClass(true);
569 cap::switchBetweenClasses(
570 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
571 static_cast<InsetText &>(buffer_clone->inset()), el);
573 bufmap[this] = buffer_clone;
574 clones->insert(buffer_clone);
575 buffer_clone->d->clone_list_ = clones;
576 buffer_clone->d->macro_lock = true;
577 buffer_clone->d->children_positions.clear();
579 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
580 // math macro caches need to be rethought and simplified.
581 // I am not sure wether we should handle Buffer cloning here or in BufferList.
582 // Right now BufferList knows nothing about buffer clones.
583 Impl::PositionScopeBufferMap::iterator it = d->position_to_children.begin();
584 Impl::PositionScopeBufferMap::iterator end = d->position_to_children.end();
585 for (; it != end; ++it) {
586 DocIterator dit = it->first.clone(buffer_clone);
587 dit.setBuffer(buffer_clone);
588 Buffer * child = const_cast<Buffer *>(it->second.buffer);
590 child->cloneWithChildren(bufmap, clones);
591 BufferMap::iterator const bit = bufmap.find(child);
592 LASSERT(bit != bufmap.end(), continue);
593 Buffer * child_clone = bit->second;
595 Inset * inset = dit.nextInset();
596 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
597 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
598 inset_inc->setChildBuffer(child_clone);
599 child_clone->d->setParent(buffer_clone);
600 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
601 buffer_clone->setChild(dit, child_clone);
603 buffer_clone->d->macro_lock = false;
608 Buffer * Buffer::cloneBufferOnly() const {
609 cloned_buffers.push_back(new CloneList);
610 CloneList * clones = cloned_buffers.back();
611 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
613 // The clone needs its own DocumentClass, since running updateBuffer() will
614 // modify it, and we would otherwise be sharing it with the original Buffer.
615 buffer_clone->params().makeDocumentClass(true);
617 cap::switchBetweenClasses(
618 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
619 static_cast<InsetText &>(buffer_clone->inset()), el);
621 clones->insert(buffer_clone);
622 buffer_clone->d->clone_list_ = clones;
624 // we won't be cloning the children
625 buffer_clone->d->children_positions.clear();
630 bool Buffer::isClone() const
632 return d->cloned_buffer_;
636 void Buffer::changed(bool update_metrics) const
639 d->wa_->redrawAll(update_metrics);
643 frontend::WorkAreaManager & Buffer::workAreaManager() const
650 Text & Buffer::text() const
652 return d->inset->text();
656 Inset & Buffer::inset() const
662 BufferParams & Buffer::params()
668 BufferParams const & Buffer::params() const
674 BufferParams const & Buffer::masterParams() const
676 if (masterBuffer() == this)
679 BufferParams & mparams = const_cast<Buffer *>(masterBuffer())->params();
680 // Copy child authors to the params. We need those pointers.
681 AuthorList const & child_authors = params().authors();
682 AuthorList::Authors::const_iterator it = child_authors.begin();
683 for (; it != child_authors.end(); ++it)
684 mparams.authors().record(*it);
689 double Buffer::fontScalingFactor() const
691 return isExporting() ? 75.0 * params().html_math_img_scale
692 : 0.01 * lyxrc.dpi * lyxrc.zoom * lyxrc.preview_scale_factor * params().display_pixel_ratio;
696 ParagraphList & Buffer::paragraphs()
698 return text().paragraphs();
702 ParagraphList const & Buffer::paragraphs() const
704 return text().paragraphs();
708 LyXVC & Buffer::lyxvc()
714 LyXVC const & Buffer::lyxvc() const
720 string const Buffer::temppath() const
722 return d->temppath.absFileName();
726 TexRow & Buffer::texrow()
732 TexRow const & Buffer::texrow() const
738 TocBackend & Buffer::tocBackend() const
740 return d->toc_backend;
744 Undo & Buffer::undo()
750 void Buffer::setChild(DocIterator const & dit, Buffer * child)
752 d->children_positions[child] = dit;
756 string Buffer::latexName(bool const no_path) const
758 FileName latex_name =
759 makeLatexName(d->exportFileName());
760 return no_path ? latex_name.onlyFileName()
761 : latex_name.absFileName();
765 FileName Buffer::Impl::exportFileName() const
767 docstring const branch_suffix =
768 params.branchlist().getFileNameSuffix();
769 if (branch_suffix.empty())
772 string const name = filename.onlyFileNameWithoutExt()
773 + to_utf8(branch_suffix);
774 FileName res(filename.onlyPath().absFileName() + "/" + name);
775 res.changeExtension(filename.extension());
781 string Buffer::logName(LogType * type) const
783 string const filename = latexName(false);
785 if (filename.empty()) {
791 string const path = temppath();
793 FileName const fname(addName(temppath(),
794 onlyFileName(changeExtension(filename,
797 // FIXME: how do we know this is the name of the build log?
798 FileName const bname(
799 addName(path, onlyFileName(
800 changeExtension(filename,
801 formats.extension(params().bufferFormat()) + ".out"))));
803 // Also consider the master buffer log file
804 FileName masterfname = fname;
805 LogType mtype = latexlog;
806 if (masterBuffer() != this) {
807 string const mlogfile = masterBuffer()->logName(&mtype);
808 masterfname = FileName(mlogfile);
811 // If no Latex log or Build log is newer, show Build log
812 if (bname.exists() &&
813 ((!fname.exists() && !masterfname.exists())
814 || (fname.lastModified() < bname.lastModified()
815 && masterfname.lastModified() < bname.lastModified()))) {
816 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
819 return bname.absFileName();
820 // If we have a newer master file log or only a master log, show this
821 } else if (fname != masterfname
822 && (!fname.exists() && (masterfname.exists()
823 || fname.lastModified() < masterfname.lastModified()))) {
824 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
827 return masterfname.absFileName();
829 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
832 return fname.absFileName();
836 void Buffer::setReadonly(bool const flag)
838 if (d->read_only != flag) {
845 void Buffer::setFileName(FileName const & fname)
847 bool const changed = fname != d->filename;
850 lyxvc().file_found_hook(fname);
851 setReadonly(d->filename.isReadOnly());
857 int Buffer::readHeader(Lexer & lex)
859 int unknown_tokens = 0;
861 int begin_header_line = -1;
863 // Initialize parameters that may be/go lacking in header:
864 params().branchlist().clear();
865 params().preamble.erase();
866 params().options.erase();
867 params().master.erase();
868 params().float_placement.erase();
869 params().paperwidth.erase();
870 params().paperheight.erase();
871 params().leftmargin.erase();
872 params().rightmargin.erase();
873 params().topmargin.erase();
874 params().bottommargin.erase();
875 params().headheight.erase();
876 params().headsep.erase();
877 params().footskip.erase();
878 params().columnsep.erase();
879 params().fonts_cjk.erase();
880 params().listings_params.clear();
881 params().clearLayoutModules();
882 params().clearRemovedModules();
883 params().clearIncludedChildren();
884 params().pdfoptions().clear();
885 params().indiceslist().clear();
886 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
887 params().isbackgroundcolor = false;
888 params().fontcolor = RGBColor(0, 0, 0);
889 params().isfontcolor = false;
890 params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
891 params().boxbgcolor = RGBColor(0xFF, 0, 0);
892 params().html_latex_start.clear();
893 params().html_latex_end.clear();
894 params().html_math_img_scale = 1.0;
895 params().output_sync_macro.erase();
896 params().setLocalLayout(string(), false);
897 params().setLocalLayout(string(), true);
899 for (int i = 0; i < 4; ++i) {
900 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
901 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
904 ErrorList & errorList = d->errorLists["Parse"];
913 if (token == "\\end_header")
917 if (token == "\\begin_header") {
918 begin_header_line = line;
922 LYXERR(Debug::PARSER, "Handling document header token: `"
925 string const result =
926 params().readToken(lex, token, d->filename.onlyPath());
927 if (!result.empty()) {
928 if (token == "\\textclass") {
929 d->layout_position = result;
932 docstring const s = bformat(_("Unknown token: "
936 errorList.push_back(ErrorItem(_("Document header error"),
941 if (begin_header_line) {
942 docstring const s = _("\\begin_header is missing");
943 errorList.push_back(ErrorItem(_("Document header error"),
947 params().makeDocumentClass();
949 return unknown_tokens;
954 // changed to be public and have one parameter
955 // Returns true if "\end_document" is not read (Asger)
956 bool Buffer::readDocument(Lexer & lex)
958 ErrorList & errorList = d->errorLists["Parse"];
961 // remove dummy empty par
962 paragraphs().clear();
964 if (!lex.checkFor("\\begin_document")) {
965 docstring const s = _("\\begin_document is missing");
966 errorList.push_back(ErrorItem(_("Document header error"),
972 if (params().output_changes) {
973 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
974 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
975 LaTeXFeatures::isAvailable("xcolor");
977 if (!dvipost && !xcolorulem) {
978 Alert::warning(_("Changes not shown in LaTeX output"),
979 _("Changes will not be highlighted in LaTeX output, "
980 "because neither dvipost nor xcolor/ulem are installed.\n"
981 "Please install these packages or redefine "
982 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
983 } else if (!xcolorulem) {
984 Alert::warning(_("Changes not shown in LaTeX output"),
985 _("Changes will not be highlighted in LaTeX output "
986 "when using pdflatex, because xcolor and ulem are not installed.\n"
987 "Please install both packages or redefine "
988 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
992 if (!parent() && !params().master.empty()) {
993 FileName const master_file = makeAbsPath(params().master,
994 onlyPath(absFileName()));
995 if (isLyXFileName(master_file.absFileName())) {
997 checkAndLoadLyXFile(master_file, true);
999 // necessary e.g. after a reload
1000 // to re-register the child (bug 5873)
1001 // FIXME: clean up updateMacros (here, only
1002 // child registering is needed).
1003 master->updateMacros();
1004 // set master as master buffer, but only
1005 // if we are a real child
1006 if (master->isChild(this))
1008 // if the master is not fully loaded
1009 // it is probably just loading this
1010 // child. No warning needed then.
1011 else if (master->isFullyLoaded())
1012 LYXERR0("The master '"
1014 << "' assigned to this document ("
1016 << ") does not include "
1017 "this document. Ignoring the master assignment.");
1022 // assure we have a default index
1023 params().indiceslist().addDefault(B_("Index"));
1026 d->old_position = originFilePath();
1027 bool const res = text().read(lex, errorList, d->inset);
1028 d->old_position.clear();
1030 // inform parent buffer about local macros
1032 Buffer const * pbuf = parent();
1033 UserMacroSet::const_iterator cit = usermacros.begin();
1034 UserMacroSet::const_iterator end = usermacros.end();
1035 for (; cit != end; ++cit)
1036 pbuf->usermacros.insert(*cit);
1040 updateMacroInstances(InternalUpdate);
1045 bool Buffer::importString(string const & format, docstring const & contents, ErrorList & errorList)
1047 Format const * fmt = formats.getFormat(format);
1050 // It is important to use the correct extension here, since some
1051 // converters create a wrong output file otherwise (e.g. html2latex)
1052 TempFile const tempfile("Buffer_importStringXXXXXX." + fmt->extension());
1053 FileName const name(tempfile.name());
1054 ofdocstream os(name.toFilesystemEncoding().c_str());
1055 // Do not convert os implicitly to bool, since that is forbidden in C++11.
1056 bool const success = !(os << contents).fail();
1059 bool converted = false;
1061 params().compressed = false;
1063 // remove dummy empty par
1064 paragraphs().clear();
1066 converted = importFile(format, name, errorList);
1075 bool Buffer::importFile(string const & format, FileName const & name, ErrorList & errorList)
1077 if (!theConverters().isReachable(format, "lyx"))
1080 TempFile const tempfile("Buffer_importFileXXXXXX.lyx");
1081 FileName const lyx(tempfile.name());
1082 if (theConverters().convert(0, name, lyx, name, format, "lyx", errorList))
1083 return readFile(lyx) == ReadSuccess;
1089 bool Buffer::readString(string const & s)
1091 params().compressed = false;
1094 istringstream is(s);
1096 TempFile tempfile("Buffer_readStringXXXXXX.lyx");
1097 FileName const fn = tempfile.name();
1100 bool success = parseLyXFormat(lex, fn, file_format) == ReadSuccess;
1102 if (success && file_format != LYX_FORMAT) {
1103 // We need to call lyx2lyx, so write the input to a file
1104 ofstream os(fn.toFilesystemEncoding().c_str());
1107 // lyxvc in readFile
1108 if (readFile(fn) != ReadSuccess)
1112 if (readDocument(lex))
1118 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
1122 if (!lex.setFile(fname)) {
1123 Alert::error(_("File Not Found"),
1124 bformat(_("Unable to open file `%1$s'."),
1125 from_utf8(fn.absFileName())));
1126 return ReadFileNotFound;
1130 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
1131 if (ret_plf != ReadSuccess)
1134 if (file_format != LYX_FORMAT) {
1136 ReadStatus const ret_clf = convertLyXFormat(fn, tmpFile, file_format);
1137 if (ret_clf != ReadSuccess)
1139 return readFile(tmpFile);
1142 // FIXME: InsetInfo needs to know whether the file is under VCS
1143 // during the parse process, so this has to be done before.
1144 lyxvc().file_found_hook(d->filename);
1146 if (readDocument(lex)) {
1147 Alert::error(_("Document format failure"),
1148 bformat(_("%1$s ended unexpectedly, which means"
1149 " that it is probably corrupted."),
1150 from_utf8(fn.absFileName())));
1151 return ReadDocumentFailure;
1154 d->file_fully_loaded = true;
1155 d->read_only = !d->filename.isWritable();
1156 params().compressed = formats.isZippedFile(d->filename);
1162 bool Buffer::isFullyLoaded() const
1164 return d->file_fully_loaded;
1168 void Buffer::setFullyLoaded(bool value)
1170 d->file_fully_loaded = value;
1174 bool Buffer::lastPreviewError() const
1176 return d->preview_error_;
1180 PreviewLoader * Buffer::loader() const
1182 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1184 if (!d->preview_loader_)
1185 d->preview_loader_ = new PreviewLoader(*this);
1186 return d->preview_loader_;
1190 void Buffer::removePreviews() const
1192 delete d->preview_loader_;
1193 d->preview_loader_ = 0;
1197 void Buffer::updatePreviews() const
1199 PreviewLoader * ploader = loader();
1203 InsetIterator it = inset_iterator_begin(*d->inset);
1204 InsetIterator const end = inset_iterator_end(*d->inset);
1205 for (; it != end; ++it)
1206 it->addPreview(it, *ploader);
1208 ploader->startLoading();
1212 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1213 FileName const & fn, int & file_format) const
1215 if(!lex.checkFor("\\lyxformat")) {
1216 Alert::error(_("Document format failure"),
1217 bformat(_("%1$s is not a readable LyX document."),
1218 from_utf8(fn.absFileName())));
1219 return ReadNoLyXFormat;
1225 // LyX formats 217 and earlier were written as 2.17. This corresponds
1226 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1227 // these cases. See also: www.lyx.org/trac/changeset/1313.
1228 size_t dot = tmp_format.find_first_of(".,");
1229 if (dot != string::npos)
1230 tmp_format.erase(dot, 1);
1232 file_format = convert<int>(tmp_format);
1237 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1238 FileName & tmpfile, int from_format)
1240 TempFile tempfile("Buffer_convertLyXFormatXXXXXX.lyx");
1241 tempfile.setAutoRemove(false);
1242 tmpfile = tempfile.name();
1243 if(tmpfile.empty()) {
1244 Alert::error(_("Conversion failed"),
1245 bformat(_("%1$s is from a different"
1246 " version of LyX, but a temporary"
1247 " file for converting it could"
1248 " not be created."),
1249 from_utf8(fn.absFileName())));
1250 return LyX2LyXNoTempFile;
1253 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1254 if (lyx2lyx.empty()) {
1255 Alert::error(_("Conversion script not found"),
1256 bformat(_("%1$s is from a different"
1257 " version of LyX, but the"
1258 " conversion script lyx2lyx"
1259 " could not be found."),
1260 from_utf8(fn.absFileName())));
1261 return LyX2LyXNotFound;
1265 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1266 ostringstream command;
1267 command << os::python()
1268 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1269 << " -t " << convert<string>(LYX_FORMAT)
1270 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
1271 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1272 string const command_str = command.str();
1274 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1276 cmd_ret const ret = runCommand(command_str);
1277 if (ret.first != 0) {
1278 if (from_format < LYX_FORMAT) {
1279 Alert::error(_("Conversion script failed"),
1280 bformat(_("%1$s is from an older version"
1281 " of LyX and the lyx2lyx script"
1282 " failed to convert it."),
1283 from_utf8(fn.absFileName())));
1284 return LyX2LyXOlderFormat;
1286 Alert::error(_("Conversion script failed"),
1287 bformat(_("%1$s is from a newer version"
1288 " of LyX and the lyx2lyx script"
1289 " failed to convert it."),
1290 from_utf8(fn.absFileName())));
1291 return LyX2LyXNewerFormat;
1298 // Should probably be moved to somewhere else: BufferView? GuiView?
1299 bool Buffer::save() const
1301 docstring const file = makeDisplayPath(absFileName(), 20);
1302 d->filename.refresh();
1304 // check the read-only status before moving the file as a backup
1305 if (d->filename.exists()) {
1306 bool const read_only = !d->filename.isWritable();
1308 Alert::warning(_("File is read-only"),
1309 bformat(_("The file %1$s cannot be written because it "
1310 "is marked as read-only."), file));
1315 // ask if the disk file has been externally modified (use checksum method)
1316 if (fileName().exists() && isExternallyModified(checksum_method)) {
1318 bformat(_("Document %1$s has been externally modified. "
1319 "Are you sure you want to overwrite this file?"), file);
1320 int const ret = Alert::prompt(_("Overwrite modified file?"),
1321 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1326 // We don't need autosaves in the immediate future. (Asger)
1327 resetAutosaveTimers();
1329 // if the file does not yet exist, none of the backup activity
1330 // that follows is necessary
1331 if (!fileName().exists()) {
1332 if (!writeFile(fileName()))
1338 // we first write the file to a new name, then move it to its
1339 // proper location once that has been done successfully. that
1340 // way we preserve the original file if something goes wrong.
1341 string const justname = fileName().onlyFileNameWithoutExt();
1342 boost::scoped_ptr<TempFile>
1343 tempfile(new TempFile(fileName().onlyPath(),
1344 justname + "-XXXXXX.lyx"));
1345 bool const symlink = fileName().isSymLink();
1347 tempfile->setAutoRemove(false);
1349 FileName savefile(tempfile->name());
1350 LYXERR(Debug::FILES, "Saving to " << savefile.absFileName());
1351 if (!writeFile(savefile))
1354 // we will set this to false if we fail
1355 bool made_backup = true;
1357 FileName backupName(absFileName() + '~');
1358 if (lyxrc.make_backup) {
1359 if (!lyxrc.backupdir_path.empty()) {
1360 string const mangledName =
1361 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1362 backupName = FileName(addName(lyxrc.backupdir_path,
1366 LYXERR(Debug::FILES, "Backing up original file to " <<
1367 backupName.absFileName());
1368 // Except file is symlink do not copy because of #6587.
1369 // Hard links have bad luck.
1370 made_backup = symlink ?
1371 fileName().copyTo(backupName):
1372 fileName().moveTo(backupName);
1375 Alert::error(_("Backup failure"),
1376 bformat(_("Cannot create backup file %1$s.\n"
1377 "Please check whether the directory exists and is writable."),
1378 from_utf8(backupName.absFileName())));
1379 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1383 // Destroy tempfile since it keeps the file locked on windows (bug 9234)
1384 // Only do this if tempfile is not in autoremove mode
1387 // If we have no symlink, we can simply rename the temp file.
1388 // Otherwise, we need to copy it so the symlink stays intact.
1389 if (made_backup && symlink ? savefile.copyTo(fileName(), true) :
1390 savefile.moveTo(fileName()))
1392 // saveCheckSum() was already called by writeFile(), but the
1393 // time stamp is invalidated by copying/moving
1398 // else we saved the file, but failed to move it to the right location.
1400 if (lyxrc.make_backup && made_backup && !symlink) {
1401 // the original file was moved to filename.lyx~, so it will look
1402 // to the user as if it was deleted. (see bug #9234.) we could try
1403 // to restore it, but that would basically mean trying to do again
1404 // what we just failed to do. better to leave things as they are.
1405 Alert::error(_("Write failure"),
1406 bformat(_("The file has successfully been saved as:\n %1$s.\n"
1407 "But LyX could not move it to:\n %2$s.\n"
1408 "Your original file has been backed up to:\n %3$s"),
1409 from_utf8(savefile.absFileName()),
1410 from_utf8(fileName().absFileName()),
1411 from_utf8(backupName.absFileName())));
1413 // either we did not try to make a backup, or else we tried and failed,
1414 // or else the original file was a symlink, in which case it was copied,
1415 // not moved. so the original file is intact.
1416 Alert::error(_("Write failure"),
1417 bformat(_("Cannot move saved file to:\n %1$s.\n"
1418 "But the file has successfully been saved as:\n %2$s."),
1419 from_utf8(fileName().absFileName()),
1420 from_utf8(savefile.absFileName())));
1426 bool Buffer::writeFile(FileName const & fname) const
1428 if (d->read_only && fname == d->filename)
1431 bool retval = false;
1433 docstring const str = bformat(_("Saving document %1$s..."),
1434 makeDisplayPath(fname.absFileName()));
1437 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1439 if (params().compressed) {
1440 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1441 retval = ofs && write(ofs);
1443 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1444 retval = ofs && write(ofs);
1448 message(str + _(" could not write file!"));
1453 // removeAutosaveFile();
1456 message(str + _(" done."));
1462 docstring Buffer::emergencyWrite()
1464 // No need to save if the buffer has not changed.
1468 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1470 docstring user_message = bformat(
1471 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1473 // We try to save three places:
1474 // 1) Same place as document. Unless it is an unnamed doc.
1476 string s = absFileName();
1479 if (writeFile(FileName(s))) {
1481 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1482 return user_message;
1484 user_message += " " + _("Save failed! Trying again...\n");
1488 // 2) In HOME directory.
1489 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1491 lyxerr << ' ' << s << endl;
1492 if (writeFile(FileName(s))) {
1494 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1495 return user_message;
1498 user_message += " " + _("Save failed! Trying yet again...\n");
1500 // 3) In "/tmp" directory.
1501 // MakeAbsPath to prepend the current
1502 // drive letter on OS/2
1503 s = addName(package().temp_dir().absFileName(), absFileName());
1505 lyxerr << ' ' << s << endl;
1506 if (writeFile(FileName(s))) {
1508 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1509 return user_message;
1512 user_message += " " + _("Save failed! Bummer. Document is lost.");
1515 return user_message;
1519 bool Buffer::write(ostream & ofs) const
1522 // Use the standard "C" locale for file output.
1523 ofs.imbue(locale::classic());
1526 // The top of the file should not be written by params().
1528 // write out a comment in the top of the file
1529 // Important: Keep the version formatting in sync with lyx2lyx and
1530 // tex2lyx (bug 7951)
1531 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1532 << " created this file. For more info see http://www.lyx.org/\n"
1533 << "\\lyxformat " << LYX_FORMAT << "\n"
1534 << "\\begin_document\n";
1536 /// For each author, set 'used' to true if there is a change
1537 /// by this author in the document; otherwise set it to 'false'.
1538 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1539 AuthorList::Authors::const_iterator a_end = params().authors().end();
1540 for (; a_it != a_end; ++a_it)
1541 a_it->setUsed(false);
1543 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1544 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1545 for ( ; it != end; ++it)
1546 it->checkAuthors(params().authors());
1548 // now write out the buffer parameters.
1549 ofs << "\\begin_header\n";
1550 params().writeFile(ofs, this);
1551 ofs << "\\end_header\n";
1554 ofs << "\n\\begin_body\n";
1556 ofs << "\n\\end_body\n";
1558 // Write marker that shows file is complete
1559 ofs << "\\end_document" << endl;
1561 // Shouldn't really be needed....
1564 // how to check if close went ok?
1565 // Following is an attempt... (BE 20001011)
1567 // good() returns false if any error occurred, including some
1568 // formatting error.
1569 // bad() returns true if something bad happened in the buffer,
1570 // which should include file system full errors.
1575 lyxerr << "File was not closed properly." << endl;
1582 bool Buffer::makeLaTeXFile(FileName const & fname,
1583 string const & original_path,
1584 OutputParams const & runparams_in,
1585 OutputWhat output) const
1587 OutputParams runparams = runparams_in;
1589 // XeTeX with TeX fonts is only safe with ASCII encoding,
1590 // See #9740 and FIXME in BufferParams::encoding()
1591 if (!params().useNonTeXFonts && (runparams.flavor == OutputParams::XETEX))
1592 runparams.encoding = encodings.fromLyXName("ascii");
1594 string const encoding = runparams.encoding->iconvName();
1595 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1598 try { ofs.reset(encoding); }
1599 catch (iconv_codecvt_facet_exception const & e) {
1600 lyxerr << "Caught iconv exception: " << e.what() << endl;
1601 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1602 "verify that the support software for your encoding (%1$s) is "
1603 "properly installed"), from_ascii(encoding)));
1606 if (!openFileWrite(ofs, fname))
1609 ErrorList & errorList = d->errorLists["Export"];
1611 bool failed_export = false;
1612 otexstream os(ofs, d->texrow);
1614 // make sure we are ready to export
1615 // this needs to be done before we validate
1616 // FIXME Do we need to do this all the time? I.e., in children
1617 // of a master we are exporting?
1619 updateMacroInstances(OutputUpdate);
1622 os.texrow().reset();
1623 writeLaTeXSource(os, original_path, runparams, output);
1625 catch (EncodingException const & e) {
1626 docstring const failed(1, e.failed_char);
1628 oss << "0x" << hex << e.failed_char << dec;
1629 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1630 " (code point %2$s)"),
1631 failed, from_utf8(oss.str()));
1632 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1633 "representable in the chosen encoding.\n"
1634 "Changing the document encoding to utf8 could help."),
1635 e.par_id, e.pos, e.pos + 1));
1636 failed_export = true;
1638 catch (iconv_codecvt_facet_exception const & e) {
1639 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1640 _(e.what()), -1, 0, 0));
1641 failed_export = true;
1643 catch (exception const & e) {
1644 errorList.push_back(ErrorItem(_("conversion failed"),
1645 _(e.what()), -1, 0, 0));
1646 failed_export = true;
1649 lyxerr << "Caught some really weird exception..." << endl;
1655 failed_export = true;
1656 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1659 if (runparams_in.silent)
1663 return !failed_export;
1667 void Buffer::writeLaTeXSource(otexstream & os,
1668 string const & original_path,
1669 OutputParams const & runparams_in,
1670 OutputWhat output) const
1672 // The child documents, if any, shall be already loaded at this point.
1674 OutputParams runparams = runparams_in;
1676 // XeTeX with TeX fonts is only safe with ASCII encoding,
1677 // See #9740 and FIXME in BufferParams::encoding()
1678 // FIXME: when only the current paragraph is shown, this seems to be ignored:
1679 // characters encodable in the current encoding are not converted to ASCII-representation.
1680 if (!params().useNonTeXFonts && (runparams.flavor == OutputParams::XETEX))
1681 runparams.encoding = encodings.fromLyXName("ascii");
1683 // If we are compiling a file standalone, even if this is the
1684 // child of some other buffer, let's cut the link here, so the
1685 // file is really independent and no concurring settings from
1686 // the master (e.g. branch state) interfere (see #8100).
1687 if (!runparams.is_child)
1688 d->ignore_parent = true;
1690 // Classify the unicode characters appearing in math insets
1691 BufferEncodings::initUnicodeMath(*this);
1693 // validate the buffer.
1694 LYXERR(Debug::LATEX, " Validating buffer...");
1695 LaTeXFeatures features(*this, params(), runparams);
1697 // This is only set once per document (in master)
1698 if (!runparams.is_child)
1699 runparams.use_polyglossia = features.usePolyglossia();
1700 LYXERR(Debug::LATEX, " Buffer validation done.");
1702 bool const output_preamble =
1703 output == FullSource || output == OnlyPreamble;
1704 bool const output_body =
1705 output == FullSource || output == OnlyBody;
1707 // The starting paragraph of the coming rows is the
1708 // first paragraph of the document. (Asger)
1709 if (output_preamble && runparams.nice) {
1710 os << "%% LyX " << lyx_version << " created this file. "
1711 "For more info, see http://www.lyx.org/.\n"
1712 "%% Do not edit unless you really know what "
1715 LYXERR(Debug::INFO, "lyx document header finished");
1717 // There are a few differences between nice LaTeX and usual files:
1718 // usual files have \batchmode and special input@path to allow
1719 // inclusion of figures specified by an explicitly relative path
1720 // (i.e., a path starting with './' or '../') with either \input or
1721 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1722 // input@path is set when the actual parameter original_path is set.
1723 // This is done for usual tex-file, but not for nice-latex-file.
1724 // (Matthias 250696)
1725 // Note that input@path is only needed for something the user does
1726 // in the preamble, included .tex files or ERT, files included by
1727 // LyX work without it.
1728 if (output_preamble) {
1729 if (!runparams.nice) {
1730 // code for usual, NOT nice-latex-file
1731 os << "\\batchmode\n"; // changed from \nonstopmode
1733 if (!original_path.empty()) {
1735 // We don't know the encoding of inputpath
1736 docstring const inputpath = from_utf8(original_path);
1737 docstring uncodable_glyphs;
1738 Encoding const * const enc = runparams.encoding;
1740 for (size_t n = 0; n < inputpath.size(); ++n) {
1741 if (!enc->encodable(inputpath[n])) {
1742 docstring const glyph(1, inputpath[n]);
1743 LYXERR0("Uncodable character '"
1745 << "' in input path!");
1746 uncodable_glyphs += glyph;
1751 // warn user if we found uncodable glyphs.
1752 if (!uncodable_glyphs.empty()) {
1753 frontend::Alert::warning(
1754 _("Uncodable character in file path"),
1756 _("The path of your document\n"
1758 "contains glyphs that are unknown "
1759 "in the current document encoding "
1760 "(namely %2$s). This may result in "
1761 "incomplete output, unless "
1762 "TEXINPUTS contains the document "
1763 "directory and you don't use "
1764 "explicitly relative paths (i.e., "
1765 "paths starting with './' or "
1766 "'../') in the preamble or in ERT."
1767 "\n\nIn case of problems, choose "
1768 "an appropriate document encoding\n"
1769 "(such as utf8) or change the "
1771 inputpath, uncodable_glyphs));
1774 support::latex_path(original_path);
1775 if (contains(docdir, '#')) {
1776 docdir = subst(docdir, "#", "\\#");
1777 os << "\\catcode`\\#=11"
1778 "\\def\\#{#}\\catcode`\\#=6\n";
1780 if (contains(docdir, '%')) {
1781 docdir = subst(docdir, "%", "\\%");
1782 os << "\\catcode`\\%=11"
1783 "\\def\\%{%}\\catcode`\\%=14\n";
1785 os << "\\makeatletter\n"
1786 << "\\def\\input@path{{"
1788 << "\\makeatother\n";
1792 // get parent macros (if this buffer has a parent) which will be
1793 // written at the document begin further down.
1794 MacroSet parentMacros;
1795 listParentMacros(parentMacros, features);
1797 // Write the preamble
1798 runparams.use_babel = params().writeLaTeX(os, features,
1799 d->filename.onlyPath());
1801 // Japanese might be required only in some children of a document,
1802 // but once required, we must keep use_japanese true.
1803 runparams.use_japanese |= features.isRequired("japanese");
1806 // Restore the parenthood if needed
1807 if (!runparams.is_child)
1808 d->ignore_parent = false;
1813 os << "\\begin{document}\n";
1815 // output the parent macros
1816 MacroSet::iterator it = parentMacros.begin();
1817 MacroSet::iterator end = parentMacros.end();
1818 for (; it != end; ++it) {
1819 int num_lines = (*it)->write(os.os(), true);
1820 os.texrow().newlines(num_lines);
1823 } // output_preamble
1825 os.texrow().start(paragraphs().begin()->id(), 0);
1827 LYXERR(Debug::INFO, "preamble finished, now the body.");
1830 latexParagraphs(*this, text(), os, runparams);
1832 // Restore the parenthood if needed
1833 if (!runparams.is_child)
1834 d->ignore_parent = false;
1836 // add this just in case after all the paragraphs
1839 if (output_preamble) {
1840 os << "\\end{document}\n";
1841 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1843 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1845 runparams_in.encoding = runparams.encoding;
1847 os.texrow().finalize();
1849 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1850 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
1854 void Buffer::makeDocBookFile(FileName const & fname,
1855 OutputParams const & runparams,
1856 OutputWhat output) const
1858 LYXERR(Debug::LATEX, "makeDocBookFile...");
1861 if (!openFileWrite(ofs, fname))
1864 // make sure we are ready to export
1865 // this needs to be done before we validate
1867 updateMacroInstances(OutputUpdate);
1869 writeDocBookSource(ofs, fname.absFileName(), runparams, output);
1873 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1877 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1878 OutputParams const & runparams,
1879 OutputWhat output) const
1881 LaTeXFeatures features(*this, params(), runparams);
1884 d->texrow.reset(false);
1886 DocumentClass const & tclass = params().documentClass();
1887 string const & top_element = tclass.latexname();
1889 bool const output_preamble =
1890 output == FullSource || output == OnlyPreamble;
1891 bool const output_body =
1892 output == FullSource || output == OnlyBody;
1894 if (output_preamble) {
1895 if (runparams.flavor == OutputParams::XML)
1896 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1899 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1902 if (! tclass.class_header().empty())
1903 os << from_ascii(tclass.class_header());
1904 else if (runparams.flavor == OutputParams::XML)
1905 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1906 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1908 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1910 docstring preamble = from_utf8(params().preamble);
1911 if (runparams.flavor != OutputParams::XML ) {
1912 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1913 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1914 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1915 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1918 string const name = runparams.nice
1919 ? changeExtension(absFileName(), ".sgml") : fname;
1920 preamble += features.getIncludedFiles(name);
1921 preamble += features.getLyXSGMLEntities();
1923 if (!preamble.empty()) {
1924 os << "\n [ " << preamble << " ]";
1930 string top = top_element;
1932 if (runparams.flavor == OutputParams::XML)
1933 top += params().language->code();
1935 top += params().language->code().substr(0, 2);
1938 if (!params().options.empty()) {
1940 top += params().options;
1943 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1944 << " file was created by LyX " << lyx_version
1945 << "\n See http://www.lyx.org/ for more information -->\n";
1947 params().documentClass().counters().reset();
1949 sgml::openTag(os, top);
1951 docbookParagraphs(text(), *this, os, runparams);
1952 sgml::closeTag(os, top_element);
1957 void Buffer::makeLyXHTMLFile(FileName const & fname,
1958 OutputParams const & runparams) const
1960 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1963 if (!openFileWrite(ofs, fname))
1966 // make sure we are ready to export
1967 // this has to be done before we validate
1968 updateBuffer(UpdateMaster, OutputUpdate);
1969 updateMacroInstances(OutputUpdate);
1971 writeLyXHTMLSource(ofs, runparams, FullSource);
1975 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1979 void Buffer::writeLyXHTMLSource(odocstream & os,
1980 OutputParams const & runparams,
1981 OutputWhat output) const
1983 LaTeXFeatures features(*this, params(), runparams);
1985 d->bibinfo_.makeCitationLabels(*this);
1987 bool const output_preamble =
1988 output == FullSource || output == OnlyPreamble;
1989 bool const output_body =
1990 output == FullSource || output == OnlyBody || output == IncludedFile;
1992 if (output_preamble) {
1993 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1994 << "<!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"
1995 // FIXME Language should be set properly.
1996 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
1998 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
1999 // FIXME Presumably need to set this right
2000 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
2002 docstring const & doctitle = features.htmlTitle();
2004 << (doctitle.empty() ?
2005 from_ascii("LyX Document") :
2006 html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
2009 docstring styles = features.getTClassHTMLPreamble();
2010 if (!styles.empty())
2011 os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
2013 styles = from_utf8(features.getPreambleSnippets());
2014 if (!styles.empty())
2015 os << "\n<!-- Preamble Snippets -->\n" << styles << '\n';
2017 // we will collect CSS information in a stream, and then output it
2018 // either here, as part of the header, or else in a separate file.
2019 odocstringstream css;
2020 styles = from_utf8(features.getCSSSnippets());
2021 if (!styles.empty())
2022 css << "/* LyX Provided Styles */\n" << styles << '\n';
2024 styles = features.getTClassHTMLStyles();
2025 if (!styles.empty())
2026 css << "/* Layout-provided Styles */\n" << styles << '\n';
2028 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
2029 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
2030 if (needfg || needbg) {
2031 css << "\nbody {\n";
2034 << from_ascii(X11hexname(params().fontcolor))
2037 css << " background-color: "
2038 << from_ascii(X11hexname(params().backgroundcolor))
2043 docstring const dstyles = css.str();
2044 if (!dstyles.empty()) {
2045 bool written = false;
2046 if (params().html_css_as_file) {
2047 // open a file for CSS info
2049 string const fcssname = addName(temppath(), "docstyle.css");
2050 FileName const fcssfile = FileName(fcssname);
2051 if (openFileWrite(ocss, fcssfile)) {
2055 // write link to header
2056 os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
2058 runparams.exportdata->addExternalFile("xhtml", fcssfile);
2061 // we are here if the CSS is supposed to be written to the header
2062 // or if we failed to write it to an external file.
2064 os << "<style type='text/css'>\n"
2073 bool const output_body_tag = (output != IncludedFile);
2074 if (output_body_tag)
2077 if (output != IncludedFile)
2078 // if we're an included file, the counters are in the master.
2079 params().documentClass().counters().reset();
2080 xhtmlParagraphs(text(), *this, xs, runparams);
2081 if (output_body_tag)
2085 if (output_preamble)
2090 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
2091 // Other flags: -wall -v0 -x
2092 int Buffer::runChktex()
2096 // get LaTeX-Filename
2097 FileName const path(temppath());
2098 string const name = addName(path.absFileName(), latexName());
2099 string const org_path = filePath();
2101 PathChanger p(path); // path to LaTeX file
2102 message(_("Running chktex..."));
2104 // Generate the LaTeX file if neccessary
2105 OutputParams runparams(¶ms().encoding());
2106 runparams.flavor = OutputParams::LATEX;
2107 runparams.nice = false;
2108 runparams.linelen = lyxrc.plaintext_linelen;
2109 makeLaTeXFile(FileName(name), org_path, runparams);
2112 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
2113 int const res = chktex.run(terr); // run chktex
2116 Alert::error(_("chktex failure"),
2117 _("Could not run chktex successfully."));
2119 ErrorList & errlist = d->errorLists["ChkTeX"];
2121 bufferErrors(terr, errlist);
2126 if (runparams.silent)
2127 d->errorLists["ChkTeX"].clear();
2135 void Buffer::validate(LaTeXFeatures & features) const
2137 // Validate the buffer params, but not for included
2138 // files, since they also use the parent buffer's
2140 if (!features.runparams().is_child)
2141 params().validate(features);
2143 for_each(paragraphs().begin(), paragraphs().end(),
2144 bind(&Paragraph::validate, _1, ref(features)));
2146 if (lyxerr.debugging(Debug::LATEX)) {
2147 features.showStruct();
2152 void Buffer::getLabelList(vector<docstring> & list) const
2154 // If this is a child document, use the master's list instead.
2156 masterBuffer()->getLabelList(list);
2161 shared_ptr<Toc> toc = d->toc_backend.toc("label");
2162 TocIterator toc_it = toc->begin();
2163 TocIterator end = toc->end();
2164 for (; toc_it != end; ++toc_it) {
2165 if (toc_it->depth() == 0)
2166 list.push_back(toc_it->str());
2171 void Buffer::updateBibfilesCache(UpdateScope scope) const
2173 // FIXME This is probably unnecssary, given where we call this.
2174 // If this is a child document, use the parent's cache instead.
2175 if (parent() && scope != UpdateChildOnly) {
2176 masterBuffer()->updateBibfilesCache();
2180 d->bibfiles_cache_.clear();
2181 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2182 if (it->lyxCode() == BIBTEX_CODE) {
2183 InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
2184 support::FileNameList const bibfiles = inset.getBibFiles();
2185 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2188 } else if (it->lyxCode() == INCLUDE_CODE) {
2189 InsetInclude & inset = static_cast<InsetInclude &>(*it);
2190 Buffer const * const incbuf = inset.getChildBuffer();
2193 support::FileNameList const & bibfiles =
2194 incbuf->getBibfilesCache(UpdateChildOnly);
2195 if (!bibfiles.empty()) {
2196 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2202 d->bibfile_cache_valid_ = true;
2203 d->bibinfo_cache_valid_ = false;
2204 d->cite_labels_valid_ = false;
2208 void Buffer::invalidateBibinfoCache() const
2210 d->bibinfo_cache_valid_ = false;
2211 d->cite_labels_valid_ = false;
2212 // also invalidate the cache for the parent buffer
2213 Buffer const * const pbuf = d->parent();
2215 pbuf->invalidateBibinfoCache();
2219 void Buffer::invalidateBibfileCache() const
2221 d->bibfile_cache_valid_ = false;
2222 d->bibinfo_cache_valid_ = false;
2223 d->cite_labels_valid_ = false;
2224 // also invalidate the cache for the parent buffer
2225 Buffer const * const pbuf = d->parent();
2227 pbuf->invalidateBibfileCache();
2231 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
2233 // FIXME This is probably unnecessary, given where we call this.
2234 // If this is a child document, use the master's cache instead.
2235 Buffer const * const pbuf = masterBuffer();
2236 if (pbuf != this && scope != UpdateChildOnly)
2237 return pbuf->getBibfilesCache();
2239 if (!d->bibfile_cache_valid_)
2240 this->updateBibfilesCache(scope);
2242 return d->bibfiles_cache_;
2246 BiblioInfo const & Buffer::masterBibInfo() const
2248 Buffer const * const tmp = masterBuffer();
2250 return tmp->masterBibInfo();
2255 void Buffer::checkIfBibInfoCacheIsValid() const
2257 // use the master's cache
2258 Buffer const * const tmp = masterBuffer();
2260 tmp->checkIfBibInfoCacheIsValid();
2264 // compare the cached timestamps with the actual ones.
2265 FileNameList const & bibfiles_cache = getBibfilesCache();
2266 FileNameList::const_iterator ei = bibfiles_cache.begin();
2267 FileNameList::const_iterator en = bibfiles_cache.end();
2268 for (; ei != en; ++ ei) {
2269 time_t lastw = ei->lastModified();
2270 time_t prevw = d->bibfile_status_[*ei];
2271 if (lastw != prevw) {
2272 d->bibinfo_cache_valid_ = false;
2273 d->cite_labels_valid_ = false;
2274 d->bibfile_status_[*ei] = lastw;
2280 void Buffer::reloadBibInfoCache() const
2282 // use the master's cache
2283 Buffer const * const tmp = masterBuffer();
2285 tmp->reloadBibInfoCache();
2289 checkIfBibInfoCacheIsValid();
2290 if (d->bibinfo_cache_valid_)
2293 d->bibinfo_.clear();
2295 d->bibinfo_cache_valid_ = true;
2299 void Buffer::collectBibKeys() const
2301 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2302 it->collectBibKeys(it);
2306 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
2308 Buffer const * tmp = masterBuffer();
2309 BiblioInfo & masterbi = (tmp == this) ?
2310 d->bibinfo_ : tmp->d->bibinfo_;
2311 masterbi.mergeBiblioInfo(bi);
2315 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
2317 Buffer const * tmp = masterBuffer();
2318 BiblioInfo & masterbi = (tmp == this) ?
2319 d->bibinfo_ : tmp->d->bibinfo_;
2324 void Buffer::makeCitationLabels() const
2326 Buffer const * const master = masterBuffer();
2327 return d->bibinfo_.makeCitationLabels(*master);
2331 bool Buffer::citeLabelsValid() const
2333 return masterBuffer()->d->cite_labels_valid_;
2337 void Buffer::removeBiblioTempFiles() const
2339 // We remove files that contain LaTeX commands specific to the
2340 // particular bibliographic style being used, in order to avoid
2341 // LaTeX errors when we switch style.
2342 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2343 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2344 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2345 aux_file.removeFile();
2346 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2347 bbl_file.removeFile();
2348 // Also for the parent buffer
2349 Buffer const * const pbuf = parent();
2351 pbuf->removeBiblioTempFiles();
2355 bool Buffer::isDepClean(string const & name) const
2357 DepClean::const_iterator const it = d->dep_clean.find(name);
2358 if (it == d->dep_clean.end())
2364 void Buffer::markDepClean(string const & name)
2366 d->dep_clean[name] = true;
2370 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2373 // FIXME? if there is an Buffer LFUN that can be dispatched even
2374 // if internal, put a switch '(cmd.action)' here.
2380 switch (cmd.action()) {
2382 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2383 flag.setOnOff(isReadonly());
2386 // FIXME: There is need for a command-line import.
2387 //case LFUN_BUFFER_IMPORT:
2389 case LFUN_BUFFER_AUTO_SAVE:
2392 case LFUN_BUFFER_EXPORT_CUSTOM:
2393 // FIXME: Nothing to check here?
2396 case LFUN_BUFFER_EXPORT: {
2397 docstring const arg = cmd.argument();
2398 if (arg == "custom") {
2402 string format = to_utf8(arg);
2403 size_t pos = format.find(' ');
2404 if (pos != string::npos)
2405 format = format.substr(0, pos);
2406 enable = params().isExportable(format);
2408 flag.message(bformat(
2409 _("Don't know how to export to format: %1$s"), arg));
2413 case LFUN_BUFFER_CHKTEX:
2414 enable = params().isLatex() && !lyxrc.chktex_command.empty();
2417 case LFUN_BUILD_PROGRAM:
2418 enable = params().isExportable("program");
2421 case LFUN_BRANCH_ACTIVATE:
2422 case LFUN_BRANCH_DEACTIVATE:
2423 case LFUN_BRANCH_MASTER_ACTIVATE:
2424 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2425 bool const master = (cmd.action() == LFUN_BRANCH_MASTER_ACTIVATE
2426 || cmd.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2427 BranchList const & branchList = master ? masterBuffer()->params().branchlist()
2428 : params().branchlist();
2429 docstring const branchName = cmd.argument();
2430 flag.setEnabled(!branchName.empty() && branchList.find(branchName));
2434 case LFUN_BRANCH_ADD:
2435 case LFUN_BRANCHES_RENAME:
2436 // if no Buffer is present, then of course we won't be called!
2439 case LFUN_BUFFER_LANGUAGE:
2440 enable = !isReadonly();
2443 case LFUN_BUFFER_VIEW_CACHE:
2444 (d->preview_file_).refresh();
2445 enable = (d->preview_file_).exists() && !(d->preview_file_).isFileEmpty();
2448 case LFUN_CHANGES_TRACK:
2449 flag.setEnabled(true);
2450 flag.setOnOff(params().track_changes);
2453 case LFUN_CHANGES_OUTPUT:
2454 flag.setEnabled(true);
2455 flag.setOnOff(params().output_changes);
2458 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
2459 flag.setOnOff(params().compressed);
2463 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC: {
2464 flag.setOnOff(params().output_sync);
2471 flag.setEnabled(enable);
2476 void Buffer::dispatch(string const & command, DispatchResult & result)
2478 return dispatch(lyxaction.lookupFunc(command), result);
2482 // NOTE We can end up here even if we have no GUI, because we are called
2483 // by LyX::exec to handled command-line requests. So we may need to check
2484 // whether we have a GUI or not. The boolean use_gui holds this information.
2485 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2488 // FIXME? if there is an Buffer LFUN that can be dispatched even
2489 // if internal, put a switch '(cmd.action())' here.
2490 dr.dispatched(false);
2493 string const argument = to_utf8(func.argument());
2494 // We'll set this back to false if need be.
2495 bool dispatched = true;
2496 undo().beginUndoGroup();
2498 switch (func.action()) {
2499 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2500 if (lyxvc().inUse()) {
2501 string log = lyxvc().toggleReadOnly();
2506 setReadonly(!isReadonly());
2509 case LFUN_BUFFER_EXPORT: {
2510 ExportStatus const status = doExport(argument, false);
2511 dr.setError(status != ExportSuccess);
2512 if (status != ExportSuccess)
2513 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2518 case LFUN_BUILD_PROGRAM: {
2519 ExportStatus const status = doExport("program", true);
2520 dr.setError(status != ExportSuccess);
2521 if (status != ExportSuccess)
2522 dr.setMessage(_("Error generating literate programming code."));
2526 case LFUN_BUFFER_CHKTEX:
2530 case LFUN_BUFFER_EXPORT_CUSTOM: {
2532 string command = split(argument, format_name, ' ');
2533 Format const * format = formats.getFormat(format_name);
2535 lyxerr << "Format \"" << format_name
2536 << "\" not recognized!"
2541 // The name of the file created by the conversion process
2544 // Output to filename
2545 if (format->name() == "lyx") {
2546 string const latexname = latexName(false);
2547 filename = changeExtension(latexname,
2548 format->extension());
2549 filename = addName(temppath(), filename);
2551 if (!writeFile(FileName(filename)))
2555 doExport(format_name, true, filename);
2558 // Substitute $$FName for filename
2559 if (!contains(command, "$$FName"))
2560 command = "( " + command + " ) < $$FName";
2561 command = subst(command, "$$FName", filename);
2563 // Execute the command in the background
2565 call.startscript(Systemcall::DontWait, command,
2566 filePath(), layoutPos());
2570 // FIXME: There is need for a command-line import.
2572 case LFUN_BUFFER_IMPORT:
2577 case LFUN_BUFFER_AUTO_SAVE:
2579 resetAutosaveTimers();
2582 case LFUN_BRANCH_ACTIVATE:
2583 case LFUN_BRANCH_DEACTIVATE:
2584 case LFUN_BRANCH_MASTER_ACTIVATE:
2585 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2586 bool const master = (func.action() == LFUN_BRANCH_MASTER_ACTIVATE
2587 || func.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2588 Buffer * buf = master ? const_cast<Buffer *>(masterBuffer())
2591 docstring const branch_name = func.argument();
2592 // the case without a branch name is handled elsewhere
2593 if (branch_name.empty()) {
2597 Branch * branch = buf->params().branchlist().find(branch_name);
2599 LYXERR0("Branch " << branch_name << " does not exist.");
2601 docstring const msg =
2602 bformat(_("Branch \"%1$s\" does not exist."), branch_name);
2606 bool const activate = (func.action() == LFUN_BRANCH_ACTIVATE
2607 || func.action() == LFUN_BRANCH_MASTER_ACTIVATE);
2608 if (branch->isSelected() != activate) {
2609 buf->undo().recordUndoBufferParams(CursorData());
2610 branch->setSelected(activate);
2612 dr.screenUpdate(Update::Force);
2613 dr.forceBufferUpdate();
2618 case LFUN_BRANCH_ADD: {
2619 docstring branch_name = func.argument();
2620 if (branch_name.empty()) {
2624 BranchList & branch_list = params().branchlist();
2625 vector<docstring> const branches =
2626 getVectorFromString(branch_name, branch_list.separator());
2628 for (vector<docstring>::const_iterator it = branches.begin();
2629 it != branches.end(); ++it) {
2631 Branch * branch = branch_list.find(branch_name);
2633 LYXERR0("Branch " << branch_name << " already exists.");
2637 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2639 undo().recordUndoBufferParams(CursorData());
2640 branch_list.add(branch_name);
2641 branch = branch_list.find(branch_name);
2642 string const x11hexname = X11hexname(branch->color());
2643 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2644 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2646 dr.screenUpdate(Update::Force);
2654 case LFUN_BRANCHES_RENAME: {
2655 if (func.argument().empty())
2658 docstring const oldname = from_utf8(func.getArg(0));
2659 docstring const newname = from_utf8(func.getArg(1));
2660 InsetIterator it = inset_iterator_begin(inset());
2661 InsetIterator const end = inset_iterator_end(inset());
2662 bool success = false;
2663 for (; it != end; ++it) {
2664 if (it->lyxCode() == BRANCH_CODE) {
2665 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2666 if (ins.branch() == oldname) {
2667 undo().recordUndo(CursorData(it));
2668 ins.rename(newname);
2673 if (it->lyxCode() == INCLUDE_CODE) {
2674 // get buffer of external file
2675 InsetInclude const & ins =
2676 static_cast<InsetInclude const &>(*it);
2677 Buffer * child = ins.getChildBuffer();
2680 child->dispatch(func, dr);
2685 dr.screenUpdate(Update::Force);
2686 dr.forceBufferUpdate();
2691 case LFUN_BUFFER_VIEW_CACHE:
2692 if (!formats.view(*this, d->preview_file_,
2693 d->preview_format_))
2694 dr.setMessage(_("Error viewing the output file."));
2697 case LFUN_CHANGES_TRACK:
2698 undo().recordUndoBufferParams(CursorData());
2699 params().track_changes = !params().track_changes;
2702 case LFUN_CHANGES_OUTPUT:
2703 undo().recordUndoBufferParams(CursorData());
2704 params().output_changes = !params().output_changes;
2705 if (params().output_changes) {
2706 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
2707 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
2708 LaTeXFeatures::isAvailable("xcolor");
2710 if (!dvipost && !xcolorulem) {
2711 Alert::warning(_("Changes not shown in LaTeX output"),
2712 _("Changes will not be highlighted in LaTeX output, "
2713 "because neither dvipost nor xcolor/ulem are installed.\n"
2714 "Please install these packages or redefine "
2715 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
2716 } else if (!xcolorulem) {
2717 Alert::warning(_("Changes not shown in LaTeX output"),
2718 _("Changes will not be highlighted in LaTeX output "
2719 "when using pdflatex, because xcolor and ulem are not installed.\n"
2720 "Please install both packages or redefine "
2721 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
2726 case LFUN_BUFFER_TOGGLE_COMPRESSION:
2727 // turn compression on/off
2728 undo().recordUndoBufferParams(CursorData());
2729 params().compressed = !params().compressed;
2732 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
2733 undo().recordUndoBufferParams(CursorData());
2734 params().output_sync = !params().output_sync;
2741 dr.dispatched(dispatched);
2742 undo().endUndoGroup();
2746 void Buffer::changeLanguage(Language const * from, Language const * to)
2748 LASSERT(from, return);
2749 LASSERT(to, return);
2751 for_each(par_iterator_begin(),
2753 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2757 bool Buffer::isMultiLingual() const
2759 ParConstIterator end = par_iterator_end();
2760 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2761 if (it->isMultiLingual(params()))
2768 std::set<Language const *> Buffer::getLanguages() const
2770 std::set<Language const *> languages;
2771 getLanguages(languages);
2776 void Buffer::getLanguages(std::set<Language const *> & languages) const
2778 ParConstIterator end = par_iterator_end();
2779 // add the buffer language, even if it's not actively used
2780 languages.insert(language());
2781 // iterate over the paragraphs
2782 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2783 it->getLanguages(languages);
2785 ListOfBuffers clist = getDescendents();
2786 ListOfBuffers::const_iterator cit = clist.begin();
2787 ListOfBuffers::const_iterator const cen = clist.end();
2788 for (; cit != cen; ++cit)
2789 (*cit)->getLanguages(languages);
2793 DocIterator Buffer::getParFromID(int const id) const
2795 Buffer * buf = const_cast<Buffer *>(this);
2797 // John says this is called with id == -1 from undo
2798 lyxerr << "getParFromID(), id: " << id << endl;
2799 return doc_iterator_end(buf);
2802 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2803 if (it.paragraph().id() == id)
2806 return doc_iterator_end(buf);
2810 bool Buffer::hasParWithID(int const id) const
2812 return !getParFromID(id).atEnd();
2816 ParIterator Buffer::par_iterator_begin()
2818 return ParIterator(doc_iterator_begin(this));
2822 ParIterator Buffer::par_iterator_end()
2824 return ParIterator(doc_iterator_end(this));
2828 ParConstIterator Buffer::par_iterator_begin() const
2830 return ParConstIterator(doc_iterator_begin(this));
2834 ParConstIterator Buffer::par_iterator_end() const
2836 return ParConstIterator(doc_iterator_end(this));
2840 Language const * Buffer::language() const
2842 return params().language;
2846 docstring const Buffer::B_(string const & l10n) const
2848 return params().B_(l10n);
2852 bool Buffer::isClean() const
2854 return d->lyx_clean;
2858 bool Buffer::isExternallyModified(CheckMethod method) const
2860 LASSERT(d->filename.exists(), return false);
2861 // if method == timestamp, check timestamp before checksum
2862 return (method == checksum_method
2863 || d->timestamp_ != d->filename.lastModified())
2864 && d->checksum_ != d->filename.checksum();
2868 void Buffer::saveCheckSum() const
2870 FileName const & file = d->filename;
2873 if (file.exists()) {
2874 d->timestamp_ = file.lastModified();
2875 d->checksum_ = file.checksum();
2877 // in the case of save to a new file.
2884 void Buffer::markClean() const
2886 if (!d->lyx_clean) {
2887 d->lyx_clean = true;
2890 // if the .lyx file has been saved, we don't need an
2892 d->bak_clean = true;
2893 d->undo_.markDirty();
2897 void Buffer::setUnnamed(bool flag)
2903 bool Buffer::isUnnamed() const
2910 /// Don't check unnamed, here: isInternal() is used in
2911 /// newBuffer(), where the unnamed flag has not been set by anyone
2912 /// yet. Also, for an internal buffer, there should be no need for
2913 /// retrieving fileName() nor for checking if it is unnamed or not.
2914 bool Buffer::isInternal() const
2916 return d->internal_buffer;
2920 void Buffer::setInternal(bool flag)
2922 d->internal_buffer = flag;
2926 void Buffer::markDirty()
2929 d->lyx_clean = false;
2932 d->bak_clean = false;
2934 DepClean::iterator it = d->dep_clean.begin();
2935 DepClean::const_iterator const end = d->dep_clean.end();
2937 for (; it != end; ++it)
2942 FileName Buffer::fileName() const
2948 string Buffer::absFileName() const
2950 return d->filename.absFileName();
2954 string Buffer::filePath() const
2956 string const abs = d->filename.onlyPath().absFileName();
2959 int last = abs.length() - 1;
2961 return abs[last] == '/' ? abs : abs + '/';
2965 string Buffer::originFilePath() const
2967 if (FileName::isAbsolute(params().origin))
2968 return params().origin;
2974 string Buffer::layoutPos() const
2976 return d->layout_position;
2980 void Buffer::setLayoutPos(string const & path)
2983 d->layout_position.clear();
2987 LATTEST(FileName::isAbsolute(path));
2989 d->layout_position =
2990 to_utf8(makeRelPath(from_utf8(path), from_utf8(filePath())));
2992 if (d->layout_position.empty())
2993 d->layout_position = ".";
2997 bool Buffer::isReadonly() const
2999 return d->read_only;
3003 void Buffer::setParent(Buffer const * buffer)
3005 // Avoids recursive include.
3006 d->setParent(buffer == this ? 0 : buffer);
3011 Buffer const * Buffer::parent() const
3017 ListOfBuffers Buffer::allRelatives() const
3019 ListOfBuffers lb = masterBuffer()->getDescendents();
3020 lb.push_front(const_cast<Buffer *>(masterBuffer()));
3025 Buffer const * Buffer::masterBuffer() const
3027 // FIXME Should be make sure we are not in some kind
3028 // of recursive include? A -> B -> A will crash this.
3029 Buffer const * const pbuf = d->parent();
3033 return pbuf->masterBuffer();
3037 bool Buffer::isChild(Buffer * child) const
3039 return d->children_positions.find(child) != d->children_positions.end();
3043 DocIterator Buffer::firstChildPosition(Buffer const * child)
3045 Impl::BufferPositionMap::iterator it;
3046 it = d->children_positions.find(child);
3047 if (it == d->children_positions.end())
3048 return DocIterator(this);
3053 bool Buffer::hasChildren() const
3055 return !d->children_positions.empty();
3059 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
3061 // loop over children
3062 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3063 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3064 for (; it != end; ++it) {
3065 Buffer * child = const_cast<Buffer *>(it->first);
3067 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
3068 if (bit != clist.end())
3070 clist.push_back(child);
3072 // there might be grandchildren
3073 child->collectChildren(clist, true);
3078 ListOfBuffers Buffer::getChildren() const
3081 collectChildren(v, false);
3082 // Make sure we have not included ourselves.
3083 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3084 if (bit != v.end()) {
3085 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3092 ListOfBuffers Buffer::getDescendents() const
3095 collectChildren(v, true);
3096 // Make sure we have not included ourselves.
3097 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3098 if (bit != v.end()) {
3099 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3106 template<typename M>
3107 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
3112 typename M::const_iterator it = m.lower_bound(x);
3113 if (it == m.begin())
3121 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
3122 DocIterator const & pos) const
3124 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
3126 // if paragraphs have no macro context set, pos will be empty
3130 // we haven't found anything yet
3131 DocIterator bestPos = owner_->par_iterator_begin();
3132 MacroData const * bestData = 0;
3134 // find macro definitions for name
3135 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
3136 if (nameIt != macros.end()) {
3137 // find last definition in front of pos or at pos itself
3138 PositionScopeMacroMap::const_iterator it
3139 = greatest_below(nameIt->second, pos);
3140 if (it != nameIt->second.end()) {
3142 // scope ends behind pos?
3143 if (pos < it->second.scope) {
3144 // Looks good, remember this. If there
3145 // is no external macro behind this,
3146 // we found the right one already.
3147 bestPos = it->first;
3148 bestData = &it->second.macro;
3152 // try previous macro if there is one
3153 if (it == nameIt->second.begin())
3160 // find macros in included files
3161 PositionScopeBufferMap::const_iterator it
3162 = greatest_below(position_to_children, pos);
3163 if (it == position_to_children.end())
3164 // no children before
3168 // do we know something better (i.e. later) already?
3169 if (it->first < bestPos )
3172 // scope ends behind pos?
3173 if (pos < it->second.scope
3174 && (cloned_buffer_ ||
3175 theBufferList().isLoaded(it->second.buffer))) {
3176 // look for macro in external file
3178 MacroData const * data
3179 = it->second.buffer->getMacro(name, false);
3182 bestPos = it->first;
3188 // try previous file if there is one
3189 if (it == position_to_children.begin())
3194 // return the best macro we have found
3199 MacroData const * Buffer::getMacro(docstring const & name,
3200 DocIterator const & pos, bool global) const
3205 // query buffer macros
3206 MacroData const * data = d->getBufferMacro(name, pos);
3210 // If there is a master buffer, query that
3211 Buffer const * const pbuf = d->parent();
3213 d->macro_lock = true;
3214 MacroData const * macro = pbuf->getMacro(
3215 name, *this, false);
3216 d->macro_lock = false;
3222 data = MacroTable::globalMacros().get(name);
3231 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3233 // set scope end behind the last paragraph
3234 DocIterator scope = par_iterator_begin();
3235 scope.pit() = scope.lastpit() + 1;
3237 return getMacro(name, scope, global);
3241 MacroData const * Buffer::getMacro(docstring const & name,
3242 Buffer const & child, bool global) const
3244 // look where the child buffer is included first
3245 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3246 if (it == d->children_positions.end())
3249 // check for macros at the inclusion position
3250 return getMacro(name, it->second, global);
3254 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3256 pit_type const lastpit = it.lastpit();
3258 // look for macros in each paragraph
3259 while (it.pit() <= lastpit) {
3260 Paragraph & par = it.paragraph();
3262 // iterate over the insets of the current paragraph
3263 InsetList const & insets = par.insetList();
3264 InsetList::const_iterator iit = insets.begin();
3265 InsetList::const_iterator end = insets.end();
3266 for (; iit != end; ++iit) {
3267 it.pos() = iit->pos;
3269 // is it a nested text inset?
3270 if (iit->inset->asInsetText()) {
3271 // Inset needs its own scope?
3272 InsetText const * itext = iit->inset->asInsetText();
3273 bool newScope = itext->isMacroScope();
3275 // scope which ends just behind the inset
3276 DocIterator insetScope = it;
3279 // collect macros in inset
3280 it.push_back(CursorSlice(*iit->inset));
3281 updateMacros(it, newScope ? insetScope : scope);
3286 if (iit->inset->asInsetTabular()) {
3287 CursorSlice slice(*iit->inset);
3288 size_t const numcells = slice.nargs();
3289 for (; slice.idx() < numcells; slice.forwardIdx()) {
3290 it.push_back(slice);
3291 updateMacros(it, scope);
3297 // is it an external file?
3298 if (iit->inset->lyxCode() == INCLUDE_CODE) {
3299 // get buffer of external file
3300 InsetInclude const & inset =
3301 static_cast<InsetInclude const &>(*iit->inset);
3303 Buffer * child = inset.getChildBuffer();
3308 // register its position, but only when it is
3309 // included first in the buffer
3310 if (children_positions.find(child) ==
3311 children_positions.end())
3312 children_positions[child] = it;
3314 // register child with its scope
3315 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3319 InsetMath * im = iit->inset->asInsetMath();
3320 if (doing_export && im) {
3321 InsetMathHull * hull = im->asHullInset();
3323 hull->recordLocation(it);
3326 if (iit->inset->lyxCode() != MATHMACRO_CODE)
3330 MathMacroTemplate & macroTemplate =
3331 *iit->inset->asInsetMath()->asMacroTemplate();
3332 MacroContext mc(owner_, it);
3333 macroTemplate.updateToContext(mc);
3336 bool valid = macroTemplate.validMacro();
3337 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3338 // then the BufferView's cursor will be invalid in
3339 // some cases which leads to crashes.
3344 // FIXME (Abdel), I don't understand why we pass 'it' here
3345 // instead of 'macroTemplate' defined above... is this correct?
3346 macros[macroTemplate.name()][it] =
3347 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3357 void Buffer::updateMacros() const
3362 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3364 // start with empty table
3366 d->children_positions.clear();
3367 d->position_to_children.clear();
3369 // Iterate over buffer, starting with first paragraph
3370 // The scope must be bigger than any lookup DocIterator
3371 // later. For the global lookup, lastpit+1 is used, hence
3372 // we use lastpit+2 here.
3373 DocIterator it = par_iterator_begin();
3374 DocIterator outerScope = it;
3375 outerScope.pit() = outerScope.lastpit() + 2;
3376 d->updateMacros(it, outerScope);
3380 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3382 InsetIterator it = inset_iterator_begin(inset());
3383 InsetIterator const end = inset_iterator_end(inset());
3384 for (; it != end; ++it) {
3385 if (it->lyxCode() == BRANCH_CODE) {
3386 InsetBranch & br = static_cast<InsetBranch &>(*it);
3387 docstring const name = br.branch();
3388 if (!from_master && !params().branchlist().find(name))
3389 result.push_back(name);
3390 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3391 result.push_back(name);
3394 if (it->lyxCode() == INCLUDE_CODE) {
3395 // get buffer of external file
3396 InsetInclude const & ins =
3397 static_cast<InsetInclude const &>(*it);
3398 Buffer * child = ins.getChildBuffer();
3401 child->getUsedBranches(result, true);
3404 // remove duplicates
3409 void Buffer::updateMacroInstances(UpdateType utype) const
3411 LYXERR(Debug::MACROS, "updateMacroInstances for "
3412 << d->filename.onlyFileName());
3413 DocIterator it = doc_iterator_begin(this);
3415 DocIterator const end = doc_iterator_end(this);
3416 for (; it != end; it.forwardInset()) {
3417 // look for MathData cells in InsetMathNest insets
3418 InsetMath * minset = it.nextInset()->asInsetMath();
3422 // update macro in all cells of the InsetMathNest
3423 DocIterator::idx_type n = minset->nargs();
3424 MacroContext mc = MacroContext(this, it);
3425 for (DocIterator::idx_type i = 0; i < n; ++i) {
3426 MathData & data = minset->cell(i);
3427 data.updateMacros(0, mc, utype);
3433 void Buffer::listMacroNames(MacroNameSet & macros) const
3438 d->macro_lock = true;
3440 // loop over macro names
3441 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3442 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3443 for (; nameIt != nameEnd; ++nameIt)
3444 macros.insert(nameIt->first);
3446 // loop over children
3447 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3448 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3449 for (; it != end; ++it)
3450 it->first->listMacroNames(macros);
3453 Buffer const * const pbuf = d->parent();
3455 pbuf->listMacroNames(macros);
3457 d->macro_lock = false;
3461 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3463 Buffer const * const pbuf = d->parent();
3468 pbuf->listMacroNames(names);
3471 MacroNameSet::iterator it = names.begin();
3472 MacroNameSet::iterator end = names.end();
3473 for (; it != end; ++it) {
3475 MacroData const * data =
3476 pbuf->getMacro(*it, *this, false);
3478 macros.insert(data);
3480 // we cannot access the original MathMacroTemplate anymore
3481 // here to calls validate method. So we do its work here manually.
3482 // FIXME: somehow make the template accessible here.
3483 if (data->optionals() > 0)
3484 features.require("xargs");
3490 Buffer::References & Buffer::getReferenceCache(docstring const & label)
3493 return const_cast<Buffer *>(masterBuffer())->getReferenceCache(label);
3495 RefCache::iterator it = d->ref_cache_.find(label);
3496 if (it != d->ref_cache_.end())
3497 return it->second.second;
3499 static InsetLabel const * dummy_il = 0;
3500 static References const dummy_refs = References();
3501 it = d->ref_cache_.insert(
3502 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3503 return it->second.second;
3507 Buffer::References const & Buffer::references(docstring const & label) const
3509 return const_cast<Buffer *>(this)->getReferenceCache(label);
3513 void Buffer::addReference(docstring const & label, Inset * inset, ParIterator it)
3515 References & refs = getReferenceCache(label);
3516 refs.push_back(make_pair(inset, it));
3520 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3522 masterBuffer()->d->ref_cache_[label].first = il;
3526 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3528 return masterBuffer()->d->ref_cache_[label].first;
3532 void Buffer::clearReferenceCache() const
3535 d->ref_cache_.clear();
3539 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to)
3541 //FIXME: This does not work for child documents yet.
3542 reloadBibInfoCache();
3544 // Check if the label 'from' appears more than once
3545 BiblioInfo const & keys = masterBibInfo();
3546 BiblioInfo::const_iterator bit = keys.begin();
3547 BiblioInfo::const_iterator bend = keys.end();
3548 vector<docstring> labels;
3550 for (; bit != bend; ++bit)
3552 labels.push_back(bit->first);
3554 if (count(labels.begin(), labels.end(), from) > 1)
3557 string const paramName = "key";
3558 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3559 if (it->lyxCode() != CITE_CODE)
3561 InsetCommand * inset = it->asInsetCommand();
3562 docstring const oldValue = inset->getParam(paramName);
3563 if (oldValue == from)
3564 inset->setParam(paramName, to);
3568 // returns NULL if id-to-row conversion is unsupported
3569 auto_ptr<TexRow> Buffer::getSourceCode(odocstream & os, string const & format,
3570 pit_type par_begin, pit_type par_end,
3571 OutputWhat output, bool master) const
3573 auto_ptr<TexRow> texrow(NULL);
3574 OutputParams runparams(¶ms().encoding());
3575 runparams.nice = true;
3576 runparams.flavor = params().getOutputFlavor(format);
3577 runparams.linelen = lyxrc.plaintext_linelen;
3578 // No side effect of file copying and image conversion
3579 runparams.dryrun = true;
3581 if (output == CurrentParagraph) {
3582 runparams.par_begin = par_begin;
3583 runparams.par_end = par_end;
3584 if (par_begin + 1 == par_end) {
3586 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3590 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3591 convert<docstring>(par_begin),
3592 convert<docstring>(par_end - 1))
3595 // output paragraphs
3596 if (runparams.flavor == OutputParams::LYX) {
3597 Paragraph const & par = text().paragraphs()[par_begin];
3599 depth_type dt = par.getDepth();
3600 par.write(ods, params(), dt);
3601 os << from_utf8(ods.str());
3602 } else if (runparams.flavor == OutputParams::HTML) {
3604 setMathFlavor(runparams);
3605 xhtmlParagraphs(text(), *this, xs, runparams);
3606 } else if (runparams.flavor == OutputParams::TEXT) {
3608 // FIXME Handles only one paragraph, unlike the others.
3609 // Probably should have some routine with a signature like them.
3610 writePlaintextParagraph(*this,
3611 text().paragraphs()[par_begin], os, runparams, dummy);
3612 } else if (params().isDocBook()) {
3613 docbookParagraphs(text(), *this, os, runparams);
3615 // If we are previewing a paragraph, even if this is the
3616 // child of some other buffer, let's cut the link here,
3617 // so that no concurring settings from the master
3618 // (e.g. branch state) interfere (see #8101).
3620 d->ignore_parent = true;
3621 // We need to validate the Buffer params' features here
3622 // in order to know if we should output polyglossia
3623 // macros (instead of babel macros)
3624 LaTeXFeatures features(*this, params(), runparams);
3625 params().validate(features);
3626 runparams.use_polyglossia = features.usePolyglossia();
3627 texrow.reset(new TexRow());
3630 // latex or literate
3631 otexstream ots(os, *texrow);
3634 latexParagraphs(*this, text(), ots, runparams);
3637 // Restore the parenthood
3639 d->ignore_parent = false;
3643 if (output == FullSource)
3644 os << _("Preview source code");
3645 else if (output == OnlyPreamble)
3646 os << _("Preview preamble");
3647 else if (output == OnlyBody)
3648 os << _("Preview body");
3650 if (runparams.flavor == OutputParams::LYX) {
3652 if (output == FullSource)
3654 else if (output == OnlyPreamble)
3655 params().writeFile(ods, this);
3656 else if (output == OnlyBody)
3658 os << from_utf8(ods.str());
3659 } else if (runparams.flavor == OutputParams::HTML) {
3660 writeLyXHTMLSource(os, runparams, output);
3661 } else if (runparams.flavor == OutputParams::TEXT) {
3662 if (output == OnlyPreamble) {
3663 os << "% "<< _("Plain text does not have a preamble.");
3665 writePlaintextFile(*this, os, runparams);
3666 } else if (params().isDocBook()) {
3667 writeDocBookSource(os, absFileName(), runparams, output);
3669 // latex or literate
3670 texrow.reset(new TexRow());
3673 otexstream ots(os, *texrow);
3675 runparams.is_child = true;
3676 writeLaTeXSource(ots, string(), runparams, output);
3684 ErrorList & Buffer::errorList(string const & type) const
3686 return d->errorLists[type];
3690 void Buffer::updateTocItem(std::string const & type,
3691 DocIterator const & dit) const
3694 d->gui_->updateTocItem(type, dit);
3698 void Buffer::structureChanged() const
3701 d->gui_->structureChanged();
3705 void Buffer::errors(string const & err, bool from_master) const
3708 d->gui_->errors(err, from_master);
3712 void Buffer::message(docstring const & msg) const
3715 d->gui_->message(msg);
3719 void Buffer::setBusy(bool on) const
3722 d->gui_->setBusy(on);
3726 void Buffer::updateTitles() const
3729 d->wa_->updateTitles();
3733 void Buffer::resetAutosaveTimers() const
3736 d->gui_->resetAutosaveTimers();
3740 bool Buffer::hasGuiDelegate() const
3746 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3755 class AutoSaveBuffer : public ForkedProcess {
3758 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3759 : buffer_(buffer), fname_(fname) {}
3761 virtual shared_ptr<ForkedProcess> clone() const
3763 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3768 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3769 from_utf8(fname_.absFileName())));
3770 return run(DontWait);
3774 virtual int generateChild();
3776 Buffer const & buffer_;
3781 int AutoSaveBuffer::generateChild()
3783 #if defined(__APPLE__)
3784 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3785 * We should use something else like threads.
3787 * Since I do not know how to determine at run time what is the OS X
3788 * version, I just disable forking altogether for now (JMarc)
3790 pid_t const pid = -1;
3792 // tmp_ret will be located (usually) in /tmp
3793 // will that be a problem?
3794 // Note that this calls ForkedCalls::fork(), so it's
3795 // ok cross-platform.
3796 pid_t const pid = fork();
3797 // If you want to debug the autosave
3798 // you should set pid to -1, and comment out the fork.
3799 if (pid != 0 && pid != -1)
3803 // pid = -1 signifies that lyx was unable
3804 // to fork. But we will do the save
3806 bool failed = false;
3807 TempFile tempfile("lyxautoXXXXXX.lyx");
3808 tempfile.setAutoRemove(false);
3809 FileName const tmp_ret = tempfile.name();
3810 if (!tmp_ret.empty()) {
3811 if (!buffer_.writeFile(tmp_ret))
3813 else if (!tmp_ret.moveTo(fname_))
3819 // failed to write/rename tmp_ret so try writing direct
3820 if (!buffer_.writeFile(fname_)) {
3821 // It is dangerous to do this in the child,
3822 // but safe in the parent, so...
3823 if (pid == -1) // emit message signal.
3824 buffer_.message(_("Autosave failed!"));
3828 if (pid == 0) // we are the child so...
3837 FileName Buffer::getEmergencyFileName() const
3839 return FileName(d->filename.absFileName() + ".emergency");
3843 FileName Buffer::getAutosaveFileName() const
3845 // if the document is unnamed try to save in the backup dir, else
3846 // in the default document path, and as a last try in the filePath,
3847 // which will most often be the temporary directory
3850 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3851 : lyxrc.backupdir_path;
3852 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3855 string const fname = "#" + d->filename.onlyFileName() + "#";
3857 return makeAbsPath(fname, fpath);
3861 void Buffer::removeAutosaveFile() const
3863 FileName const f = getAutosaveFileName();
3869 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3871 FileName const newauto = getAutosaveFileName();
3873 if (newauto != oldauto && oldauto.exists())
3874 if (!oldauto.moveTo(newauto))
3875 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3879 bool Buffer::autoSave() const
3881 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
3882 if (buf->d->bak_clean || isReadonly())
3885 message(_("Autosaving current document..."));
3886 buf->d->bak_clean = true;
3888 FileName const fname = getAutosaveFileName();
3889 LASSERT(d->cloned_buffer_, return false);
3891 // If this buffer is cloned, we assume that
3892 // we are running in a separate thread already.
3893 TempFile tempfile("lyxautoXXXXXX.lyx");
3894 tempfile.setAutoRemove(false);
3895 FileName const tmp_ret = tempfile.name();
3896 if (!tmp_ret.empty()) {
3898 // assume successful write of tmp_ret
3899 if (tmp_ret.moveTo(fname))
3902 // failed to write/rename tmp_ret so try writing direct
3903 return writeFile(fname);
3907 void Buffer::setExportStatus(bool e) const
3909 d->doing_export = e;
3910 ListOfBuffers clist = getDescendents();
3911 ListOfBuffers::const_iterator cit = clist.begin();
3912 ListOfBuffers::const_iterator const cen = clist.end();
3913 for (; cit != cen; ++cit)
3914 (*cit)->d->doing_export = e;
3918 bool Buffer::isExporting() const
3920 return d->doing_export;
3924 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
3928 return doExport(target, put_in_tempdir, result_file);
3931 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3932 string & result_file) const
3934 bool const update_unincluded =
3935 params().maintain_unincluded_children
3936 && !params().getIncludedChildren().empty();
3938 // (1) export with all included children (omit \includeonly)
3939 if (update_unincluded) {
3940 ExportStatus const status =
3941 doExport(target, put_in_tempdir, true, result_file);
3942 if (status != ExportSuccess)
3945 // (2) export with included children only
3946 return doExport(target, put_in_tempdir, false, result_file);
3950 void Buffer::setMathFlavor(OutputParams & op) const
3952 switch (params().html_math_output) {
3953 case BufferParams::MathML:
3954 op.math_flavor = OutputParams::MathAsMathML;
3956 case BufferParams::HTML:
3957 op.math_flavor = OutputParams::MathAsHTML;
3959 case BufferParams::Images:
3960 op.math_flavor = OutputParams::MathAsImages;
3962 case BufferParams::LaTeX:
3963 op.math_flavor = OutputParams::MathAsLaTeX;
3969 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3970 bool includeall, string & result_file) const
3972 LYXERR(Debug::FILES, "target=" << target);
3973 OutputParams runparams(¶ms().encoding());
3974 string format = target;
3975 string dest_filename;
3976 size_t pos = target.find(' ');
3977 if (pos != string::npos) {
3978 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
3979 format = target.substr(0, pos);
3980 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
3981 FileName(dest_filename).onlyPath().createPath();
3982 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
3984 MarkAsExporting exporting(this);
3985 string backend_format;
3986 runparams.flavor = OutputParams::LATEX;
3987 runparams.linelen = lyxrc.plaintext_linelen;
3988 runparams.includeall = includeall;
3989 vector<string> backs = params().backends();
3990 Converters converters = theConverters();
3991 bool need_nice_file = false;
3992 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3993 // Get shortest path to format
3994 converters.buildGraph();
3995 Graph::EdgePath path;
3996 for (vector<string>::const_iterator it = backs.begin();
3997 it != backs.end(); ++it) {
3998 Graph::EdgePath p = converters.getPath(*it, format);
3999 if (!p.empty() && (path.empty() || p.size() < path.size())) {
4000 backend_format = *it;
4005 if (!put_in_tempdir) {
4006 // Only show this alert if this is an export to a non-temporary
4007 // file (not for previewing).
4008 Alert::error(_("Couldn't export file"), bformat(
4009 _("No information for exporting the format %1$s."),
4010 formats.prettyName(format)));
4012 return ExportNoPathToFormat;
4014 runparams.flavor = converters.getFlavor(path, this);
4015 Graph::EdgePath::const_iterator it = path.begin();
4016 Graph::EdgePath::const_iterator en = path.end();
4017 for (; it != en; ++it)
4018 if (theConverters().get(*it).nice()) {
4019 need_nice_file = true;
4024 backend_format = format;
4025 LYXERR(Debug::FILES, "backend_format=" << backend_format);
4026 // FIXME: Don't hardcode format names here, but use a flag
4027 if (backend_format == "pdflatex")
4028 runparams.flavor = OutputParams::PDFLATEX;
4029 else if (backend_format == "luatex")
4030 runparams.flavor = OutputParams::LUATEX;
4031 else if (backend_format == "dviluatex")
4032 runparams.flavor = OutputParams::DVILUATEX;
4033 else if (backend_format == "xetex")
4034 runparams.flavor = OutputParams::XETEX;
4037 string filename = latexName(false);
4038 filename = addName(temppath(), filename);
4039 filename = changeExtension(filename,
4040 formats.extension(backend_format));
4041 LYXERR(Debug::FILES, "filename=" << filename);
4043 // Plain text backend
4044 if (backend_format == "text") {
4045 runparams.flavor = OutputParams::TEXT;
4046 writePlaintextFile(*this, FileName(filename), runparams);
4049 else if (backend_format == "xhtml") {
4050 runparams.flavor = OutputParams::HTML;
4051 setMathFlavor(runparams);
4052 makeLyXHTMLFile(FileName(filename), runparams);
4053 } else if (backend_format == "lyx")
4054 writeFile(FileName(filename));
4056 else if (params().isDocBook()) {
4057 runparams.nice = !put_in_tempdir;
4058 makeDocBookFile(FileName(filename), runparams);
4061 else if (backend_format == format || need_nice_file) {
4062 runparams.nice = true;
4063 bool const success = makeLaTeXFile(FileName(filename), string(), runparams);
4064 if (d->cloned_buffer_)
4065 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4068 } else if (!lyxrc.tex_allows_spaces
4069 && contains(filePath(), ' ')) {
4070 Alert::error(_("File name error"),
4071 _("The directory path to the document cannot contain spaces."));
4072 return ExportTexPathHasSpaces;
4074 runparams.nice = false;
4075 bool const success = makeLaTeXFile(
4076 FileName(filename), filePath(), runparams);
4077 if (d->cloned_buffer_)
4078 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4083 string const error_type = (format == "program")
4084 ? "Build" : params().bufferFormat();
4085 ErrorList & error_list = d->errorLists[error_type];
4086 string const ext = formats.extension(format);
4087 FileName const tmp_result_file(changeExtension(filename, ext));
4088 bool const success = converters.convert(this, FileName(filename),
4089 tmp_result_file, FileName(absFileName()), backend_format, format,
4092 // Emit the signal to show the error list or copy it back to the
4093 // cloned Buffer so that it can be emitted afterwards.
4094 if (format != backend_format) {
4095 if (runparams.silent)
4097 else if (d->cloned_buffer_)
4098 d->cloned_buffer_->d->errorLists[error_type] =
4099 d->errorLists[error_type];
4102 // also to the children, in case of master-buffer-view
4103 ListOfBuffers clist = getDescendents();
4104 ListOfBuffers::const_iterator cit = clist.begin();
4105 ListOfBuffers::const_iterator const cen = clist.end();
4106 for (; cit != cen; ++cit) {
4107 if (runparams.silent)
4108 (*cit)->d->errorLists[error_type].clear();
4109 else if (d->cloned_buffer_) {
4110 // Enable reverse search by copying back the
4111 // texrow object to the cloned buffer.
4112 // FIXME: this is not thread safe.
4113 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
4114 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
4115 (*cit)->d->errorLists[error_type];
4117 (*cit)->errors(error_type, true);
4121 if (d->cloned_buffer_) {
4122 // Enable reverse dvi or pdf to work by copying back the texrow
4123 // object to the cloned buffer.
4124 // FIXME: There is a possibility of concurrent access to texrow
4125 // here from the main GUI thread that should be securized.
4126 d->cloned_buffer_->d->texrow = d->texrow;
4127 string const error_type = params().bufferFormat();
4128 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
4132 if (put_in_tempdir) {
4133 result_file = tmp_result_file.absFileName();
4134 return success ? ExportSuccess : ExportConverterError;
4137 if (dest_filename.empty())
4138 result_file = changeExtension(d->exportFileName().absFileName(), ext);
4140 result_file = dest_filename;
4141 // We need to copy referenced files (e. g. included graphics
4142 // if format == "dvi") to the result dir.
4143 vector<ExportedFile> const files =
4144 runparams.exportdata->externalFiles(format);
4145 string const dest = runparams.export_folder.empty() ?
4146 onlyPath(result_file) : runparams.export_folder;
4147 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
4148 : force_overwrite == ALL_FILES;
4149 CopyStatus status = use_force ? FORCE : SUCCESS;
4151 vector<ExportedFile>::const_iterator it = files.begin();
4152 vector<ExportedFile>::const_iterator const en = files.end();
4153 for (; it != en && status != CANCEL; ++it) {
4154 string const fmt = formats.getFormatFromFile(it->sourceName);
4155 string fixedName = it->exportName;
4156 if (!runparams.export_folder.empty()) {
4157 // Relative pathnames starting with ../ will be sanitized
4158 // if exporting to a different folder
4159 while (fixedName.substr(0, 3) == "../")
4160 fixedName = fixedName.substr(3, fixedName.length() - 3);
4162 FileName fixedFileName = makeAbsPath(fixedName, dest);
4163 fixedFileName.onlyPath().createPath();
4164 status = copyFile(fmt, it->sourceName,
4166 it->exportName, status == FORCE,
4167 runparams.export_folder.empty());
4170 if (status == CANCEL) {
4171 message(_("Document export cancelled."));
4172 return ExportCancel;
4175 if (tmp_result_file.exists()) {
4176 // Finally copy the main file
4177 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
4178 : force_overwrite != NO_FILES;
4179 if (status == SUCCESS && use_force)
4181 status = copyFile(format, tmp_result_file,
4182 FileName(result_file), result_file,
4184 if (status == CANCEL) {
4185 message(_("Document export cancelled."));
4186 return ExportCancel;
4188 message(bformat(_("Document exported as %1$s "
4190 formats.prettyName(format),
4191 makeDisplayPath(result_file)));
4194 // This must be a dummy converter like fax (bug 1888)
4195 message(bformat(_("Document exported as %1$s"),
4196 formats.prettyName(format)));
4199 return success ? ExportSuccess : ExportConverterError;
4203 Buffer::ExportStatus Buffer::preview(string const & format) const
4205 bool const update_unincluded =
4206 params().maintain_unincluded_children
4207 && !params().getIncludedChildren().empty();
4208 return preview(format, update_unincluded);
4212 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4214 MarkAsExporting exporting(this);
4216 // (1) export with all included children (omit \includeonly)
4218 ExportStatus const status = doExport(format, true, true, result_file);
4219 if (status != ExportSuccess)
4222 // (2) export with included children only
4223 ExportStatus const status = doExport(format, true, false, result_file);
4224 FileName const previewFile(result_file);
4226 LATTEST (isClone());
4227 d->cloned_buffer_->d->preview_file_ = previewFile;
4228 d->cloned_buffer_->d->preview_format_ = format;
4229 d->cloned_buffer_->d->preview_error_ = (status != ExportSuccess);
4231 if (status != ExportSuccess)
4233 if (previewFile.exists()) {
4234 if (!formats.view(*this, previewFile, format))
4235 return PreviewError;
4237 return PreviewSuccess;
4240 // Successful export but no output file?
4241 // Probably a bug in error detection.
4242 LATTEST (status != ExportSuccess);
4249 Buffer::ReadStatus Buffer::extractFromVC()
4251 bool const found = LyXVC::file_not_found_hook(d->filename);
4253 return ReadFileNotFound;
4254 if (!d->filename.isReadableFile())
4260 Buffer::ReadStatus Buffer::loadEmergency()
4262 FileName const emergencyFile = getEmergencyFileName();
4263 if (!emergencyFile.exists()
4264 || emergencyFile.lastModified() <= d->filename.lastModified())
4265 return ReadFileNotFound;
4267 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4268 docstring const text = bformat(_("An emergency save of the document "
4269 "%1$s exists.\n\nRecover emergency save?"), file);
4271 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4272 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4278 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4279 bool const success = (ret_llf == ReadSuccess);
4282 Alert::warning(_("File is read-only"),
4283 bformat(_("An emergency file is successfully loaded, "
4284 "but the original file %1$s is marked read-only. "
4285 "Please make sure to save the document as a different "
4286 "file."), from_utf8(d->filename.absFileName())));
4289 lyxvc().file_found_hook(d->filename);
4290 str = _("Document was successfully recovered.");
4292 str = _("Document was NOT successfully recovered.");
4293 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4294 makeDisplayPath(emergencyFile.absFileName()));
4296 int const del_emerg =
4297 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4298 _("&Remove"), _("&Keep"));
4299 if (del_emerg == 0) {
4300 emergencyFile.removeFile();
4302 Alert::warning(_("Emergency file deleted"),
4303 _("Do not forget to save your file now!"), true);
4305 return success ? ReadSuccess : ReadEmergencyFailure;
4308 int const del_emerg =
4309 Alert::prompt(_("Delete emergency file?"),
4310 _("Remove emergency file now?"), 1, 1,
4311 _("&Remove"), _("&Keep"));
4313 emergencyFile.removeFile();
4314 return ReadOriginal;
4324 Buffer::ReadStatus Buffer::loadAutosave()
4326 // Now check if autosave file is newer.
4327 FileName const autosaveFile = getAutosaveFileName();
4328 if (!autosaveFile.exists()
4329 || autosaveFile.lastModified() <= d->filename.lastModified())
4330 return ReadFileNotFound;
4332 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4333 docstring const text = bformat(_("The backup of the document %1$s "
4334 "is newer.\n\nLoad the backup instead?"), file);
4335 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4336 _("&Load backup"), _("Load &original"), _("&Cancel"));
4341 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4342 // the file is not saved if we load the autosave file.
4343 if (ret_llf == ReadSuccess) {
4345 Alert::warning(_("File is read-only"),
4346 bformat(_("A backup file is successfully loaded, "
4347 "but the original file %1$s is marked read-only. "
4348 "Please make sure to save the document as a "
4350 from_utf8(d->filename.absFileName())));
4353 lyxvc().file_found_hook(d->filename);
4356 return ReadAutosaveFailure;
4359 // Here we delete the autosave
4360 autosaveFile.removeFile();
4361 return ReadOriginal;
4369 Buffer::ReadStatus Buffer::loadLyXFile()
4371 if (!d->filename.isReadableFile()) {
4372 ReadStatus const ret_rvc = extractFromVC();
4373 if (ret_rvc != ReadSuccess)
4377 ReadStatus const ret_re = loadEmergency();
4378 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4381 ReadStatus const ret_ra = loadAutosave();
4382 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4385 return loadThisLyXFile(d->filename);
4389 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4391 return readFile(fn);
4395 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4397 TeXErrors::Errors::const_iterator it = terr.begin();
4398 TeXErrors::Errors::const_iterator end = terr.end();
4399 ListOfBuffers clist = getDescendents();
4400 ListOfBuffers::const_iterator cen = clist.end();
4402 for (; it != end; ++it) {
4405 int errorRow = it->error_in_line;
4406 Buffer const * buf = 0;
4408 if (it->child_name.empty())
4409 p->texrow.getIdFromRow(errorRow, id_start, pos_start);
4411 // The error occurred in a child
4412 ListOfBuffers::const_iterator cit = clist.begin();
4413 for (; cit != cen; ++cit) {
4414 string const child_name =
4415 DocFileName(changeExtension(
4416 (*cit)->absFileName(), "tex")).
4418 if (it->child_name != child_name)
4420 (*cit)->d->texrow.getIdFromRow(errorRow,
4421 id_start, pos_start);
4422 if (id_start != -1) {
4423 buf = d->cloned_buffer_
4424 ? (*cit)->d->cloned_buffer_->d->owner_
4425 : (*cit)->d->owner_;
4436 found = p->texrow.getIdFromRow(errorRow, id_end, pos_end);
4437 } while (found && id_start == id_end && pos_start == pos_end);
4439 if (id_start != id_end) {
4440 // Next registered position is outside the inset where
4441 // the error occurred, so signal end-of-paragraph
4445 errorList.push_back(ErrorItem(it->error_desc,
4446 it->error_text, id_start, pos_start, pos_end, buf));
4451 void Buffer::setBuffersForInsets() const
4453 inset().setBuffer(const_cast<Buffer &>(*this));
4457 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4459 LBUFERR(!text().paragraphs().empty());
4461 // Use the master text class also for child documents
4462 Buffer const * const master = masterBuffer();
4463 DocumentClass const & textclass = master->params().documentClass();
4465 // do this only if we are the top-level Buffer
4466 if (master == this) {
4467 textclass.counters().reset(from_ascii("bibitem"));
4468 reloadBibInfoCache();
4471 // keep the buffers to be children in this set. If the call from the
4472 // master comes back we can see which of them were actually seen (i.e.
4473 // via an InsetInclude). The remaining ones in the set need still be updated.
4474 static std::set<Buffer const *> bufToUpdate;
4475 if (scope == UpdateMaster) {
4476 // If this is a child document start with the master
4477 if (master != this) {
4478 bufToUpdate.insert(this);
4479 master->updateBuffer(UpdateMaster, utype);
4480 // If the master buffer has no gui associated with it, then the TocModel is
4481 // not updated during the updateBuffer call and TocModel::toc_ is invalid
4482 // (bug 5699). The same happens if the master buffer is open in a different
4483 // window. This test catches both possibilities.
4484 // See: http://marc.info/?l=lyx-devel&m=138590578911716&w=2
4485 // There remains a problem here: If there is another child open in yet a third
4486 // window, that TOC is not updated. So some more general solution is needed at
4488 if (master->d->gui_ != d->gui_)
4491 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4492 if (bufToUpdate.find(this) == bufToUpdate.end())
4496 // start over the counters in the master
4497 textclass.counters().reset();
4500 // update will be done below for this buffer
4501 bufToUpdate.erase(this);
4503 // update all caches
4504 clearReferenceCache();
4507 Buffer & cbuf = const_cast<Buffer &>(*this);
4510 ParIterator parit = cbuf.par_iterator_begin();
4511 updateBuffer(parit, utype);
4514 // TocBackend update will be done later.
4517 d->bibinfo_cache_valid_ = true;
4518 d->cite_labels_valid_ = true;
4520 cbuf.tocBackend().update(true, utype);
4521 if (scope == UpdateMaster)
4522 cbuf.structureChanged();
4526 static depth_type getDepth(DocIterator const & it)
4528 depth_type depth = 0;
4529 for (size_t i = 0 ; i < it.depth() ; ++i)
4530 if (!it[i].inset().inMathed())
4531 depth += it[i].paragraph().getDepth() + 1;
4532 // remove 1 since the outer inset does not count
4536 static depth_type getItemDepth(ParIterator const & it)
4538 Paragraph const & par = *it;
4539 LabelType const labeltype = par.layout().labeltype;
4541 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4544 // this will hold the lowest depth encountered up to now.
4545 depth_type min_depth = getDepth(it);
4546 ParIterator prev_it = it;
4549 --prev_it.top().pit();
4551 // start of nested inset: go to outer par
4553 if (prev_it.empty()) {
4554 // start of document: nothing to do
4559 // We search for the first paragraph with same label
4560 // that is not more deeply nested.
4561 Paragraph & prev_par = *prev_it;
4562 depth_type const prev_depth = getDepth(prev_it);
4563 if (labeltype == prev_par.layout().labeltype) {
4564 if (prev_depth < min_depth)
4565 return prev_par.itemdepth + 1;
4566 if (prev_depth == min_depth)
4567 return prev_par.itemdepth;
4569 min_depth = min(min_depth, prev_depth);
4570 // small optimization: if we are at depth 0, we won't
4571 // find anything else
4572 if (prev_depth == 0)
4578 static bool needEnumCounterReset(ParIterator const & it)
4580 Paragraph const & par = *it;
4581 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, return false);
4582 depth_type const cur_depth = par.getDepth();
4583 ParIterator prev_it = it;
4584 while (prev_it.pit()) {
4585 --prev_it.top().pit();
4586 Paragraph const & prev_par = *prev_it;
4587 if (prev_par.getDepth() <= cur_depth)
4588 return prev_par.layout().labeltype != LABEL_ENUMERATE;
4590 // start of nested inset: reset
4595 // set the label of a paragraph. This includes the counters.
4596 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4598 BufferParams const & bp = owner_->masterBuffer()->params();
4599 DocumentClass const & textclass = bp.documentClass();
4600 Paragraph & par = it.paragraph();
4601 Layout const & layout = par.layout();
4602 Counters & counters = textclass.counters();
4604 if (par.params().startOfAppendix()) {
4605 // We want to reset the counter corresponding to toplevel sectioning
4606 Layout const & lay = textclass.getTOCLayout();
4607 docstring const cnt = lay.counter;
4609 counters.reset(cnt);
4610 counters.appendix(true);
4612 par.params().appendix(counters.appendix());
4614 // Compute the item depth of the paragraph
4615 par.itemdepth = getItemDepth(it);
4617 if (layout.margintype == MARGIN_MANUAL) {
4618 if (par.params().labelWidthString().empty())
4619 par.params().labelWidthString(par.expandLabel(layout, bp));
4620 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4621 // we do not need to do anything here, since the empty case is
4622 // handled during export.
4624 par.params().labelWidthString(docstring());
4627 switch(layout.labeltype) {
4628 case LABEL_ITEMIZE: {
4629 // At some point of time we should do something more
4630 // clever here, like:
4631 // par.params().labelString(
4632 // bp.user_defined_bullet(par.itemdepth).getText());
4633 // for now, use a simple hardcoded label
4634 docstring itemlabel;
4635 switch (par.itemdepth) {
4637 itemlabel = char_type(0x2022);
4640 itemlabel = char_type(0x2013);
4643 itemlabel = char_type(0x2217);
4646 itemlabel = char_type(0x2219); // or 0x00b7
4649 par.params().labelString(itemlabel);
4653 case LABEL_ENUMERATE: {
4654 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4656 switch (par.itemdepth) {
4665 enumcounter += "iv";
4668 // not a valid enumdepth...
4672 // Maybe we have to reset the enumeration counter.
4673 if (needEnumCounterReset(it))
4674 counters.reset(enumcounter);
4675 counters.step(enumcounter, utype);
4677 string const & lang = par.getParLanguage(bp)->code();
4678 par.params().labelString(counters.theCounter(enumcounter, lang));
4683 case LABEL_SENSITIVE: {
4684 string const & type = counters.current_float();
4685 docstring full_label;
4687 full_label = owner_->B_("Senseless!!! ");
4689 docstring name = owner_->B_(textclass.floats().getType(type).name());
4690 if (counters.hasCounter(from_utf8(type))) {
4691 string const & lang = par.getParLanguage(bp)->code();
4692 counters.step(from_utf8(type), utype);
4693 full_label = bformat(from_ascii("%1$s %2$s:"),
4695 counters.theCounter(from_utf8(type), lang));
4697 full_label = bformat(from_ascii("%1$s #:"), name);
4699 par.params().labelString(full_label);
4703 case LABEL_NO_LABEL:
4704 par.params().labelString(docstring());
4708 case LABEL_CENTERED:
4709 case LABEL_STATIC: {
4710 docstring const & lcounter = layout.counter;
4711 if (!lcounter.empty()) {
4712 if (layout.toclevel <= bp.secnumdepth
4713 && (layout.latextype != LATEX_ENVIRONMENT
4714 || it.text()->isFirstInSequence(it.pit()))) {
4715 if (counters.hasCounter(lcounter))
4716 counters.step(lcounter, utype);
4717 par.params().labelString(par.expandLabel(layout, bp));
4719 par.params().labelString(docstring());
4721 par.params().labelString(par.expandLabel(layout, bp));
4727 par.params().labelString(par.expandLabel(layout, bp));
4732 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4734 // LASSERT: Is it safe to continue here, or should we just return?
4735 LASSERT(parit.pit() == 0, /**/);
4737 // Set the position of the text in the buffer to be able
4738 // to resolve macros in it.
4739 parit.text()->setMacrocontextPosition(parit);
4741 depth_type maxdepth = 0;
4742 pit_type const lastpit = parit.lastpit();
4743 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4744 // reduce depth if necessary
4745 if (parit->params().depth() > maxdepth) {
4746 /** FIXME: this function is const, but
4747 * nevertheless it modifies the buffer. To be
4748 * cleaner, one should modify the buffer in
4749 * another function, which is actually
4750 * non-const. This would however be costly in
4751 * terms of code duplication.
4753 const_cast<Buffer *>(this)->undo().recordUndo(CursorData(parit));
4754 parit->params().depth(maxdepth);
4756 maxdepth = parit->getMaxDepthAfter();
4758 if (utype == OutputUpdate) {
4759 // track the active counters
4760 // we have to do this for the master buffer, since the local
4761 // buffer isn't tracking anything.
4762 masterBuffer()->params().documentClass().counters().
4763 setActiveLayout(parit->layout());
4766 // set the counter for this paragraph
4767 d->setLabel(parit, utype);
4770 InsetList::const_iterator iit = parit->insetList().begin();
4771 InsetList::const_iterator end = parit->insetList().end();
4772 for (; iit != end; ++iit) {
4773 parit.pos() = iit->pos;
4774 iit->inset->updateBuffer(parit, utype);
4780 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4781 WordLangTuple & word_lang, docstring_list & suggestions) const
4785 suggestions.clear();
4786 word_lang = WordLangTuple();
4787 bool const to_end = to.empty();
4788 DocIterator const end = to_end ? doc_iterator_end(this) : to;
4789 // OK, we start from here.
4790 for (; from != end; from.forwardPos()) {
4791 // This skips all insets with spell check disabled.
4792 while (!from.allowSpellCheck()) {
4796 // If from is at the end of the document (which is possible
4797 // when "from" was changed above) LyX will crash later otherwise.
4798 if (from.atEnd() || (!to_end && from >= end))
4801 from.paragraph().spellCheck();
4802 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4803 if (SpellChecker::misspelled(res)) {
4807 // Do not increase progress when from == to, otherwise the word
4808 // count will be wrong.
4818 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
4820 bool inword = false;
4825 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
4826 if (!dit.inTexted()) {
4831 Paragraph const & par = dit.paragraph();
4832 pos_type const pos = dit.pos();
4834 // Copied and adapted from isWordSeparator() in Paragraph
4835 if (pos == dit.lastpos()) {
4838 Inset const * ins = par.getInset(pos);
4839 if (ins && skipNoOutput && !ins->producesOutput()) {
4842 // stop if end of range was skipped
4843 if (!to.atEnd() && dit >= to)
4846 } else if (!par.isDeleted(pos)) {
4847 if (par.isWordSeparator(pos))
4853 if (ins && ins->isLetter())
4855 else if (ins && ins->isSpace())
4858 char_type const c = par.getChar(pos);
4859 if (isPrintableNonspace(c))
4861 else if (isSpace(c))
4871 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
4873 d->updateStatistics(from, to, skipNoOutput);
4877 int Buffer::wordCount() const
4879 return d->wordCount();
4883 int Buffer::charCount(bool with_blanks) const
4885 return d->charCount(with_blanks);
4889 Buffer::ReadStatus Buffer::reload()
4892 // c.f. bug http://www.lyx.org/trac/ticket/6587
4893 removeAutosaveFile();
4894 // e.g., read-only status could have changed due to version control
4895 d->filename.refresh();
4896 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4898 // clear parent. this will get reset if need be.
4900 ReadStatus const status = loadLyXFile();
4901 if (status == ReadSuccess) {
4906 message(bformat(_("Document %1$s reloaded."), disp_fn));
4909 message(bformat(_("Could not reload document %1$s."), disp_fn));
4919 bool Buffer::saveAs(FileName const & fn)
4921 FileName const old_name = fileName();
4922 FileName const old_auto = getAutosaveFileName();
4923 bool const old_unnamed = isUnnamed();
4924 bool success = true;
4925 d->old_position = filePath();
4932 // bring the autosave file with us, just in case.
4933 moveAutosaveFile(old_auto);
4934 // validate version control data and
4935 // correct buffer title
4936 lyxvc().file_found_hook(fileName());
4938 // the file has now been saved to the new location.
4939 // we need to check that the locations of child buffers
4941 checkChildBuffers();
4942 checkMasterBuffer();
4945 // reset the old filename and unnamed state
4946 setFileName(old_name);
4947 setUnnamed(old_unnamed);
4951 d->old_position.clear();
4956 void Buffer::checkChildBuffers()
4958 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4959 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4960 for (; it != en; ++it) {
4961 DocIterator dit = it->second;
4962 Buffer * cbuf = const_cast<Buffer *>(it->first);
4963 if (!cbuf || !theBufferList().isLoaded(cbuf))
4965 Inset * inset = dit.nextInset();
4966 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4967 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4968 docstring const & incfile = inset_inc->getParam("filename");
4969 string oldloc = cbuf->absFileName();
4970 string newloc = makeAbsPath(to_utf8(incfile),
4971 onlyPath(absFileName())).absFileName();
4972 if (oldloc == newloc)
4974 // the location of the child file is incorrect.
4976 inset_inc->setChildBuffer(0);
4978 // invalidate cache of children
4979 d->children_positions.clear();
4980 d->position_to_children.clear();
4984 // If a child has been saved under a different name/path, it might have been
4985 // orphaned. Therefore the master needs to be reset (bug 8161).
4986 void Buffer::checkMasterBuffer()
4988 Buffer const * const master = masterBuffer();
4992 // necessary to re-register the child (bug 5873)
4993 // FIXME: clean up updateMacros (here, only
4994 // child registering is needed).
4995 master->updateMacros();
4996 // (re)set master as master buffer, but only
4997 // if we are a real child
4998 if (master->isChild(this))
5005 string Buffer::includedFilePath(string const & name, string const & ext) const
5007 bool isabsolute = FileName::isAbsolute(name);
5008 // old_position already contains a trailing path separator
5009 string const absname = isabsolute ? name : d->old_position + name;
5011 if (d->old_position.empty()
5012 || equivalent(FileName(d->old_position), FileName(filePath()))
5013 || !FileName(addExtension(absname, ext)).exists())
5017 return to_utf8(makeRelPath(from_utf8(name), from_utf8(filePath())));
5019 return to_utf8(makeRelPath(from_utf8(FileName(absname).realPath()),
5020 from_utf8(filePath())));