3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
7 * \author Stefan Schimanski
9 * Full author contact details are available in file CREDITS.
17 #include "LayoutFile.h"
18 #include "BiblioInfo.h"
19 #include "BranchList.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
25 #include "Converter.h"
27 #include "DispatchResult.h"
28 #include "DocIterator.h"
30 #include "ErrorList.h"
33 #include "FuncRequest.h"
34 #include "FuncStatus.h"
35 #include "IndicesList.h"
36 #include "InsetIterator.h"
37 #include "InsetList.h"
39 #include "LaTeXFeatures.h"
43 #include "LyXAction.h"
48 #include "output_docbook.h"
50 #include "output_latex.h"
51 #include "output_xhtml.h"
52 #include "output_plaintext.h"
53 #include "Paragraph.h"
54 #include "ParagraphParameters.h"
55 #include "ParIterator.h"
56 #include "PDFOptions.h"
57 #include "SpellChecker.h"
60 #include "TexStream.h"
62 #include "TextClass.h"
63 #include "TocBackend.h"
65 #include "VCBackend.h"
67 #include "WordLangTuple.h"
70 #include "insets/InsetBibitem.h"
71 #include "insets/InsetBibtex.h"
72 #include "insets/InsetBranch.h"
73 #include "insets/InsetInclude.h"
74 #include "insets/InsetText.h"
76 #include "mathed/MacroTable.h"
77 #include "mathed/MathMacroTemplate.h"
78 #include "mathed/MathSupport.h"
80 #include "frontends/alert.h"
81 #include "frontends/Delegates.h"
82 #include "frontends/WorkAreaManager.h"
84 #include "graphics/Previews.h"
86 #include "support/lassert.h"
87 #include "support/convert.h"
88 #include "support/debug.h"
89 #include "support/docstring_list.h"
90 #include "support/ExceptionMessage.h"
91 #include "support/FileName.h"
92 #include "support/FileNameList.h"
93 #include "support/filetools.h"
94 #include "support/ForkedCalls.h"
95 #include "support/gettext.h"
96 #include "support/gzstream.h"
97 #include "support/lstrings.h"
98 #include "support/lyxalgo.h"
99 #include "support/os.h"
100 #include "support/Package.h"
101 #include "support/Path.h"
102 #include "support/Systemcall.h"
103 #include "support/textutils.h"
104 #include "support/types.h"
106 #include <boost/bind.hpp>
107 #include <boost/shared_ptr.hpp>
119 using namespace lyx::support;
123 namespace Alert = frontend::Alert;
124 namespace os = support::os;
128 // Do not remove the comment below, so we get merge conflict in
129 // independent branches. Instead add your own.
130 int const LYX_FORMAT = 375; // jspitzm: includeonly support
132 typedef map<string, bool> DepClean;
133 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
135 void showPrintError(string const & name)
137 docstring str = bformat(_("Could not print the document %1$s.\n"
138 "Check that your printer is set up correctly."),
139 makeDisplayPath(name, 50));
140 Alert::error(_("Print document failed"), str);
145 class BufferSet : public std::set<Buffer const *> {};
150 Impl(Buffer & parent, FileName const & file, bool readonly, Buffer const * cloned_buffer);
164 mutable TexRow texrow;
166 /// need to regenerate .tex?
170 mutable bool lyx_clean;
172 /// is autosave needed?
173 mutable bool bak_clean;
175 /// is this a unnamed file (New...)?
181 /// name of the file the buffer is associated with.
184 /** Set to true only when the file is fully loaded.
185 * Used to prevent the premature generation of previews
186 * and by the citation inset.
188 bool file_fully_loaded;
191 mutable TocBackend toc_backend;
194 typedef pair<DocIterator, MacroData> ScopeMacro;
195 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
196 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
197 /// map from the macro name to the position map,
198 /// which maps the macro definition position to the scope and the MacroData.
199 NamePositionScopeMacroMap macros;
202 /// positions of child buffers in the buffer
203 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
204 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
205 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
206 /// position of children buffers in this buffer
207 BufferPositionMap children_positions;
208 /// map from children inclusion positions to their scope and their buffer
209 PositionScopeBufferMap position_to_children;
211 /// Container for all sort of Buffer dependant errors.
212 map<string, ErrorList> errorLists;
214 /// timestamp and checksum used to test if the file has been externally
215 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
217 unsigned long checksum_;
220 frontend::WorkAreaManager * wa_;
225 /// A cache for the bibfiles (including bibfiles of loaded child
226 /// documents), needed for appropriate update of natbib labels.
227 mutable support::FileNameList bibfilesCache_;
229 // FIXME The caching mechanism could be improved. At present, we have a
230 // cache for each Buffer, that caches all the bibliography info for that
231 // Buffer. A more efficient solution would be to have a global cache per
232 // file, and then to construct the Buffer's bibinfo from that.
233 /// A cache for bibliography info
234 mutable BiblioInfo bibinfo_;
235 /// whether the bibinfo cache is valid
236 bool bibinfoCacheValid_;
237 /// Cache of timestamps of .bib files
238 map<FileName, time_t> bibfileStatus_;
240 mutable RefCache ref_cache_;
242 /// our Text that should be wrapped in an InsetText
245 /// This is here to force the test to be done whenever parent_buffer
247 Buffer const * parent() const {
248 // if parent_buffer is not loaded, then it has been unloaded,
249 // which means that parent_buffer is an invalid pointer. So we
250 // set it to null in that case.
251 if (!theBufferList().isLoaded(parent_buffer))
253 return parent_buffer;
256 void setParent(Buffer const * pb) {
257 if (parent_buffer && pb && parent_buffer != pb)
258 LYXERR0("Warning: a buffer should not have two parents!");
262 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
263 /// This one is useful for preview detached in a thread.
264 Buffer const * cloned_buffer_;
267 /// So we can force access via the accessors.
268 mutable Buffer const * parent_buffer;
273 /// Creates the per buffer temporary directory
274 static FileName createBufferTmpDir()
277 // We are in our own directory. Why bother to mangle name?
278 // In fact I wrote this code to circumvent a problematic behaviour
279 // (bug?) of EMX mkstemp().
280 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
281 convert<string>(count++));
283 if (!tmpfl.createDirectory(0777)) {
284 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
285 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
286 from_utf8(tmpfl.absFilename())));
292 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_,
293 Buffer const * cloned_buffer)
294 : lyx_clean(true), bak_clean(true), unnamed(false),
295 read_only(readonly_), filename(file), file_fully_loaded(false),
296 toc_backend(&parent), macro_lock(false), timestamp_(0),
297 checksum_(0), wa_(0), undo_(parent), bibinfoCacheValid_(false),
298 cloned_buffer_(cloned_buffer), parent_buffer(0)
300 if (!cloned_buffer_) {
301 temppath = createBufferTmpDir();
302 lyxvc.setBuffer(&parent);
304 wa_ = new frontend::WorkAreaManager;
307 temppath = cloned_buffer_->d->temppath;
308 file_fully_loaded = true;
309 params = cloned_buffer_->d->params;
313 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
314 : d(new Impl(*this, FileName(file), readonly, cloned_buffer)), gui_(0)
316 LYXERR(Debug::INFO, "Buffer::Buffer()");
318 d->inset = new InsetText(*cloned_buffer->d->inset);
319 d->inset->setBuffer(*this);
320 // FIXME: optimize this loop somewhat, maybe by creating a new
321 // general recursive Inset::setId().
322 DocIterator it = doc_iterator_begin(this);
323 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
324 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
325 it.paragraph().setId(cloned_it.paragraph().id());
327 d->inset = new InsetText(this);
328 d->inset->setAutoBreakRows(true);
329 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
335 LYXERR(Debug::INFO, "Buffer::~Buffer()");
336 // here the buffer should take care that it is
337 // saved properly, before it goes into the void.
339 // GuiView already destroyed
343 // No need to do additional cleanups for internal buffer.
348 // loop over children
349 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
350 Impl::BufferPositionMap::iterator end = d->children_positions.end();
351 for (; it != end; ++it) {
352 Buffer * child = const_cast<Buffer *>(it->first);
353 // The child buffer might have been closed already.
354 if (theBufferList().isLoaded(child))
355 theBufferList().releaseChild(this, child);
359 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
360 msg += emergencyWrite();
361 Alert::warning(_("Attempting to close changed document!"), msg);
364 // clear references to children in macro tables
365 d->children_positions.clear();
366 d->position_to_children.clear();
368 if (!d->cloned_buffer_ && !d->temppath.destroyDirectory()) {
369 Alert::warning(_("Could not remove temporary directory"),
370 bformat(_("Could not remove the temporary directory %1$s"),
371 from_utf8(d->temppath.absFilename())));
374 // Remove any previewed LaTeX snippets associated with this buffer.
375 thePreviews().removeLoader(*this);
381 Buffer * Buffer::clone() const
383 // FIXME for asynchronous export and preview: We must also clone all
384 // the child buffers!
385 return new Buffer(fileName().absFilename(), false, this);
389 bool Buffer::isClone() const
391 return d->cloned_buffer_;
395 void Buffer::changed(bool update_metrics) const
398 d->wa_->redrawAll(update_metrics);
402 frontend::WorkAreaManager & Buffer::workAreaManager() const
404 LASSERT(d->wa_, /**/);
409 Text & Buffer::text() const
411 return d->inset->text();
415 Inset & Buffer::inset() const
421 BufferParams & Buffer::params()
427 BufferParams const & Buffer::params() const
433 ParagraphList & Buffer::paragraphs()
435 return text().paragraphs();
439 ParagraphList const & Buffer::paragraphs() const
441 return text().paragraphs();
445 LyXVC & Buffer::lyxvc()
451 LyXVC const & Buffer::lyxvc() const
457 string const Buffer::temppath() const
459 return d->temppath.absFilename();
463 TexRow & Buffer::texrow()
469 TexRow const & Buffer::texrow() const
475 TocBackend & Buffer::tocBackend() const
477 return d->toc_backend;
481 Undo & Buffer::undo()
487 string Buffer::latexName(bool const no_path) const
489 FileName latex_name =
490 makeLatexName(exportFileName());
491 return no_path ? latex_name.onlyFileName()
492 : latex_name.absFilename();
496 FileName Buffer::exportFileName() const
498 docstring const branch_suffix =
499 params().branchlist().getFilenameSuffix();
500 if (branch_suffix.empty())
503 string const name = fileName().onlyFileNameWithoutExt()
504 + to_utf8(branch_suffix);
505 FileName res(fileName().onlyPath().absFilename() + "/" + name);
506 res.changeExtension(fileName().extension());
512 string Buffer::logName(LogType * type) const
514 string const filename = latexName(false);
516 if (filename.empty()) {
522 string const path = temppath();
524 FileName const fname(addName(temppath(),
525 onlyFilename(changeExtension(filename,
528 // FIXME: how do we know this is the name of the build log?
529 FileName const bname(
530 addName(path, onlyFilename(
531 changeExtension(filename,
532 formats.extension(bufferFormat()) + ".out"))));
534 // Also consider the master buffer log file
535 FileName masterfname = fname;
537 if (masterBuffer() != this) {
538 string const mlogfile = masterBuffer()->logName(&mtype);
539 masterfname = FileName(mlogfile);
542 // If no Latex log or Build log is newer, show Build log
543 if (bname.exists() &&
544 ((!fname.exists() && !masterfname.exists())
545 || (fname.lastModified() < bname.lastModified()
546 && masterfname.lastModified() < bname.lastModified()))) {
547 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
550 return bname.absFilename();
551 // If we have a newer master file log or only a master log, show this
552 } else if (fname != masterfname
553 && (!fname.exists() && (masterfname.exists()
554 || fname.lastModified() < masterfname.lastModified()))) {
555 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
558 return masterfname.absFilename();
560 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
563 return fname.absFilename();
567 void Buffer::setReadonly(bool const flag)
569 if (d->read_only != flag) {
576 void Buffer::setFileName(string const & newfile)
578 d->filename = makeAbsPath(newfile);
579 setReadonly(d->filename.isReadOnly());
584 int Buffer::readHeader(Lexer & lex)
586 int unknown_tokens = 0;
588 int begin_header_line = -1;
590 // Initialize parameters that may be/go lacking in header:
591 params().branchlist().clear();
592 params().preamble.erase();
593 params().options.erase();
594 params().master.erase();
595 params().float_placement.erase();
596 params().paperwidth.erase();
597 params().paperheight.erase();
598 params().leftmargin.erase();
599 params().rightmargin.erase();
600 params().topmargin.erase();
601 params().bottommargin.erase();
602 params().headheight.erase();
603 params().headsep.erase();
604 params().footskip.erase();
605 params().columnsep.erase();
606 params().fontsCJK.erase();
607 params().listings_params.clear();
608 params().clearLayoutModules();
609 params().clearRemovedModules();
610 params().clearIncludedChildren();
611 params().pdfoptions().clear();
612 params().indiceslist().clear();
613 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
615 for (int i = 0; i < 4; ++i) {
616 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
617 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
620 ErrorList & errorList = d->errorLists["Parse"];
629 if (token == "\\end_header")
633 if (token == "\\begin_header") {
634 begin_header_line = line;
638 LYXERR(Debug::PARSER, "Handling document header token: `"
641 string unknown = params().readToken(lex, token, d->filename.onlyPath());
642 if (!unknown.empty()) {
643 if (unknown[0] != '\\' && token == "\\textclass") {
644 Alert::warning(_("Unknown document class"),
645 bformat(_("Using the default document class, because the "
646 "class %1$s is unknown."), from_utf8(unknown)));
649 docstring const s = bformat(_("Unknown token: "
653 errorList.push_back(ErrorItem(_("Document header error"),
658 if (begin_header_line) {
659 docstring const s = _("\\begin_header is missing");
660 errorList.push_back(ErrorItem(_("Document header error"),
664 params().makeDocumentClass();
666 return unknown_tokens;
671 // changed to be public and have one parameter
672 // Returns true if "\end_document" is not read (Asger)
673 bool Buffer::readDocument(Lexer & lex)
675 ErrorList & errorList = d->errorLists["Parse"];
678 if (!lex.checkFor("\\begin_document")) {
679 docstring const s = _("\\begin_document is missing");
680 errorList.push_back(ErrorItem(_("Document header error"),
684 // we are reading in a brand new document
685 LASSERT(paragraphs().empty(), /**/);
689 if (params().outputChanges) {
690 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
691 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
692 LaTeXFeatures::isAvailable("xcolor");
694 if (!dvipost && !xcolorulem) {
695 Alert::warning(_("Changes not shown in LaTeX output"),
696 _("Changes will not be highlighted in LaTeX output, "
697 "because neither dvipost nor xcolor/ulem are installed.\n"
698 "Please install these packages or redefine "
699 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
700 } else if (!xcolorulem) {
701 Alert::warning(_("Changes not shown in LaTeX output"),
702 _("Changes will not be highlighted in LaTeX output "
703 "when using pdflatex, because xcolor and ulem are not installed.\n"
704 "Please install both packages or redefine "
705 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
709 if (!params().master.empty()) {
710 FileName const master_file = makeAbsPath(params().master,
711 onlyPath(absFileName()));
712 if (isLyXFilename(master_file.absFilename())) {
714 checkAndLoadLyXFile(master_file, true);
716 // necessary e.g. after a reload
717 // to re-register the child (bug 5873)
718 // FIXME: clean up updateMacros (here, only
719 // child registering is needed).
720 master->updateMacros();
721 // set master as master buffer, but only
722 // if we are a real child
723 if (master->isChild(this))
725 // if the master is not fully loaded
726 // it is probably just loading this
727 // child. No warning needed then.
728 else if (master->isFullyLoaded())
729 LYXERR0("The master '"
731 << "' assigned to this document ("
733 << ") does not include "
734 "this document. Ignoring the master assignment.");
739 // assure we have a default index
740 params().indiceslist().addDefault(B_("Index"));
743 bool const res = text().read(lex, errorList, d->inset);
747 updateMacroInstances();
752 bool Buffer::readString(string const & s)
754 params().compressed = false;
756 // remove dummy empty par
757 paragraphs().clear();
761 FileName const name = FileName::tempName("Buffer_readString");
762 switch (readFile(lex, name, true)) {
766 // We need to call lyx2lyx, so write the input to a file
767 ofstream os(name.toFilesystemEncoding().c_str());
770 return readFile(name);
780 bool Buffer::readFile(FileName const & filename)
782 FileName fname(filename);
784 params().compressed = fname.isZippedFile();
786 // remove dummy empty par
787 paragraphs().clear();
790 if (readFile(lex, fname) != success)
797 bool Buffer::isFullyLoaded() const
799 return d->file_fully_loaded;
803 void Buffer::setFullyLoaded(bool value)
805 d->file_fully_loaded = value;
809 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
812 LASSERT(!filename.empty(), /**/);
814 // the first (non-comment) token _must_ be...
815 if (!lex.checkFor("\\lyxformat")) {
816 Alert::error(_("Document format failure"),
817 bformat(_("%1$s is not a readable LyX document."),
818 from_utf8(filename.absFilename())));
824 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
825 // if present remove ".," from string.
826 size_t dot = tmp_format.find_first_of(".,");
827 //lyxerr << " dot found at " << dot << endl;
828 if (dot != string::npos)
829 tmp_format.erase(dot, 1);
830 int const file_format = convert<int>(tmp_format);
831 //lyxerr << "format: " << file_format << endl;
833 // save timestamp and checksum of the original disk file, making sure
834 // to not overwrite them with those of the file created in the tempdir
835 // when it has to be converted to the current format.
837 // Save the timestamp and checksum of disk file. If filename is an
838 // emergency file, save the timestamp and checksum of the original lyx file
839 // because isExternallyModified will check for this file. (BUG4193)
840 string diskfile = filename.absFilename();
841 if (suffixIs(diskfile, ".emergency"))
842 diskfile = diskfile.substr(0, diskfile.size() - 10);
843 saveCheckSum(FileName(diskfile));
846 if (file_format != LYX_FORMAT) {
849 // lyx2lyx would fail
852 FileName const tmpfile = FileName::tempName("Buffer_readFile");
853 if (tmpfile.empty()) {
854 Alert::error(_("Conversion failed"),
855 bformat(_("%1$s is from a different"
856 " version of LyX, but a temporary"
857 " file for converting it could"
859 from_utf8(filename.absFilename())));
862 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
863 if (lyx2lyx.empty()) {
864 Alert::error(_("Conversion script not found"),
865 bformat(_("%1$s is from a different"
866 " version of LyX, but the"
867 " conversion script lyx2lyx"
868 " could not be found."),
869 from_utf8(filename.absFilename())));
872 ostringstream command;
873 command << os::python()
874 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
875 << " -t " << convert<string>(LYX_FORMAT)
876 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
877 << ' ' << quoteName(filename.toFilesystemEncoding());
878 string const command_str = command.str();
880 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
882 cmd_ret const ret = runCommand(command_str);
883 if (ret.first != 0) {
884 Alert::error(_("Conversion script failed"),
885 bformat(_("%1$s is from a different version"
886 " of LyX, but the lyx2lyx script"
887 " failed to convert it."),
888 from_utf8(filename.absFilename())));
891 bool const ret = readFile(tmpfile);
892 // Do stuff with tmpfile name and buffer name here.
893 return ret ? success : failure;
898 if (readDocument(lex)) {
899 Alert::error(_("Document format failure"),
900 bformat(_("%1$s ended unexpectedly, which means"
901 " that it is probably corrupted."),
902 from_utf8(filename.absFilename())));
905 d->file_fully_loaded = true;
910 // Should probably be moved to somewhere else: BufferView? LyXView?
911 bool Buffer::save() const
913 // We don't need autosaves in the immediate future. (Asger)
914 resetAutosaveTimers();
916 string const encodedFilename = d->filename.toFilesystemEncoding();
919 bool madeBackup = false;
921 // make a backup if the file already exists
922 if (lyxrc.make_backup && fileName().exists()) {
923 backupName = FileName(absFileName() + '~');
924 if (!lyxrc.backupdir_path.empty()) {
925 string const mangledName =
926 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
927 backupName = FileName(addName(lyxrc.backupdir_path,
930 if (fileName().copyTo(backupName)) {
933 Alert::error(_("Backup failure"),
934 bformat(_("Cannot create backup file %1$s.\n"
935 "Please check whether the directory exists and is writeable."),
936 from_utf8(backupName.absFilename())));
937 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
941 // ask if the disk file has been externally modified (use checksum method)
942 if (fileName().exists() && isExternallyModified(checksum_method)) {
943 docstring const file = makeDisplayPath(absFileName(), 20);
944 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
945 "you want to overwrite this file?"), file);
946 int const ret = Alert::prompt(_("Overwrite modified file?"),
947 text, 1, 1, _("&Overwrite"), _("&Cancel"));
952 if (writeFile(d->filename)) {
956 // Saving failed, so backup is not backup
958 backupName.moveTo(d->filename);
964 bool Buffer::writeFile(FileName const & fname) const
966 if (d->read_only && fname == d->filename)
971 docstring const str = bformat(_("Saving document %1$s..."),
972 makeDisplayPath(fname.absFilename()));
975 if (params().compressed) {
976 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
977 retval = ofs && write(ofs);
979 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
980 retval = ofs && write(ofs);
984 message(str + _(" could not write file!"));
988 removeAutosaveFile();
990 saveCheckSum(d->filename);
991 message(str + _(" done."));
997 docstring Buffer::emergencyWrite()
999 // No need to save if the buffer has not changed.
1003 string const doc = isUnnamed() ? onlyFilename(absFileName()) : absFileName();
1005 docstring user_message = bformat(
1006 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1008 // We try to save three places:
1009 // 1) Same place as document. Unless it is an unnamed doc.
1011 string s = absFileName();
1014 if (writeFile(FileName(s))) {
1016 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1017 return user_message;
1019 user_message += _(" Save failed! Trying again...\n");
1023 // 2) In HOME directory.
1024 string s = addName(package().home_dir().absFilename(), absFileName());
1026 lyxerr << ' ' << s << endl;
1027 if (writeFile(FileName(s))) {
1029 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1030 return user_message;
1033 user_message += _(" Save failed! Trying yet again...\n");
1035 // 3) In "/tmp" directory.
1036 // MakeAbsPath to prepend the current
1037 // drive letter on OS/2
1038 s = addName(package().temp_dir().absFilename(), absFileName());
1040 lyxerr << ' ' << s << endl;
1041 if (writeFile(FileName(s))) {
1043 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1044 return user_message;
1047 user_message += _(" Save failed! Bummer. Document is lost.");
1050 return user_message;
1054 bool Buffer::write(ostream & ofs) const
1057 // Use the standard "C" locale for file output.
1058 ofs.imbue(locale::classic());
1061 // The top of the file should not be written by params().
1063 // write out a comment in the top of the file
1064 ofs << "#LyX " << lyx_version
1065 << " created this file. For more info see http://www.lyx.org/\n"
1066 << "\\lyxformat " << LYX_FORMAT << "\n"
1067 << "\\begin_document\n";
1069 /// For each author, set 'used' to true if there is a change
1070 /// by this author in the document; otherwise set it to 'false'.
1071 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1072 AuthorList::Authors::const_iterator a_end = params().authors().end();
1073 for (; a_it != a_end; ++a_it)
1074 a_it->setUsed(false);
1076 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1077 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1078 for ( ; it != end; ++it)
1079 it->checkAuthors(params().authors());
1081 // now write out the buffer parameters.
1082 ofs << "\\begin_header\n";
1083 params().writeFile(ofs);
1084 ofs << "\\end_header\n";
1087 ofs << "\n\\begin_body\n";
1089 ofs << "\n\\end_body\n";
1091 // Write marker that shows file is complete
1092 ofs << "\\end_document" << endl;
1094 // Shouldn't really be needed....
1097 // how to check if close went ok?
1098 // Following is an attempt... (BE 20001011)
1100 // good() returns false if any error occured, including some
1101 // formatting error.
1102 // bad() returns true if something bad happened in the buffer,
1103 // which should include file system full errors.
1108 lyxerr << "File was not closed properly." << endl;
1115 bool Buffer::makeLaTeXFile(FileName const & fname,
1116 string const & original_path,
1117 OutputParams const & runparams_in,
1118 bool output_preamble, bool output_body) const
1120 OutputParams runparams = runparams_in;
1121 if (params().useXetex)
1122 runparams.flavor = OutputParams::XETEX;
1124 string const encoding = runparams.encoding->iconvName();
1125 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1128 try { ofs.reset(encoding); }
1129 catch (iconv_codecvt_facet_exception & e) {
1130 lyxerr << "Caught iconv exception: " << e.what() << endl;
1131 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1132 "verify that the support software for your encoding (%1$s) is "
1133 "properly installed"), from_ascii(encoding)));
1136 if (!openFileWrite(ofs, fname))
1139 //TexStream ts(ofs.rdbuf(), &texrow());
1140 ErrorList & errorList = d->errorLists["Export"];
1142 bool failed_export = false;
1145 writeLaTeXSource(ofs, original_path,
1146 runparams, output_preamble, output_body);
1148 catch (EncodingException & e) {
1149 odocstringstream ods;
1150 ods.put(e.failed_char);
1152 oss << "0x" << hex << e.failed_char << dec;
1153 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1154 " (code point %2$s)"),
1155 ods.str(), from_utf8(oss.str()));
1156 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1157 "representable in the chosen encoding.\n"
1158 "Changing the document encoding to utf8 could help."),
1159 e.par_id, e.pos, e.pos + 1));
1160 failed_export = true;
1162 catch (iconv_codecvt_facet_exception & e) {
1163 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1164 _(e.what()), -1, 0, 0));
1165 failed_export = true;
1167 catch (exception const & e) {
1168 errorList.push_back(ErrorItem(_("conversion failed"),
1169 _(e.what()), -1, 0, 0));
1170 failed_export = true;
1173 lyxerr << "Caught some really weird exception..." << endl;
1179 failed_export = true;
1180 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1184 return !failed_export;
1188 void Buffer::writeLaTeXSource(odocstream & os,
1189 string const & original_path,
1190 OutputParams const & runparams_in,
1191 bool const output_preamble, bool const output_body) const
1193 // The child documents, if any, shall be already loaded at this point.
1195 OutputParams runparams = runparams_in;
1197 // Classify the unicode characters appearing in math insets
1198 Encodings::initUnicodeMath(*this);
1200 // validate the buffer.
1201 LYXERR(Debug::LATEX, " Validating buffer...");
1202 LaTeXFeatures features(*this, params(), runparams);
1204 LYXERR(Debug::LATEX, " Buffer validation done.");
1206 // The starting paragraph of the coming rows is the
1207 // first paragraph of the document. (Asger)
1208 if (output_preamble && runparams.nice) {
1209 os << "%% LyX " << lyx_version << " created this file. "
1210 "For more info, see http://www.lyx.org/.\n"
1211 "%% Do not edit unless you really know what "
1213 d->texrow.newline();
1214 d->texrow.newline();
1216 LYXERR(Debug::INFO, "lyx document header finished");
1218 // Don't move this behind the parent_buffer=0 code below,
1219 // because then the macros will not get the right "redefinition"
1220 // flag as they don't see the parent macros which are output before.
1223 // fold macros if possible, still with parent buffer as the
1224 // macros will be put in the prefix anyway.
1225 updateMacroInstances();
1227 // There are a few differences between nice LaTeX and usual files:
1228 // usual is \batchmode and has a
1229 // special input@path to allow the including of figures
1230 // with either \input or \includegraphics (what figinsets do).
1231 // input@path is set when the actual parameter
1232 // original_path is set. This is done for usual tex-file, but not
1233 // for nice-latex-file. (Matthias 250696)
1234 // Note that input@path is only needed for something the user does
1235 // in the preamble, included .tex files or ERT, files included by
1236 // LyX work without it.
1237 if (output_preamble) {
1238 if (!runparams.nice) {
1239 // code for usual, NOT nice-latex-file
1240 os << "\\batchmode\n"; // changed
1241 // from \nonstopmode
1242 d->texrow.newline();
1244 if (!original_path.empty()) {
1246 // We don't know the encoding of inputpath
1247 docstring const inputpath = from_utf8(latex_path(original_path));
1248 os << "\\makeatletter\n"
1249 << "\\def\\input@path{{"
1250 << inputpath << "/}}\n"
1251 << "\\makeatother\n";
1252 d->texrow.newline();
1253 d->texrow.newline();
1254 d->texrow.newline();
1257 // get parent macros (if this buffer has a parent) which will be
1258 // written at the document begin further down.
1259 MacroSet parentMacros;
1260 listParentMacros(parentMacros, features);
1262 // Write the preamble
1263 runparams.use_babel = params().writeLaTeX(os, features,
1265 d->filename.onlyPath());
1267 runparams.use_japanese = features.isRequired("japanese");
1273 os << "\\begin{document}\n";
1274 d->texrow.newline();
1276 // output the parent macros
1277 MacroSet::iterator it = parentMacros.begin();
1278 MacroSet::iterator end = parentMacros.end();
1279 for (; it != end; ++it)
1280 (*it)->write(os, true);
1281 } // output_preamble
1283 d->texrow.start(paragraphs().begin()->id(), 0);
1285 LYXERR(Debug::INFO, "preamble finished, now the body.");
1287 // if we are doing a real file with body, even if this is the
1288 // child of some other buffer, let's cut the link here.
1289 // This happens for example if only a child document is printed.
1290 Buffer const * save_parent = 0;
1291 if (output_preamble) {
1292 save_parent = d->parent();
1297 latexParagraphs(*this, text(), os, d->texrow, runparams);
1299 // Restore the parenthood if needed
1300 if (output_preamble)
1301 d->setParent(save_parent);
1303 // add this just in case after all the paragraphs
1305 d->texrow.newline();
1307 if (output_preamble) {
1308 os << "\\end{document}\n";
1309 d->texrow.newline();
1310 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1312 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1314 runparams_in.encoding = runparams.encoding;
1316 // Just to be sure. (Asger)
1317 d->texrow.newline();
1319 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1320 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1324 bool Buffer::isLatex() const
1326 return params().documentClass().outputType() == LATEX;
1330 bool Buffer::isLiterate() const
1332 return params().documentClass().outputType() == LITERATE;
1336 bool Buffer::isDocBook() const
1338 return params().documentClass().outputType() == DOCBOOK;
1342 void Buffer::makeDocBookFile(FileName const & fname,
1343 OutputParams const & runparams,
1344 bool const body_only) const
1346 LYXERR(Debug::LATEX, "makeDocBookFile...");
1349 if (!openFileWrite(ofs, fname))
1352 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1356 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1360 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1361 OutputParams const & runparams,
1362 bool const only_body) const
1364 LaTeXFeatures features(*this, params(), runparams);
1369 DocumentClass const & tclass = params().documentClass();
1370 string const top_element = tclass.latexname();
1373 if (runparams.flavor == OutputParams::XML)
1374 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1377 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1380 if (! tclass.class_header().empty())
1381 os << from_ascii(tclass.class_header());
1382 else if (runparams.flavor == OutputParams::XML)
1383 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1384 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1386 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1388 docstring preamble = from_utf8(params().preamble);
1389 if (runparams.flavor != OutputParams::XML ) {
1390 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1391 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1392 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1393 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1396 string const name = runparams.nice
1397 ? changeExtension(absFileName(), ".sgml") : fname;
1398 preamble += features.getIncludedFiles(name);
1399 preamble += features.getLyXSGMLEntities();
1401 if (!preamble.empty()) {
1402 os << "\n [ " << preamble << " ]";
1407 string top = top_element;
1409 if (runparams.flavor == OutputParams::XML)
1410 top += params().language->code();
1412 top += params().language->code().substr(0, 2);
1415 if (!params().options.empty()) {
1417 top += params().options;
1420 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1421 << " file was created by LyX " << lyx_version
1422 << "\n See http://www.lyx.org/ for more information -->\n";
1424 params().documentClass().counters().reset();
1428 sgml::openTag(os, top);
1430 docbookParagraphs(text(), *this, os, runparams);
1431 sgml::closeTag(os, top_element);
1435 void Buffer::makeLyXHTMLFile(FileName const & fname,
1436 OutputParams const & runparams,
1437 bool const body_only) const
1439 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1442 if (!openFileWrite(ofs, fname))
1445 writeLyXHTMLSource(ofs, runparams, body_only);
1449 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1453 void Buffer::writeLyXHTMLSource(odocstream & os,
1454 OutputParams const & runparams,
1455 bool const only_body) const
1457 LaTeXFeatures features(*this, params(), runparams);
1459 updateLabels(UpdateMaster, true);
1460 checkBibInfoCache();
1461 d->bibinfo_.collectCitedEntries(*this);
1464 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1465 os << "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1 plus MathML 2.0//EN\" \"http://www.w3.org/TR/MathML2/dtd/xhtml-math11-f.dtd\">\n";
1466 // FIXME Language should be set properly.
1467 os << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n";
1470 // FIXME Presumably need to set this right
1471 os << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1472 // FIXME Get this during validation? What about other meta-data?
1473 os << "<title>TBA</title>\n";
1475 os << "\n<!-- Text Class Preamble -->\n"
1476 << features.getTClassHTMLPreamble()
1477 << "\n<!-- Premable Snippets -->\n"
1478 << from_utf8(features.getPreambleSnippets());
1480 os << "\n<!-- Layout-provided Styles -->\n";
1481 docstring const styleinfo = features.getTClassHTMLStyles();
1482 if (!styleinfo.empty()) {
1483 os << "<style type='text/css'>\n"
1487 os << "</head>\n<body>\n";
1491 params().documentClass().counters().reset();
1492 xhtmlParagraphs(text(), *this, xs, runparams);
1494 os << "</body>\n</html>\n";
1498 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1499 // Other flags: -wall -v0 -x
1500 int Buffer::runChktex()
1504 // get LaTeX-Filename
1505 FileName const path(temppath());
1506 string const name = addName(path.absFilename(), latexName());
1507 string const org_path = filePath();
1509 PathChanger p(path); // path to LaTeX file
1510 message(_("Running chktex..."));
1512 // Generate the LaTeX file if neccessary
1513 OutputParams runparams(¶ms().encoding());
1514 runparams.flavor = OutputParams::LATEX;
1515 runparams.nice = false;
1516 makeLaTeXFile(FileName(name), org_path, runparams);
1519 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1520 int const res = chktex.run(terr); // run chktex
1523 Alert::error(_("chktex failure"),
1524 _("Could not run chktex successfully."));
1525 } else if (res > 0) {
1526 ErrorList & errlist = d->errorLists["ChkTeX"];
1528 bufferErrors(terr, errlist);
1539 void Buffer::validate(LaTeXFeatures & features) const
1541 params().validate(features);
1545 for_each(paragraphs().begin(), paragraphs().end(),
1546 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1548 if (lyxerr.debugging(Debug::LATEX)) {
1549 features.showStruct();
1554 void Buffer::getLabelList(vector<docstring> & list) const
1556 // If this is a child document, use the parent's list instead.
1557 Buffer const * const pbuf = d->parent();
1559 pbuf->getLabelList(list);
1564 Toc & toc = d->toc_backend.toc("label");
1565 TocIterator toc_it = toc.begin();
1566 TocIterator end = toc.end();
1567 for (; toc_it != end; ++toc_it) {
1568 if (toc_it->depth() == 0)
1569 list.push_back(toc_it->str());
1574 void Buffer::updateBibfilesCache(UpdateScope scope) const
1576 // If this is a child document, use the parent's cache instead.
1577 Buffer const * const pbuf = d->parent();
1578 if (pbuf && scope != UpdateChildOnly) {
1579 pbuf->updateBibfilesCache();
1583 d->bibfilesCache_.clear();
1584 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1585 if (it->lyxCode() == BIBTEX_CODE) {
1586 InsetBibtex const & inset =
1587 static_cast<InsetBibtex const &>(*it);
1588 support::FileNameList const bibfiles = inset.getBibFiles();
1589 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1592 } else if (it->lyxCode() == INCLUDE_CODE) {
1593 InsetInclude & inset =
1594 static_cast<InsetInclude &>(*it);
1595 inset.updateBibfilesCache();
1596 support::FileNameList const & bibfiles =
1597 inset.getBibfilesCache();
1598 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1603 // the bibinfo cache is now invalid
1604 d->bibinfoCacheValid_ = false;
1608 void Buffer::invalidateBibinfoCache()
1610 d->bibinfoCacheValid_ = false;
1614 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1616 // If this is a child document, use the parent's cache instead.
1617 Buffer const * const pbuf = d->parent();
1618 if (pbuf && scope != UpdateChildOnly)
1619 return pbuf->getBibfilesCache();
1621 // We update the cache when first used instead of at loading time.
1622 if (d->bibfilesCache_.empty())
1623 const_cast<Buffer *>(this)->updateBibfilesCache(scope);
1625 return d->bibfilesCache_;
1629 BiblioInfo const & Buffer::masterBibInfo() const
1631 // if this is a child document and the parent is already loaded
1632 // use the parent's list instead [ale990412]
1633 Buffer const * const tmp = masterBuffer();
1636 return tmp->masterBibInfo();
1637 return localBibInfo();
1641 BiblioInfo const & Buffer::localBibInfo() const
1643 checkBibInfoCache();
1648 void Buffer::checkBibInfoCache() const
1650 if (d->bibinfoCacheValid_) {
1651 support::FileNameList const & bibfilesCache = getBibfilesCache();
1652 // compare the cached timestamps with the actual ones.
1653 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1654 support::FileNameList::const_iterator en = bibfilesCache.end();
1655 for (; ei != en; ++ ei) {
1656 time_t lastw = ei->lastModified();
1657 if (lastw != d->bibfileStatus_[*ei]) {
1658 d->bibinfoCacheValid_ = false;
1659 d->bibfileStatus_[*ei] = lastw;
1665 if (!d->bibinfoCacheValid_) {
1666 d->bibinfo_.clear();
1667 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1668 it->fillWithBibKeys(d->bibinfo_, it);
1669 d->bibinfoCacheValid_ = true;
1674 bool Buffer::isDepClean(string const & name) const
1676 DepClean::const_iterator const it = d->dep_clean.find(name);
1677 if (it == d->dep_clean.end())
1683 void Buffer::markDepClean(string const & name)
1685 d->dep_clean[name] = true;
1689 bool Buffer::isExportableFormat(string const & format) const
1691 typedef vector<Format const *> Formats;
1693 formats = exportableFormats(true);
1694 Formats::const_iterator fit = formats.begin();
1695 Formats::const_iterator end = formats.end();
1696 for (; fit != end ; ++fit) {
1697 if ((*fit)->name() == format)
1704 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1707 // FIXME? if there is an Buffer LFUN that can be dispatched even
1708 // if internal, put a switch '(cmd.action)' here.
1714 switch (cmd.action) {
1716 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1717 flag.setOnOff(isReadonly());
1720 // FIXME: There is need for a command-line import.
1721 //case LFUN_BUFFER_IMPORT:
1723 case LFUN_BUFFER_AUTO_SAVE:
1726 case LFUN_BUFFER_EXPORT_CUSTOM:
1727 // FIXME: Nothing to check here?
1730 case LFUN_BUFFER_EXPORT: {
1731 docstring const arg = cmd.argument();
1732 enable = arg == "custom" || isExportable(to_utf8(arg));
1734 flag.message(bformat(
1735 _("Don't know how to export to format: %1$s"), arg));
1739 case LFUN_BUFFER_CHKTEX:
1740 enable = isLatex() && !lyxrc.chktex_command.empty();
1743 case LFUN_BUILD_PROGRAM:
1744 enable = isExportable("program");
1747 case LFUN_BRANCH_ACTIVATE:
1748 case LFUN_BRANCH_DEACTIVATE: {
1749 BranchList const & branchList = params().branchlist();
1750 docstring const branchName = cmd.argument();
1751 enable = !branchName.empty() && branchList.find(branchName);
1755 case LFUN_BRANCH_ADD:
1756 case LFUN_BRANCHES_RENAME:
1757 case LFUN_BUFFER_PRINT:
1758 // if no Buffer is present, then of course we won't be called!
1761 case LFUN_BUFFER_LANGUAGE:
1762 enable = !isReadonly();
1768 flag.setEnabled(enable);
1773 void Buffer::dispatch(string const & command, DispatchResult & result)
1775 return dispatch(lyxaction.lookupFunc(command), result);
1779 // NOTE We can end up here even if we have no GUI, because we are called
1780 // by LyX::exec to handled command-line requests. So we may need to check
1781 // whether we have a GUI or not. The boolean use_gui holds this information.
1782 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
1785 // FIXME? if there is an Buffer LFUN that can be dispatched even
1786 // if internal, put a switch '(cmd.action)' here.
1787 dr.dispatched(false);
1790 string const argument = to_utf8(func.argument());
1791 // We'll set this back to false if need be.
1792 bool dispatched = true;
1793 undo().beginUndoGroup();
1795 switch (func.action) {
1796 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1797 if (lyxvc().inUse())
1798 lyxvc().toggleReadOnly();
1800 setReadonly(!isReadonly());
1803 case LFUN_BUFFER_EXPORT: {
1804 bool success = doExport(argument, false);
1805 dr.setError(success);
1807 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
1812 case LFUN_BUILD_PROGRAM:
1813 doExport("program", true);
1816 case LFUN_BUFFER_CHKTEX:
1820 case LFUN_BUFFER_EXPORT_CUSTOM: {
1822 string command = split(argument, format_name, ' ');
1823 Format const * format = formats.getFormat(format_name);
1825 lyxerr << "Format \"" << format_name
1826 << "\" not recognized!"
1831 // The name of the file created by the conversion process
1834 // Output to filename
1835 if (format->name() == "lyx") {
1836 string const latexname = latexName(false);
1837 filename = changeExtension(latexname,
1838 format->extension());
1839 filename = addName(temppath(), filename);
1841 if (!writeFile(FileName(filename)))
1845 doExport(format_name, true, filename);
1848 // Substitute $$FName for filename
1849 if (!contains(command, "$$FName"))
1850 command = "( " + command + " ) < $$FName";
1851 command = subst(command, "$$FName", filename);
1853 // Execute the command in the background
1855 call.startscript(Systemcall::DontWait, command);
1859 // FIXME: There is need for a command-line import.
1861 case LFUN_BUFFER_IMPORT:
1866 case LFUN_BUFFER_AUTO_SAVE:
1870 case LFUN_BRANCH_ADD: {
1871 docstring const branch_name = func.argument();
1872 if (branch_name.empty()) {
1876 BranchList & branch_list = params().branchlist();
1877 Branch * branch = branch_list.find(branch_name);
1879 LYXERR0("Branch " << branch_name << " already exists.");
1881 docstring const msg =
1882 bformat(_("Branch \"%1$s\" already exists."), branch_name);
1885 branch_list.add(branch_name);
1886 branch = branch_list.find(branch_name);
1887 string const x11hexname = X11hexname(branch->color());
1888 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
1889 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
1891 dr.update(Update::Force);
1896 case LFUN_BRANCH_ACTIVATE:
1897 case LFUN_BRANCH_DEACTIVATE: {
1898 BranchList & branchList = params().branchlist();
1899 docstring const branchName = func.argument();
1900 // the case without a branch name is handled elsewhere
1901 if (branchName.empty()) {
1905 Branch * branch = branchList.find(branchName);
1907 LYXERR0("Branch " << branchName << " does not exist.");
1909 docstring const msg =
1910 bformat(_("Branch \"%1$s\" does not exist."), branchName);
1913 branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1915 dr.update(Update::Force);
1920 case LFUN_BRANCHES_RENAME: {
1921 if (func.argument().empty())
1924 docstring const oldname = from_utf8(func.getArg(0));
1925 docstring const newname = from_utf8(func.getArg(1));
1926 InsetIterator it = inset_iterator_begin(inset());
1927 InsetIterator const end = inset_iterator_end(inset());
1928 bool success = false;
1929 for (; it != end; ++it) {
1930 if (it->lyxCode() == BRANCH_CODE) {
1931 InsetBranch & ins = static_cast<InsetBranch &>(*it);
1932 if (ins.branch() == oldname) {
1933 undo().recordUndo(it);
1934 ins.rename(newname);
1939 if (it->lyxCode() == INCLUDE_CODE) {
1940 // get buffer of external file
1941 InsetInclude const & ins =
1942 static_cast<InsetInclude const &>(*it);
1943 Buffer * child = ins.getChildBuffer();
1946 child->dispatch(func, dr);
1951 dr.update(Update::Force);
1955 case LFUN_BUFFER_PRINT: {
1956 // we'll assume there's a problem until we succeed
1958 string target = func.getArg(0);
1959 string target_name = func.getArg(1);
1960 string command = func.getArg(2);
1963 || target_name.empty()
1964 || command.empty()) {
1965 LYXERR0("Unable to parse " << func.argument());
1966 docstring const msg =
1967 bformat(_("Unable to parse \"%1$s\""), func.argument());
1971 if (target != "printer" && target != "file") {
1972 LYXERR0("Unrecognized target \"" << target << '"');
1973 docstring const msg =
1974 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
1979 if (!doExport("dvi", true)) {
1980 showPrintError(absFileName());
1981 dr.setMessage(_("Error exporting to DVI."));
1985 // Push directory path.
1986 string const path = temppath();
1987 // Prevent the compiler from optimizing away p
1991 // there are three cases here:
1992 // 1. we print to a file
1993 // 2. we print directly to a printer
1994 // 3. we print using a spool command (print to file first)
1997 string const dviname = changeExtension(latexName(true), "dvi");
1999 if (target == "printer") {
2000 if (!lyxrc.print_spool_command.empty()) {
2001 // case 3: print using a spool
2002 string const psname = changeExtension(dviname,".ps");
2003 command += ' ' + lyxrc.print_to_file
2006 + quoteName(dviname);
2008 string command2 = lyxrc.print_spool_command + ' ';
2009 if (target_name != "default") {
2010 command2 += lyxrc.print_spool_printerprefix
2014 command2 += quoteName(psname);
2016 // If successful, then spool command
2017 res = one.startscript(Systemcall::Wait, command);
2020 // If there's no GUI, we have to wait on this command. Otherwise,
2021 // LyX deletes the temporary directory, and with it the spooled
2022 // file, before it can be printed!!
2023 Systemcall::Starttype stype = use_gui ?
2024 Systemcall::DontWait : Systemcall::Wait;
2025 res = one.startscript(stype, command2);
2028 // case 2: print directly to a printer
2029 if (target_name != "default")
2030 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2032 Systemcall::Starttype stype = use_gui ?
2033 Systemcall::DontWait : Systemcall::Wait;
2034 res = one.startscript(stype, command + quoteName(dviname));
2038 // case 1: print to a file
2039 FileName const filename(makeAbsPath(target_name, filePath()));
2040 FileName const dvifile(makeAbsPath(dviname, path));
2041 if (filename.exists()) {
2042 docstring text = bformat(
2043 _("The file %1$s already exists.\n\n"
2044 "Do you want to overwrite that file?"),
2045 makeDisplayPath(filename.absFilename()));
2046 if (Alert::prompt(_("Overwrite file?"),
2047 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2050 command += ' ' + lyxrc.print_to_file
2051 + quoteName(filename.toFilesystemEncoding())
2053 + quoteName(dvifile.toFilesystemEncoding());
2055 Systemcall::Starttype stype = use_gui ?
2056 Systemcall::DontWait : Systemcall::Wait;
2057 res = one.startscript(stype, command);
2063 dr.setMessage(_("Error running external commands."));
2064 showPrintError(absFileName());
2069 case LFUN_BUFFER_LANGUAGE: {
2070 Language const * oldL = params().language;
2071 Language const * newL = languages.getLanguage(argument);
2072 if (!newL || oldL == newL)
2074 if (oldL->rightToLeft() == newL->rightToLeft() && !isMultiLingual())
2075 changeLanguage(oldL, newL);
2083 dr.dispatched(dispatched);
2084 undo().endUndoGroup();
2088 void Buffer::changeLanguage(Language const * from, Language const * to)
2090 LASSERT(from, /**/);
2093 for_each(par_iterator_begin(),
2095 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2099 bool Buffer::isMultiLingual() const
2101 ParConstIterator end = par_iterator_end();
2102 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2103 if (it->isMultiLingual(params()))
2110 DocIterator Buffer::getParFromID(int const id) const
2112 Buffer * buf = const_cast<Buffer *>(this);
2114 // John says this is called with id == -1 from undo
2115 lyxerr << "getParFromID(), id: " << id << endl;
2116 return doc_iterator_end(buf);
2119 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2120 if (it.paragraph().id() == id)
2123 return doc_iterator_end(buf);
2127 bool Buffer::hasParWithID(int const id) const
2129 return !getParFromID(id).atEnd();
2133 ParIterator Buffer::par_iterator_begin()
2135 return ParIterator(doc_iterator_begin(this));
2139 ParIterator Buffer::par_iterator_end()
2141 return ParIterator(doc_iterator_end(this));
2145 ParConstIterator Buffer::par_iterator_begin() const
2147 return ParConstIterator(doc_iterator_begin(this));
2151 ParConstIterator Buffer::par_iterator_end() const
2153 return ParConstIterator(doc_iterator_end(this));
2157 Language const * Buffer::language() const
2159 return params().language;
2163 docstring const Buffer::B_(string const & l10n) const
2165 return params().B_(l10n);
2169 bool Buffer::isClean() const
2171 return d->lyx_clean;
2175 bool Buffer::isBakClean() const
2177 return d->bak_clean;
2181 bool Buffer::isExternallyModified(CheckMethod method) const
2183 LASSERT(d->filename.exists(), /**/);
2184 // if method == timestamp, check timestamp before checksum
2185 return (method == checksum_method
2186 || d->timestamp_ != d->filename.lastModified())
2187 && d->checksum_ != d->filename.checksum();
2191 void Buffer::saveCheckSum(FileName const & file) const
2193 if (file.exists()) {
2194 d->timestamp_ = file.lastModified();
2195 d->checksum_ = file.checksum();
2197 // in the case of save to a new file.
2204 void Buffer::markClean() const
2206 if (!d->lyx_clean) {
2207 d->lyx_clean = true;
2210 // if the .lyx file has been saved, we don't need an
2212 d->bak_clean = true;
2216 void Buffer::markBakClean() const
2218 d->bak_clean = true;
2222 void Buffer::setUnnamed(bool flag)
2228 bool Buffer::isUnnamed() const
2235 /// Don't check unnamed, here: isInternal() is used in
2236 /// newBuffer(), where the unnamed flag has not been set by anyone
2237 /// yet. Also, for an internal buffer, there should be no need for
2238 /// retrieving fileName() nor for checking if it is unnamed or not.
2239 bool Buffer::isInternal() const
2241 return fileName().extension() == "internal";
2245 void Buffer::markDirty()
2248 d->lyx_clean = false;
2251 d->bak_clean = false;
2253 DepClean::iterator it = d->dep_clean.begin();
2254 DepClean::const_iterator const end = d->dep_clean.end();
2256 for (; it != end; ++it)
2261 FileName Buffer::fileName() const
2267 string Buffer::absFileName() const
2269 return d->filename.absFilename();
2273 string Buffer::filePath() const
2275 return d->filename.onlyPath().absFilename() + "/";
2279 bool Buffer::isReadonly() const
2281 return d->read_only;
2285 void Buffer::setParent(Buffer const * buffer)
2287 // Avoids recursive include.
2288 d->setParent(buffer == this ? 0 : buffer);
2293 Buffer const * Buffer::parent() const
2299 void Buffer::collectRelatives(BufferSet & bufs) const
2303 parent()->collectRelatives(bufs);
2305 // loop over children
2306 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2307 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2308 for (; it != end; ++it)
2309 bufs.insert(const_cast<Buffer *>(it->first));
2313 std::vector<Buffer const *> Buffer::allRelatives() const
2316 collectRelatives(bufs);
2317 BufferSet::iterator it = bufs.begin();
2318 std::vector<Buffer const *> ret;
2319 for (; it != bufs.end(); ++it)
2325 Buffer const * Buffer::masterBuffer() const
2327 Buffer const * const pbuf = d->parent();
2331 return pbuf->masterBuffer();
2335 bool Buffer::isChild(Buffer * child) const
2337 return d->children_positions.find(child) != d->children_positions.end();
2341 DocIterator Buffer::firstChildPosition(Buffer const * child)
2343 Impl::BufferPositionMap::iterator it;
2344 it = d->children_positions.find(child);
2345 if (it == d->children_positions.end())
2346 return DocIterator(this);
2351 void Buffer::getChildren(std::vector<Buffer *> & clist, bool grand_children) const
2353 // loop over children
2354 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2355 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2356 for (; it != end; ++it) {
2357 Buffer * child = const_cast<Buffer *>(it->first);
2358 clist.push_back(child);
2359 if (grand_children) {
2360 // there might be grandchildren
2361 std::vector<Buffer *> glist = child->getChildren();
2362 for (vector<Buffer *>::const_iterator git = glist.begin();
2363 git != glist.end(); ++git)
2364 clist.push_back(*git);
2370 std::vector<Buffer *> Buffer::getChildren(bool grand_children) const
2372 std::vector<Buffer *> v;
2373 getChildren(v, grand_children);
2378 template<typename M>
2379 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
2384 typename M::iterator it = m.lower_bound(x);
2385 if (it == m.begin())
2393 MacroData const * Buffer::getBufferMacro(docstring const & name,
2394 DocIterator const & pos) const
2396 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2398 // if paragraphs have no macro context set, pos will be empty
2402 // we haven't found anything yet
2403 DocIterator bestPos = par_iterator_begin();
2404 MacroData const * bestData = 0;
2406 // find macro definitions for name
2407 Impl::NamePositionScopeMacroMap::iterator nameIt
2408 = d->macros.find(name);
2409 if (nameIt != d->macros.end()) {
2410 // find last definition in front of pos or at pos itself
2411 Impl::PositionScopeMacroMap::const_iterator it
2412 = greatest_below(nameIt->second, pos);
2413 if (it != nameIt->second.end()) {
2415 // scope ends behind pos?
2416 if (pos < it->second.first) {
2417 // Looks good, remember this. If there
2418 // is no external macro behind this,
2419 // we found the right one already.
2420 bestPos = it->first;
2421 bestData = &it->second.second;
2425 // try previous macro if there is one
2426 if (it == nameIt->second.begin())
2433 // find macros in included files
2434 Impl::PositionScopeBufferMap::const_iterator it
2435 = greatest_below(d->position_to_children, pos);
2436 if (it == d->position_to_children.end())
2437 // no children before
2441 // do we know something better (i.e. later) already?
2442 if (it->first < bestPos )
2445 // scope ends behind pos?
2446 if (pos < it->second.first) {
2447 // look for macro in external file
2448 d->macro_lock = true;
2449 MacroData const * data
2450 = it->second.second->getMacro(name, false);
2451 d->macro_lock = false;
2453 bestPos = it->first;
2459 // try previous file if there is one
2460 if (it == d->position_to_children.begin())
2465 // return the best macro we have found
2470 MacroData const * Buffer::getMacro(docstring const & name,
2471 DocIterator const & pos, bool global) const
2476 // query buffer macros
2477 MacroData const * data = getBufferMacro(name, pos);
2481 // If there is a master buffer, query that
2482 Buffer const * const pbuf = d->parent();
2484 d->macro_lock = true;
2485 MacroData const * macro = pbuf->getMacro(
2486 name, *this, false);
2487 d->macro_lock = false;
2493 data = MacroTable::globalMacros().get(name);
2502 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2504 // set scope end behind the last paragraph
2505 DocIterator scope = par_iterator_begin();
2506 scope.pit() = scope.lastpit() + 1;
2508 return getMacro(name, scope, global);
2512 MacroData const * Buffer::getMacro(docstring const & name,
2513 Buffer const & child, bool global) const
2515 // look where the child buffer is included first
2516 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2517 if (it == d->children_positions.end())
2520 // check for macros at the inclusion position
2521 return getMacro(name, it->second, global);
2525 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
2527 pit_type lastpit = it.lastpit();
2529 // look for macros in each paragraph
2530 while (it.pit() <= lastpit) {
2531 Paragraph & par = it.paragraph();
2533 // iterate over the insets of the current paragraph
2534 InsetList const & insets = par.insetList();
2535 InsetList::const_iterator iit = insets.begin();
2536 InsetList::const_iterator end = insets.end();
2537 for (; iit != end; ++iit) {
2538 it.pos() = iit->pos;
2540 // is it a nested text inset?
2541 if (iit->inset->asInsetText()) {
2542 // Inset needs its own scope?
2543 InsetText const * itext = iit->inset->asInsetText();
2544 bool newScope = itext->isMacroScope();
2546 // scope which ends just behind the inset
2547 DocIterator insetScope = it;
2550 // collect macros in inset
2551 it.push_back(CursorSlice(*iit->inset));
2552 updateMacros(it, newScope ? insetScope : scope);
2557 // is it an external file?
2558 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2559 // get buffer of external file
2560 InsetInclude const & inset =
2561 static_cast<InsetInclude const &>(*iit->inset);
2562 d->macro_lock = true;
2563 Buffer * child = inset.getChildBuffer();
2564 d->macro_lock = false;
2568 // register its position, but only when it is
2569 // included first in the buffer
2570 if (d->children_positions.find(child) ==
2571 d->children_positions.end())
2572 d->children_positions[child] = it;
2574 // register child with its scope
2575 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
2579 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2583 MathMacroTemplate & macroTemplate =
2584 static_cast<MathMacroTemplate &>(*iit->inset);
2585 MacroContext mc(this, it);
2586 macroTemplate.updateToContext(mc);
2589 bool valid = macroTemplate.validMacro();
2590 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2591 // then the BufferView's cursor will be invalid in
2592 // some cases which leads to crashes.
2597 // FIXME (Abdel), I don't understandt why we pass 'it' here
2598 // instead of 'macroTemplate' defined above... is this correct?
2599 d->macros[macroTemplate.name()][it] =
2600 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(this), it));
2610 void Buffer::updateMacros() const
2615 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2617 // start with empty table
2619 d->children_positions.clear();
2620 d->position_to_children.clear();
2622 // Iterate over buffer, starting with first paragraph
2623 // The scope must be bigger than any lookup DocIterator
2624 // later. For the global lookup, lastpit+1 is used, hence
2625 // we use lastpit+2 here.
2626 DocIterator it = par_iterator_begin();
2627 DocIterator outerScope = it;
2628 outerScope.pit() = outerScope.lastpit() + 2;
2629 updateMacros(it, outerScope);
2633 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
2635 InsetIterator it = inset_iterator_begin(inset());
2636 InsetIterator const end = inset_iterator_end(inset());
2637 for (; it != end; ++it) {
2638 if (it->lyxCode() == BRANCH_CODE) {
2639 InsetBranch & br = static_cast<InsetBranch &>(*it);
2640 docstring const name = br.branch();
2641 if (!from_master && !params().branchlist().find(name))
2642 result.push_back(name);
2643 else if (from_master && !masterBuffer()->params().branchlist().find(name))
2644 result.push_back(name);
2647 if (it->lyxCode() == INCLUDE_CODE) {
2648 // get buffer of external file
2649 InsetInclude const & ins =
2650 static_cast<InsetInclude const &>(*it);
2651 Buffer * child = ins.getChildBuffer();
2654 child->getUsedBranches(result, true);
2657 // remove duplicates
2662 void Buffer::updateMacroInstances() const
2664 LYXERR(Debug::MACROS, "updateMacroInstances for "
2665 << d->filename.onlyFileName());
2666 DocIterator it = doc_iterator_begin(this);
2668 DocIterator const end = doc_iterator_end(this);
2669 for (; it != end; it.forwardInset()) {
2670 // look for MathData cells in InsetMathNest insets
2671 InsetMath * minset = it.nextInset()->asInsetMath();
2675 // update macro in all cells of the InsetMathNest
2676 DocIterator::idx_type n = minset->nargs();
2677 MacroContext mc = MacroContext(this, it);
2678 for (DocIterator::idx_type i = 0; i < n; ++i) {
2679 MathData & data = minset->cell(i);
2680 data.updateMacros(0, mc);
2686 void Buffer::listMacroNames(MacroNameSet & macros) const
2691 d->macro_lock = true;
2693 // loop over macro names
2694 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2695 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2696 for (; nameIt != nameEnd; ++nameIt)
2697 macros.insert(nameIt->first);
2699 // loop over children
2700 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2701 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2702 for (; it != end; ++it)
2703 it->first->listMacroNames(macros);
2706 Buffer const * const pbuf = d->parent();
2708 pbuf->listMacroNames(macros);
2710 d->macro_lock = false;
2714 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2716 Buffer const * const pbuf = d->parent();
2721 pbuf->listMacroNames(names);
2724 MacroNameSet::iterator it = names.begin();
2725 MacroNameSet::iterator end = names.end();
2726 for (; it != end; ++it) {
2728 MacroData const * data =
2729 pbuf->getMacro(*it, *this, false);
2731 macros.insert(data);
2733 // we cannot access the original MathMacroTemplate anymore
2734 // here to calls validate method. So we do its work here manually.
2735 // FIXME: somehow make the template accessible here.
2736 if (data->optionals() > 0)
2737 features.require("xargs");
2743 Buffer::References & Buffer::references(docstring const & label)
2746 return const_cast<Buffer *>(masterBuffer())->references(label);
2748 RefCache::iterator it = d->ref_cache_.find(label);
2749 if (it != d->ref_cache_.end())
2750 return it->second.second;
2752 static InsetLabel const * dummy_il = 0;
2753 static References const dummy_refs;
2754 it = d->ref_cache_.insert(
2755 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2756 return it->second.second;
2760 Buffer::References const & Buffer::references(docstring const & label) const
2762 return const_cast<Buffer *>(this)->references(label);
2766 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2768 masterBuffer()->d->ref_cache_[label].first = il;
2772 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2774 return masterBuffer()->d->ref_cache_[label].first;
2778 void Buffer::clearReferenceCache() const
2781 d->ref_cache_.clear();
2785 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2788 //FIXME: This does not work for child documents yet.
2789 LASSERT(code == CITE_CODE, /**/);
2790 // Check if the label 'from' appears more than once
2791 vector<docstring> labels;
2793 BiblioInfo const & keys = masterBibInfo();
2794 BiblioInfo::const_iterator bit = keys.begin();
2795 BiblioInfo::const_iterator bend = keys.end();
2797 for (; bit != bend; ++bit)
2799 labels.push_back(bit->first);
2802 if (count(labels.begin(), labels.end(), from) > 1)
2805 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2806 if (it->lyxCode() == code) {
2807 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2808 docstring const oldValue = inset.getParam(paramName);
2809 if (oldValue == from)
2810 inset.setParam(paramName, to);
2816 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2817 pit_type par_end, bool full_source) const
2819 OutputParams runparams(¶ms().encoding());
2820 runparams.nice = true;
2821 runparams.flavor = params().useXetex ?
2822 OutputParams::XETEX : OutputParams::LATEX;
2823 runparams.linelen = lyxrc.plaintext_linelen;
2824 // No side effect of file copying and image conversion
2825 runparams.dryrun = true;
2828 os << "% " << _("Preview source code") << "\n\n";
2830 d->texrow.newline();
2831 d->texrow.newline();
2833 writeDocBookSource(os, absFileName(), runparams, false);
2835 // latex or literate
2836 writeLaTeXSource(os, string(), runparams, true, true);
2838 runparams.par_begin = par_begin;
2839 runparams.par_end = par_end;
2840 if (par_begin + 1 == par_end) {
2842 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2846 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2847 convert<docstring>(par_begin),
2848 convert<docstring>(par_end - 1))
2855 // output paragraphs
2857 docbookParagraphs(text(), *this, os, runparams);
2859 // latex or literate
2860 latexParagraphs(*this, text(), os, texrow, runparams);
2865 ErrorList & Buffer::errorList(string const & type) const
2867 static ErrorList emptyErrorList;
2868 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2869 if (I == d->errorLists.end())
2870 return emptyErrorList;
2876 void Buffer::updateTocItem(std::string const & type,
2877 DocIterator const & dit) const
2880 gui_->updateTocItem(type, dit);
2884 void Buffer::structureChanged() const
2887 gui_->structureChanged();
2891 void Buffer::errors(string const & err, bool from_master) const
2894 gui_->errors(err, from_master);
2898 void Buffer::message(docstring const & msg) const
2905 void Buffer::setBusy(bool on) const
2912 void Buffer::setReadOnly(bool on) const
2915 d->wa_->setReadOnly(on);
2919 void Buffer::updateTitles() const
2922 d->wa_->updateTitles();
2926 void Buffer::resetAutosaveTimers() const
2929 gui_->resetAutosaveTimers();
2933 bool Buffer::hasGuiDelegate() const
2939 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2948 class AutoSaveBuffer : public ForkedProcess {
2951 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2952 : buffer_(buffer), fname_(fname) {}
2954 virtual boost::shared_ptr<ForkedProcess> clone() const
2956 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2961 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2962 from_utf8(fname_.absFilename())));
2963 return run(DontWait);
2967 virtual int generateChild();
2969 Buffer const & buffer_;
2974 int AutoSaveBuffer::generateChild()
2976 #if defined(__APPLE__)
2977 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
2978 * We should use something else like threads.
2980 * Since I do not know how to determine at run time what is the OS X
2981 * version, I just disable forking altogether for now (JMarc)
2983 pid_t const pid = -1;
2985 // tmp_ret will be located (usually) in /tmp
2986 // will that be a problem?
2987 // Note that this calls ForkedCalls::fork(), so it's
2988 // ok cross-platform.
2989 pid_t const pid = fork();
2990 // If you want to debug the autosave
2991 // you should set pid to -1, and comment out the fork.
2992 if (pid != 0 && pid != -1)
2996 // pid = -1 signifies that lyx was unable
2997 // to fork. But we will do the save
2999 bool failed = false;
3000 FileName const tmp_ret = FileName::tempName("lyxauto");
3001 if (!tmp_ret.empty()) {
3002 buffer_.writeFile(tmp_ret);
3003 // assume successful write of tmp_ret
3004 if (!tmp_ret.moveTo(fname_))
3010 // failed to write/rename tmp_ret so try writing direct
3011 if (!buffer_.writeFile(fname_)) {
3012 // It is dangerous to do this in the child,
3013 // but safe in the parent, so...
3014 if (pid == -1) // emit message signal.
3015 buffer_.message(_("Autosave failed!"));
3019 if (pid == 0) // we are the child so...
3028 FileName Buffer::getAutosaveFilename() const
3030 // if the document is unnamed try to save in the backup dir, else
3031 // in the default document path, and as a last try in the filePath,
3032 // which will most often be the temporary directory
3035 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3036 : lyxrc.backupdir_path;
3037 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3040 string const fname = "#" + d->filename.onlyFileName() + "#";
3041 return makeAbsPath(fname, fpath);
3045 void Buffer::removeAutosaveFile() const
3047 FileName const f = getAutosaveFilename();
3053 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3055 FileName const newauto = getAutosaveFilename();
3056 if (!(oldauto == newauto || oldauto.moveTo(newauto)))
3057 LYXERR0("Unable to remove autosave file `" << oldauto << "'!");
3061 // Perfect target for a thread...
3062 void Buffer::autoSave() const
3064 if (isBakClean() || isReadonly()) {
3065 // We don't save now, but we'll try again later
3066 resetAutosaveTimers();
3070 // emit message signal.
3071 message(_("Autosaving current document..."));
3072 AutoSaveBuffer autosave(*this, getAutosaveFilename());
3076 resetAutosaveTimers();
3080 string Buffer::bufferFormat() const
3082 string format = params().documentClass().outputFormat();
3083 if (format == "latex") {
3084 if (params().useXetex)
3086 if (params().encoding().package() == Encoding::japanese)
3093 string Buffer::getDefaultOutputFormat() const
3095 if (!params().defaultOutputFormat.empty()
3096 && params().defaultOutputFormat != "default")
3097 return params().defaultOutputFormat;
3098 typedef vector<Format const *> Formats;
3099 Formats formats = exportableFormats(true);
3102 || params().useXetex
3103 || params().encoding().package() == Encoding::japanese) {
3104 if (formats.empty())
3106 // return the first we find
3107 return formats.front()->name();
3109 return lyxrc.default_view_format;
3114 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3115 string & result_file) const
3117 string backend_format;
3118 OutputParams runparams(¶ms().encoding());
3119 runparams.flavor = OutputParams::LATEX;
3120 runparams.linelen = lyxrc.plaintext_linelen;
3121 vector<string> backs = backends();
3122 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3123 // Get shortest path to format
3124 Graph::EdgePath path;
3125 for (vector<string>::const_iterator it = backs.begin();
3126 it != backs.end(); ++it) {
3127 Graph::EdgePath p = theConverters().getPath(*it, format);
3128 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3129 backend_format = *it;
3134 if (!put_in_tempdir) {
3135 // Only show this alert if this is an export to a non-temporary
3136 // file (not for previewing).
3137 Alert::error(_("Couldn't export file"), bformat(
3138 _("No information for exporting the format %1$s."),
3139 formats.prettyName(format)));
3143 runparams.flavor = theConverters().getFlavor(path);
3146 backend_format = format;
3147 // FIXME: Don't hardcode format names here, but use a flag
3148 if (backend_format == "pdflatex")
3149 runparams.flavor = OutputParams::PDFLATEX;
3152 string filename = latexName(false);
3153 filename = addName(temppath(), filename);
3154 filename = changeExtension(filename,
3155 formats.extension(backend_format));
3158 updateMacroInstances();
3160 // Plain text backend
3161 if (backend_format == "text") {
3162 runparams.flavor = OutputParams::TEXT;
3163 writePlaintextFile(*this, FileName(filename), runparams);
3166 else if (backend_format == "xhtml") {
3167 runparams.flavor = OutputParams::HTML;
3168 makeLyXHTMLFile(FileName(filename), runparams);
3169 } else if (backend_format == "lyx")
3170 writeFile(FileName(filename));
3172 else if (isDocBook()) {
3173 runparams.nice = !put_in_tempdir;
3174 makeDocBookFile(FileName(filename), runparams);
3177 else if (backend_format == format) {
3178 runparams.nice = true;
3179 if (!makeLaTeXFile(FileName(filename), string(), runparams))
3181 } else if (!lyxrc.tex_allows_spaces
3182 && contains(filePath(), ' ')) {
3183 Alert::error(_("File name error"),
3184 _("The directory path to the document cannot contain spaces."));
3187 runparams.nice = false;
3188 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
3192 string const error_type = (format == "program")
3193 ? "Build" : bufferFormat();
3194 ErrorList & error_list = d->errorLists[error_type];
3195 string const ext = formats.extension(format);
3196 FileName const tmp_result_file(changeExtension(filename, ext));
3197 bool const success = theConverters().convert(this, FileName(filename),
3198 tmp_result_file, FileName(absFileName()), backend_format, format,
3200 // Emit the signal to show the error list.
3201 if (format != backend_format) {
3203 // also to the children, in case of master-buffer-view
3204 std::vector<Buffer *> clist = getChildren();
3205 for (vector<Buffer *>::const_iterator cit = clist.begin();
3206 cit != clist.end(); ++cit)
3207 (*cit)->errors(error_type, true);
3212 if (d->cloned_buffer_) {
3213 // Enable reverse dvi or pdf to work by copying back the texrow
3214 // object to the cloned buffer.
3215 // FIXME: There is a possibility of concurrent access to texrow
3216 // here from the main GUI thread that should be securized.
3217 d->cloned_buffer_->d->texrow = d->texrow;
3220 if (put_in_tempdir) {
3221 result_file = tmp_result_file.absFilename();
3225 result_file = changeExtension(exportFileName().absFilename(), ext);
3226 // We need to copy referenced files (e. g. included graphics
3227 // if format == "dvi") to the result dir.
3228 vector<ExportedFile> const files =
3229 runparams.exportdata->externalFiles(format);
3230 string const dest = onlyPath(result_file);
3231 CopyStatus status = SUCCESS;
3232 for (vector<ExportedFile>::const_iterator it = files.begin();
3233 it != files.end() && status != CANCEL; ++it) {
3234 string const fmt = formats.getFormatFromFile(it->sourceName);
3235 status = copyFile(fmt, it->sourceName,
3236 makeAbsPath(it->exportName, dest),
3237 it->exportName, status == FORCE);
3239 if (status == CANCEL) {
3240 message(_("Document export cancelled."));
3241 } else if (tmp_result_file.exists()) {
3242 // Finally copy the main file
3243 status = copyFile(format, tmp_result_file,
3244 FileName(result_file), result_file,
3246 message(bformat(_("Document exported as %1$s "
3248 formats.prettyName(format),
3249 makeDisplayPath(result_file)));
3251 // This must be a dummy converter like fax (bug 1888)
3252 message(bformat(_("Document exported as %1$s"),
3253 formats.prettyName(format)));
3260 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
3263 return doExport(format, put_in_tempdir, result_file);
3267 bool Buffer::preview(string const & format) const
3270 if (!doExport(format, true, result_file))
3272 return formats.view(*this, FileName(result_file), format);
3276 bool Buffer::isExportable(string const & format) const
3278 vector<string> backs = backends();
3279 for (vector<string>::const_iterator it = backs.begin();
3280 it != backs.end(); ++it)
3281 if (theConverters().isReachable(*it, format))
3287 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
3289 vector<string> const backs = backends();
3290 vector<Format const *> result =
3291 theConverters().getReachable(backs[0], only_viewable, true);
3292 for (vector<string>::const_iterator it = backs.begin() + 1;
3293 it != backs.end(); ++it) {
3294 vector<Format const *> r =
3295 theConverters().getReachable(*it, only_viewable, false);
3296 result.insert(result.end(), r.begin(), r.end());
3302 vector<string> Buffer::backends() const
3305 v.push_back(bufferFormat());
3306 // FIXME: Don't hardcode format names here, but use a flag
3307 if (v.back() == "latex")
3308 v.push_back("pdflatex");
3309 v.push_back("xhtml");
3310 v.push_back("text");
3316 bool Buffer::readFileHelper(FileName const & s)
3318 // File information about normal file
3320 docstring const file = makeDisplayPath(s.absFilename(), 50);
3321 docstring text = bformat(_("The specified document\n%1$s"
3322 "\ncould not be read."), file);
3323 Alert::error(_("Could not read document"), text);
3327 // Check if emergency save file exists and is newer.
3328 FileName const e(s.absFilename() + ".emergency");
3330 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
3331 docstring const file = makeDisplayPath(s.absFilename(), 20);
3332 docstring const text =
3333 bformat(_("An emergency save of the document "
3335 "Recover emergency save?"), file);
3336 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
3337 _("&Recover"), _("&Load Original"),
3341 // the file is not saved if we load the emergency file.
3346 if ((res = readFile(e)) == success)
3347 str = _("Document was successfully recovered.");
3349 str = _("Document was NOT successfully recovered.");
3350 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3351 from_utf8(e.absFilename()));
3353 if (!Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3354 _("&Remove"), _("&Keep it"))) {
3357 Alert::warning(_("Emergency file deleted"),
3358 _("Do not forget to save your file now!"), true);
3363 if (!Alert::prompt(_("Delete emergency file?"),
3364 _("Remove emergency file now?"), 1, 1,
3365 _("&Remove"), _("&Keep it")))
3373 // Now check if autosave file is newer.
3374 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
3376 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
3377 docstring const file = makeDisplayPath(s.absFilename(), 20);
3378 docstring const text =
3379 bformat(_("The backup of the document "
3380 "%1$s is newer.\n\nLoad the "
3381 "backup instead?"), file);
3382 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
3383 _("&Load backup"), _("Load &original"),
3387 // the file is not saved if we load the autosave file.
3391 // Here we delete the autosave
3402 bool Buffer::loadLyXFile(FileName const & s)
3404 if (s.isReadableFile()) {
3405 if (readFileHelper(s)) {
3406 lyxvc().file_found_hook(s);
3407 if (!s.isWritable())
3412 docstring const file = makeDisplayPath(s.absFilename(), 20);
3413 // Here we probably should run
3414 if (LyXVC::file_not_found_hook(s)) {
3415 docstring const text =
3416 bformat(_("Do you want to retrieve the document"
3417 " %1$s from version control?"), file);
3418 int const ret = Alert::prompt(_("Retrieve from version control?"),
3419 text, 0, 1, _("&Retrieve"), _("&Cancel"));
3422 // How can we know _how_ to do the checkout?
3423 // With the current VC support it has to be,
3424 // a RCS file since CVS do not have special ,v files.
3426 return loadLyXFile(s);
3434 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3436 TeXErrors::Errors::const_iterator cit = terr.begin();
3437 TeXErrors::Errors::const_iterator end = terr.end();
3439 for (; cit != end; ++cit) {
3442 int errorRow = cit->error_in_line;
3443 bool found = d->texrow.getIdFromRow(errorRow, id_start,
3449 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
3450 } while (found && id_start == id_end && pos_start == pos_end);
3452 errorList.push_back(ErrorItem(cit->error_desc,
3453 cit->error_text, id_start, pos_start, pos_end));
3458 void Buffer::setBuffersForInsets() const
3460 inset().setBuffer(const_cast<Buffer &>(*this));
3464 void Buffer::updateLabels(UpdateScope scope, bool out) const
3466 // Use the master text class also for child documents
3467 Buffer const * const master = masterBuffer();
3468 DocumentClass const & textclass = master->params().documentClass();
3470 // keep the buffers to be children in this set. If the call from the
3471 // master comes back we can see which of them were actually seen (i.e.
3472 // via an InsetInclude). The remaining ones in the set need still be updated.
3473 static std::set<Buffer const *> bufToUpdate;
3474 if (scope == UpdateMaster) {
3475 // If this is a child document start with the master
3476 if (master != this) {
3477 bufToUpdate.insert(this);
3478 master->updateLabels(UpdateMaster, out);
3479 // Do this here in case the master has no gui associated with it. Then,
3480 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3484 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3485 if (bufToUpdate.find(this) == bufToUpdate.end())
3489 // start over the counters in the master
3490 textclass.counters().reset();
3493 // update will be done below for this buffer
3494 bufToUpdate.erase(this);
3496 // update all caches
3497 clearReferenceCache();
3500 Buffer & cbuf = const_cast<Buffer &>(*this);
3502 LASSERT(!text().paragraphs().empty(), /**/);
3505 ParIterator parit = cbuf.par_iterator_begin();
3506 updateLabels(parit, out);
3509 // TocBackend update will be done later.
3512 cbuf.tocBackend().update();
3513 if (scope == UpdateMaster)
3514 cbuf.structureChanged();
3518 static depth_type getDepth(DocIterator const & it)
3520 depth_type depth = 0;
3521 for (size_t i = 0 ; i < it.depth() ; ++i)
3522 if (!it[i].inset().inMathed())
3523 depth += it[i].paragraph().getDepth() + 1;
3524 // remove 1 since the outer inset does not count
3528 static depth_type getItemDepth(ParIterator const & it)
3530 Paragraph const & par = *it;
3531 LabelType const labeltype = par.layout().labeltype;
3533 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3536 // this will hold the lowest depth encountered up to now.
3537 depth_type min_depth = getDepth(it);
3538 ParIterator prev_it = it;
3541 --prev_it.top().pit();
3543 // start of nested inset: go to outer par
3545 if (prev_it.empty()) {
3546 // start of document: nothing to do
3551 // We search for the first paragraph with same label
3552 // that is not more deeply nested.
3553 Paragraph & prev_par = *prev_it;
3554 depth_type const prev_depth = getDepth(prev_it);
3555 if (labeltype == prev_par.layout().labeltype) {
3556 if (prev_depth < min_depth)
3557 return prev_par.itemdepth + 1;
3558 if (prev_depth == min_depth)
3559 return prev_par.itemdepth;
3561 min_depth = min(min_depth, prev_depth);
3562 // small optimization: if we are at depth 0, we won't
3563 // find anything else
3564 if (prev_depth == 0)
3570 static bool needEnumCounterReset(ParIterator const & it)
3572 Paragraph const & par = *it;
3573 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3574 depth_type const cur_depth = par.getDepth();
3575 ParIterator prev_it = it;
3576 while (prev_it.pit()) {
3577 --prev_it.top().pit();
3578 Paragraph const & prev_par = *prev_it;
3579 if (prev_par.getDepth() <= cur_depth)
3580 return prev_par.layout().labeltype != LABEL_ENUMERATE;
3582 // start of nested inset: reset
3587 // set the label of a paragraph. This includes the counters.
3588 void Buffer::setLabel(ParIterator & it) const
3590 BufferParams const & bp = this->masterBuffer()->params();
3591 DocumentClass const & textclass = bp.documentClass();
3592 Paragraph & par = it.paragraph();
3593 Layout const & layout = par.layout();
3594 Counters & counters = textclass.counters();
3596 if (par.params().startOfAppendix()) {
3597 // FIXME: only the counter corresponding to toplevel
3598 // sectioning should be reset
3600 counters.appendix(true);
3602 par.params().appendix(counters.appendix());
3604 // Compute the item depth of the paragraph
3605 par.itemdepth = getItemDepth(it);
3607 if (layout.margintype == MARGIN_MANUAL
3608 || layout.latextype == LATEX_BIB_ENVIRONMENT) {
3609 if (par.params().labelWidthString().empty())
3610 par.params().labelWidthString(par.expandLabel(layout, bp));
3612 par.params().labelWidthString(docstring());
3615 switch(layout.labeltype) {
3617 if (layout.toclevel <= bp.secnumdepth
3618 && (layout.latextype != LATEX_ENVIRONMENT
3619 || it.text()->isFirstInSequence(it.pit()))) {
3620 counters.step(layout.counter);
3621 par.params().labelString(
3622 par.expandLabel(layout, bp));
3624 par.params().labelString(docstring());
3627 case LABEL_ITEMIZE: {
3628 // At some point of time we should do something more
3629 // clever here, like:
3630 // par.params().labelString(
3631 // bp.user_defined_bullet(par.itemdepth).getText());
3632 // for now, use a simple hardcoded label
3633 docstring itemlabel;
3634 switch (par.itemdepth) {
3636 itemlabel = char_type(0x2022);
3639 itemlabel = char_type(0x2013);
3642 itemlabel = char_type(0x2217);
3645 itemlabel = char_type(0x2219); // or 0x00b7
3648 par.params().labelString(itemlabel);
3652 case LABEL_ENUMERATE: {
3653 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
3655 switch (par.itemdepth) {
3664 enumcounter += "iv";
3667 // not a valid enumdepth...
3671 // Maybe we have to reset the enumeration counter.
3672 if (needEnumCounterReset(it))
3673 counters.reset(enumcounter);
3674 counters.step(enumcounter);
3676 string const & lang = par.getParLanguage(bp)->code();
3677 par.params().labelString(counters.theCounter(enumcounter, lang));
3682 case LABEL_SENSITIVE: {
3683 string const & type = counters.current_float();
3684 docstring full_label;
3686 full_label = this->B_("Senseless!!! ");
3688 docstring name = this->B_(textclass.floats().getType(type).name());
3689 if (counters.hasCounter(from_utf8(type))) {
3690 string const & lang = par.getParLanguage(bp)->code();
3691 counters.step(from_utf8(type));
3692 full_label = bformat(from_ascii("%1$s %2$s:"),
3694 counters.theCounter(from_utf8(type), lang));
3696 full_label = bformat(from_ascii("%1$s #:"), name);
3698 par.params().labelString(full_label);
3702 case LABEL_NO_LABEL:
3703 par.params().labelString(docstring());
3707 case LABEL_TOP_ENVIRONMENT:
3708 case LABEL_CENTERED_TOP_ENVIRONMENT:
3711 par.params().labelString(par.expandLabel(layout, bp));
3717 void Buffer::updateLabels(ParIterator & parit, bool out) const
3719 LASSERT(parit.pit() == 0, /**/);
3721 // set the position of the text in the buffer to be able
3722 // to resolve macros in it. This has nothing to do with
3723 // labels, but by putting it here we avoid implementing
3724 // a whole bunch of traversal routines just for this call.
3725 parit.text()->setMacrocontextPosition(parit);
3727 depth_type maxdepth = 0;
3728 pit_type const lastpit = parit.lastpit();
3729 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
3730 // reduce depth if necessary
3731 parit->params().depth(min(parit->params().depth(), maxdepth));
3732 maxdepth = parit->getMaxDepthAfter();
3734 // set the counter for this paragraph
3738 InsetList::const_iterator iit = parit->insetList().begin();
3739 InsetList::const_iterator end = parit->insetList().end();
3740 for (; iit != end; ++iit) {
3741 parit.pos() = iit->pos;
3742 iit->inset->updateLabels(parit, out);
3748 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
3749 WordLangTuple & word_lang, docstring_list & suggestions) const
3753 suggestions.clear();
3754 word_lang = WordLangTuple();
3755 // OK, we start from here.
3756 DocIterator const end = doc_iterator_end(this);
3757 for (; from != end; from.forwardPos()) {
3758 // We are only interested in text so remove the math CursorSlice.
3759 while (from.inMathed()) {
3763 // If from is at the end of the document (which is possible
3764 // when leaving the mathed) LyX will crash later.
3768 if (from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions)) {
3773 // Do not increase progress when from == to, otherwise the word
3774 // count will be wrong.
3784 bool Buffer::reload()
3787 // e.g., read-only status could have changed due to version control
3788 d->filename.refresh();
3789 docstring const disp_fn = makeDisplayPath(d->filename.absFilename());
3791 bool const success = loadLyXFile(d->filename);
3796 message(bformat(_("Document %1$s reloaded."), disp_fn));
3798 message(bformat(_("Could not reload document %1$s."), disp_fn));