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 "DocIterator.h"
29 #include "ErrorList.h"
32 #include "FuncRequest.h"
33 #include "InsetIterator.h"
34 #include "InsetList.h"
36 #include "LaTeXFeatures.h"
40 #include "LyXAction.h"
44 #include "output_docbook.h"
46 #include "output_latex.h"
47 #include "output_plaintext.h"
48 #include "paragraph_funcs.h"
49 #include "Paragraph.h"
50 #include "ParagraphParameters.h"
51 #include "ParIterator.h"
52 #include "PDFOptions.h"
53 #include "SpellChecker.h"
56 #include "TexStream.h"
58 #include "TextClass.h"
59 #include "TocBackend.h"
61 #include "VCBackend.h"
63 #include "WordLangTuple.h"
66 #include "insets/InsetBibitem.h"
67 #include "insets/InsetBibtex.h"
68 #include "insets/InsetInclude.h"
69 #include "insets/InsetText.h"
71 #include "mathed/MacroTable.h"
72 #include "mathed/MathMacroTemplate.h"
73 #include "mathed/MathSupport.h"
75 #include "frontends/alert.h"
76 #include "frontends/Delegates.h"
77 #include "frontends/WorkAreaManager.h"
79 #include "graphics/Previews.h"
81 #include "support/lassert.h"
82 #include "support/convert.h"
83 #include "support/debug.h"
84 #include "support/docstring_list.h"
85 #include "support/ExceptionMessage.h"
86 #include "support/FileName.h"
87 #include "support/FileNameList.h"
88 #include "support/filetools.h"
89 #include "support/ForkedCalls.h"
90 #include "support/gettext.h"
91 #include "support/gzstream.h"
92 #include "support/lstrings.h"
93 #include "support/lyxalgo.h"
94 #include "support/os.h"
95 #include "support/Package.h"
96 #include "support/Path.h"
97 #include "support/textutils.h"
98 #include "support/types.h"
100 #include <boost/bind.hpp>
101 #include <boost/shared_ptr.hpp>
113 using namespace lyx::support;
117 namespace Alert = frontend::Alert;
118 namespace os = support::os;
122 // Do not remove the comment below, so we get merge conflict in
123 // independent branches. Instead add your own.
124 int const LYX_FORMAT = 348; // uwestoehr: add support for \*phantom
126 typedef map<string, bool> DepClean;
127 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
131 class BufferSet : public std::set<Buffer const *> {};
136 Impl(Buffer & parent, FileName const & file, bool readonly);
150 mutable TexRow texrow;
152 /// need to regenerate .tex?
156 mutable bool lyx_clean;
158 /// is autosave needed?
159 mutable bool bak_clean;
161 /// is this a unnamed file (New...)?
167 /// name of the file the buffer is associated with.
170 /** Set to true only when the file is fully loaded.
171 * Used to prevent the premature generation of previews
172 * and by the citation inset.
174 bool file_fully_loaded;
177 mutable TocBackend toc_backend;
180 typedef pair<DocIterator, MacroData> ScopeMacro;
181 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
182 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
183 /// map from the macro name to the position map,
184 /// which maps the macro definition position to the scope and the MacroData.
185 NamePositionScopeMacroMap macros;
188 /// positions of child buffers in the buffer
189 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
190 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
191 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
192 /// position of children buffers in this buffer
193 BufferPositionMap children_positions;
194 /// map from children inclusion positions to their scope and their buffer
195 PositionScopeBufferMap position_to_children;
197 /// Container for all sort of Buffer dependant errors.
198 map<string, ErrorList> errorLists;
200 /// timestamp and checksum used to test if the file has been externally
201 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
203 unsigned long checksum_;
206 frontend::WorkAreaManager * wa_;
211 /// A cache for the bibfiles (including bibfiles of loaded child
212 /// documents), needed for appropriate update of natbib labels.
213 mutable support::FileNameList bibfilesCache_;
215 // FIXME The caching mechanism could be improved. At present, we have a
216 // cache for each Buffer, that caches all the bibliography info for that
217 // Buffer. A more efficient solution would be to have a global cache per
218 // file, and then to construct the Buffer's bibinfo from that.
219 /// A cache for bibliography info
220 mutable BiblioInfo bibinfo_;
221 /// whether the bibinfo cache is valid
222 bool bibinfoCacheValid_;
223 /// Cache of timestamps of .bib files
224 map<FileName, time_t> bibfileStatus_;
226 mutable RefCache ref_cache_;
228 /// our Text that should be wrapped in an InsetText
231 /// This is here to force the test to be done whenever parent_buffer
233 Buffer const * parent() const {
234 // if parent_buffer is not loaded, then it has been unloaded,
235 // which means that parent_buffer is an invalid pointer. So we
236 // set it to null in that case.
237 if (!theBufferList().isLoaded(parent_buffer))
239 return parent_buffer;
242 void setParent(Buffer const * pb) { parent_buffer = pb; }
244 /// So we can force access via the accessors.
245 mutable Buffer const * parent_buffer;
249 /// Creates the per buffer temporary directory
250 static FileName createBufferTmpDir()
253 // We are in our own directory. Why bother to mangle name?
254 // In fact I wrote this code to circumvent a problematic behaviour
255 // (bug?) of EMX mkstemp().
256 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
257 convert<string>(count++));
259 if (!tmpfl.createDirectory(0777)) {
260 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
261 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
262 from_utf8(tmpfl.absFilename())));
268 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
269 : lyx_clean(true), bak_clean(true), unnamed(false),
270 read_only(readonly_), filename(file), file_fully_loaded(false),
271 toc_backend(&parent), macro_lock(false), timestamp_(0),
272 checksum_(0), wa_(0), undo_(parent), bibinfoCacheValid_(false),
275 temppath = createBufferTmpDir();
276 lyxvc.setBuffer(&parent);
278 wa_ = new frontend::WorkAreaManager;
282 Buffer::Buffer(string const & file, bool readonly)
283 : d(new Impl(*this, FileName(file), readonly)), gui_(0)
285 LYXERR(Debug::INFO, "Buffer::Buffer()");
287 d->inset = new InsetText(*this);
288 d->inset->setAutoBreakRows(true);
289 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
295 LYXERR(Debug::INFO, "Buffer::~Buffer()");
296 // here the buffer should take care that it is
297 // saved properly, before it goes into the void.
299 // GuiView already destroyed
302 if (d->unnamed && d->filename.extension() == "internal") {
303 // No need to do additional cleanups for internal buffer.
308 // loop over children
309 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
310 Impl::BufferPositionMap::iterator end = d->children_positions.end();
311 for (; it != end; ++it) {
312 Buffer * child = const_cast<Buffer *>(it->first);
313 // The child buffer might have been closed already.
314 if (theBufferList().isLoaded(child))
315 theBufferList().releaseChild(this, child);
318 // clear references to children in macro tables
319 d->children_positions.clear();
320 d->position_to_children.clear();
322 if (!d->temppath.destroyDirectory()) {
323 Alert::warning(_("Could not remove temporary directory"),
324 bformat(_("Could not remove the temporary directory %1$s"),
325 from_utf8(d->temppath.absFilename())));
328 // Remove any previewed LaTeX snippets associated with this buffer.
329 thePreviews().removeLoader(*this);
335 void Buffer::changed() const
342 frontend::WorkAreaManager & Buffer::workAreaManager() const
344 LASSERT(d->wa_, /**/);
349 Text & Buffer::text() const
351 return d->inset->text();
355 Inset & Buffer::inset() const
361 BufferParams & Buffer::params()
367 BufferParams const & Buffer::params() const
373 ParagraphList & Buffer::paragraphs()
375 return text().paragraphs();
379 ParagraphList const & Buffer::paragraphs() const
381 return text().paragraphs();
385 LyXVC & Buffer::lyxvc()
391 LyXVC const & Buffer::lyxvc() const
397 string const Buffer::temppath() const
399 return d->temppath.absFilename();
403 TexRow & Buffer::texrow()
409 TexRow const & Buffer::texrow() const
415 TocBackend & Buffer::tocBackend() const
417 return d->toc_backend;
421 Undo & Buffer::undo()
427 string Buffer::latexName(bool const no_path) const
429 FileName latex_name = makeLatexName(d->filename);
430 return no_path ? latex_name.onlyFileName()
431 : latex_name.absFilename();
435 string Buffer::logName(LogType * type) const
437 string const filename = latexName(false);
439 if (filename.empty()) {
445 string const path = temppath();
447 FileName const fname(addName(temppath(),
448 onlyFilename(changeExtension(filename,
450 FileName const bname(
451 addName(path, onlyFilename(
452 changeExtension(filename,
453 formats.extension("literate") + ".out"))));
455 // If no Latex log or Build log is newer, show Build log
457 if (bname.exists() &&
458 (!fname.exists() || fname.lastModified() < bname.lastModified())) {
459 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
462 return bname.absFilename();
464 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
467 return fname.absFilename();
471 void Buffer::setReadonly(bool const flag)
473 if (d->read_only != flag) {
480 void Buffer::setFileName(string const & newfile)
482 d->filename = makeAbsPath(newfile);
483 setReadonly(d->filename.isReadOnly());
488 int Buffer::readHeader(Lexer & lex)
490 int unknown_tokens = 0;
492 int begin_header_line = -1;
494 // Initialize parameters that may be/go lacking in header:
495 params().branchlist().clear();
496 params().preamble.erase();
497 params().options.erase();
498 params().master.erase();
499 params().float_placement.erase();
500 params().paperwidth.erase();
501 params().paperheight.erase();
502 params().leftmargin.erase();
503 params().rightmargin.erase();
504 params().topmargin.erase();
505 params().bottommargin.erase();
506 params().headheight.erase();
507 params().headsep.erase();
508 params().footskip.erase();
509 params().columnsep.erase();
510 params().fontsCJK.erase();
511 params().listings_params.clear();
512 params().clearLayoutModules();
513 params().clearRemovedModules();
514 params().pdfoptions().clear();
516 for (int i = 0; i < 4; ++i) {
517 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
518 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
521 ErrorList & errorList = d->errorLists["Parse"];
530 if (token == "\\end_header")
534 if (token == "\\begin_header") {
535 begin_header_line = line;
539 LYXERR(Debug::PARSER, "Handling document header token: `"
542 string unknown = params().readToken(lex, token, d->filename.onlyPath());
543 if (!unknown.empty()) {
544 if (unknown[0] != '\\' && token == "\\textclass") {
545 Alert::warning(_("Unknown document class"),
546 bformat(_("Using the default document class, because the "
547 "class %1$s is unknown."), from_utf8(unknown)));
550 docstring const s = bformat(_("Unknown token: "
554 errorList.push_back(ErrorItem(_("Document header error"),
559 if (begin_header_line) {
560 docstring const s = _("\\begin_header is missing");
561 errorList.push_back(ErrorItem(_("Document header error"),
565 params().makeDocumentClass();
567 return unknown_tokens;
572 // changed to be public and have one parameter
573 // Returns true if "\end_document" is not read (Asger)
574 bool Buffer::readDocument(Lexer & lex)
576 ErrorList & errorList = d->errorLists["Parse"];
579 if (!lex.checkFor("\\begin_document")) {
580 docstring const s = _("\\begin_document is missing");
581 errorList.push_back(ErrorItem(_("Document header error"),
585 // we are reading in a brand new document
586 LASSERT(paragraphs().empty(), /**/);
590 if (params().outputChanges) {
591 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
592 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
593 LaTeXFeatures::isAvailable("xcolor");
595 if (!dvipost && !xcolorulem) {
596 Alert::warning(_("Changes not shown in LaTeX output"),
597 _("Changes will not be highlighted in LaTeX output, "
598 "because neither dvipost nor xcolor/ulem are installed.\n"
599 "Please install these packages or redefine "
600 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
601 } else if (!xcolorulem) {
602 Alert::warning(_("Changes not shown in LaTeX output"),
603 _("Changes will not be highlighted in LaTeX output "
604 "when using pdflatex, because xcolor and ulem are not installed.\n"
605 "Please install both packages or redefine "
606 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
610 if (!params().master.empty()) {
611 FileName const master_file = makeAbsPath(params().master,
612 onlyPath(absFileName()));
613 if (isLyXFilename(master_file.absFilename())) {
615 checkAndLoadLyXFile(master_file, true);
617 // necessary e.g. after a reload
618 // to re-register the child (bug 5873)
619 // FIXME: clean up updateMacros (here, only
620 // child registering is needed).
621 master->updateMacros();
622 // set master as master buffer, but only
623 // if we are a real child
624 if (master->isChild(this))
626 // if the master is not fully loaded
627 // it is probably just loading this
628 // child. No warning needed then.
629 else if (master->isFullyLoaded())
630 LYXERR0("The master '"
632 << "' assigned to this document ("
634 << ") does not include "
635 "this document. Ignoring the master assignment.");
641 bool const res = text().read(*this, lex, errorList, d->inset);
644 updateMacroInstances();
649 // needed to insert the selection
650 void Buffer::insertStringAsLines(ParagraphList & pars,
651 pit_type & pit, pos_type & pos,
652 Font const & fn, docstring const & str, bool autobreakrows)
656 // insert the string, don't insert doublespace
657 bool space_inserted = true;
658 for (docstring::const_iterator cit = str.begin();
659 cit != str.end(); ++cit) {
660 Paragraph & par = pars[pit];
662 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
663 breakParagraph(params(), pars, pit, pos,
664 par.layout().isEnvironment());
667 space_inserted = true;
671 // do not insert consecutive spaces if !free_spacing
672 } else if ((*cit == ' ' || *cit == '\t') &&
673 space_inserted && !par.isFreeSpacing()) {
675 } else if (*cit == '\t') {
676 if (!par.isFreeSpacing()) {
677 // tabs are like spaces here
678 par.insertChar(pos, ' ', font, params().trackChanges);
680 space_inserted = true;
682 par.insertChar(pos, *cit, font, params().trackChanges);
684 space_inserted = true;
686 } else if (!isPrintable(*cit)) {
687 // Ignore unprintables
690 // just insert the character
691 par.insertChar(pos, *cit, font, params().trackChanges);
693 space_inserted = (*cit == ' ');
700 bool Buffer::readString(string const & s)
702 params().compressed = false;
704 // remove dummy empty par
705 paragraphs().clear();
709 FileName const name = FileName::tempName("Buffer_readString");
710 switch (readFile(lex, name, true)) {
714 // We need to call lyx2lyx, so write the input to a file
715 ofstream os(name.toFilesystemEncoding().c_str());
718 return readFile(name);
728 bool Buffer::readFile(FileName const & filename)
730 FileName fname(filename);
732 params().compressed = fname.isZippedFile();
734 // remove dummy empty par
735 paragraphs().clear();
738 if (readFile(lex, fname) != success)
745 bool Buffer::isFullyLoaded() const
747 return d->file_fully_loaded;
751 void Buffer::setFullyLoaded(bool value)
753 d->file_fully_loaded = value;
757 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
760 LASSERT(!filename.empty(), /**/);
762 // the first (non-comment) token _must_ be...
763 if (!lex.checkFor("\\lyxformat")) {
764 Alert::error(_("Document format failure"),
765 bformat(_("%1$s is not a readable LyX document."),
766 from_utf8(filename.absFilename())));
772 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
773 // if present remove ".," from string.
774 size_t dot = tmp_format.find_first_of(".,");
775 //lyxerr << " dot found at " << dot << endl;
776 if (dot != string::npos)
777 tmp_format.erase(dot, 1);
778 int const file_format = convert<int>(tmp_format);
779 //lyxerr << "format: " << file_format << endl;
781 // save timestamp and checksum of the original disk file, making sure
782 // to not overwrite them with those of the file created in the tempdir
783 // when it has to be converted to the current format.
785 // Save the timestamp and checksum of disk file. If filename is an
786 // emergency file, save the timestamp and checksum of the original lyx file
787 // because isExternallyModified will check for this file. (BUG4193)
788 string diskfile = filename.absFilename();
789 if (suffixIs(diskfile, ".emergency"))
790 diskfile = diskfile.substr(0, diskfile.size() - 10);
791 saveCheckSum(FileName(diskfile));
794 if (file_format != LYX_FORMAT) {
797 // lyx2lyx would fail
800 FileName const tmpfile = FileName::tempName("Buffer_readFile");
801 if (tmpfile.empty()) {
802 Alert::error(_("Conversion failed"),
803 bformat(_("%1$s is from a different"
804 " version of LyX, but a temporary"
805 " file for converting it could"
807 from_utf8(filename.absFilename())));
810 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
811 if (lyx2lyx.empty()) {
812 Alert::error(_("Conversion script not found"),
813 bformat(_("%1$s is from a different"
814 " version of LyX, but the"
815 " conversion script lyx2lyx"
816 " could not be found."),
817 from_utf8(filename.absFilename())));
820 ostringstream command;
821 command << os::python()
822 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
823 << " -t " << convert<string>(LYX_FORMAT)
824 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
825 << ' ' << quoteName(filename.toFilesystemEncoding());
826 string const command_str = command.str();
828 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
830 cmd_ret const ret = runCommand(command_str);
831 if (ret.first != 0) {
832 Alert::error(_("Conversion script failed"),
833 bformat(_("%1$s is from a different version"
834 " of LyX, but the lyx2lyx script"
835 " failed to convert it."),
836 from_utf8(filename.absFilename())));
839 bool const ret = readFile(tmpfile);
840 // Do stuff with tmpfile name and buffer name here.
841 return ret ? success : failure;
846 if (readDocument(lex)) {
847 Alert::error(_("Document format failure"),
848 bformat(_("%1$s ended unexpectedly, which means"
849 " that it is probably corrupted."),
850 from_utf8(filename.absFilename())));
853 d->file_fully_loaded = true;
858 // Should probably be moved to somewhere else: BufferView? LyXView?
859 bool Buffer::save() const
861 // We don't need autosaves in the immediate future. (Asger)
862 resetAutosaveTimers();
864 string const encodedFilename = d->filename.toFilesystemEncoding();
867 bool madeBackup = false;
869 // make a backup if the file already exists
870 if (lyxrc.make_backup && fileName().exists()) {
871 backupName = FileName(absFileName() + '~');
872 if (!lyxrc.backupdir_path.empty()) {
873 string const mangledName =
874 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
875 backupName = FileName(addName(lyxrc.backupdir_path,
878 if (fileName().copyTo(backupName)) {
881 Alert::error(_("Backup failure"),
882 bformat(_("Cannot create backup file %1$s.\n"
883 "Please check whether the directory exists and is writeable."),
884 from_utf8(backupName.absFilename())));
885 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
889 // ask if the disk file has been externally modified (use checksum method)
890 if (fileName().exists() && isExternallyModified(checksum_method)) {
891 docstring const file = makeDisplayPath(absFileName(), 20);
892 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
893 "you want to overwrite this file?"), file);
894 int const ret = Alert::prompt(_("Overwrite modified file?"),
895 text, 1, 1, _("&Overwrite"), _("&Cancel"));
900 if (writeFile(d->filename)) {
904 // Saving failed, so backup is not backup
906 backupName.moveTo(d->filename);
912 bool Buffer::writeFile(FileName const & fname) const
914 if (d->read_only && fname == d->filename)
919 docstring const str = bformat(_("Saving document %1$s..."),
920 makeDisplayPath(fname.absFilename()));
923 if (params().compressed) {
924 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
925 retval = ofs && write(ofs);
927 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
928 retval = ofs && write(ofs);
932 message(str + _(" could not write file!"));
936 removeAutosaveFile();
938 saveCheckSum(d->filename);
939 message(str + _(" done."));
945 bool Buffer::write(ostream & ofs) const
948 // Use the standard "C" locale for file output.
949 ofs.imbue(locale::classic());
952 // The top of the file should not be written by params().
954 // write out a comment in the top of the file
955 ofs << "#LyX " << lyx_version
956 << " created this file. For more info see http://www.lyx.org/\n"
957 << "\\lyxformat " << LYX_FORMAT << "\n"
958 << "\\begin_document\n";
960 /// For each author, set 'used' to true if there is a change
961 /// by this author in the document; otherwise set it to 'false'.
962 AuthorList::Authors::const_iterator a_it = params().authors().begin();
963 AuthorList::Authors::const_iterator a_end = params().authors().end();
964 for (; a_it != a_end; ++a_it)
965 a_it->second.setUsed(false);
967 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
968 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
969 for ( ; it != end; ++it)
970 it->checkAuthors(params().authors());
972 // now write out the buffer parameters.
973 ofs << "\\begin_header\n";
974 params().writeFile(ofs);
975 ofs << "\\end_header\n";
978 ofs << "\n\\begin_body\n";
979 text().write(*this, ofs);
980 ofs << "\n\\end_body\n";
982 // Write marker that shows file is complete
983 ofs << "\\end_document" << endl;
985 // Shouldn't really be needed....
988 // how to check if close went ok?
989 // Following is an attempt... (BE 20001011)
991 // good() returns false if any error occured, including some
993 // bad() returns true if something bad happened in the buffer,
994 // which should include file system full errors.
999 lyxerr << "File was not closed properly." << endl;
1006 bool Buffer::makeLaTeXFile(FileName const & fname,
1007 string const & original_path,
1008 OutputParams const & runparams,
1009 bool output_preamble, bool output_body) const
1011 string const encoding = runparams.encoding->iconvName();
1012 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1015 try { ofs.reset(encoding); }
1016 catch (iconv_codecvt_facet_exception & e) {
1017 lyxerr << "Caught iconv exception: " << e.what() << endl;
1018 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1019 "verify that the support software for your encoding (%1$s) is "
1020 "properly installed"), from_ascii(encoding)));
1023 if (!openFileWrite(ofs, fname))
1026 //TexStream ts(ofs.rdbuf(), &texrow());
1027 ErrorList & errorList = d->errorLists["Export"];
1029 bool failed_export = false;
1032 writeLaTeXSource(ofs, original_path,
1033 runparams, output_preamble, output_body);
1035 catch (EncodingException & e) {
1036 odocstringstream ods;
1037 ods.put(e.failed_char);
1039 oss << "0x" << hex << e.failed_char << dec;
1040 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1041 " (code point %2$s)"),
1042 ods.str(), from_utf8(oss.str()));
1043 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1044 "representable in the chosen encoding.\n"
1045 "Changing the document encoding to utf8 could help."),
1046 e.par_id, e.pos, e.pos + 1));
1047 failed_export = true;
1049 catch (iconv_codecvt_facet_exception & e) {
1050 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1051 _(e.what()), -1, 0, 0));
1052 failed_export = true;
1054 catch (exception const & e) {
1055 errorList.push_back(ErrorItem(_("conversion failed"),
1056 _(e.what()), -1, 0, 0));
1057 failed_export = true;
1060 lyxerr << "Caught some really weird exception..." << endl;
1066 failed_export = true;
1067 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1071 return !failed_export;
1075 void Buffer::writeLaTeXSource(odocstream & os,
1076 string const & original_path,
1077 OutputParams const & runparams_in,
1078 bool const output_preamble, bool const output_body) const
1080 // The child documents, if any, shall be already loaded at this point.
1082 OutputParams runparams = runparams_in;
1084 // Classify the unicode characters appearing in math insets
1085 Encodings::initUnicodeMath(*this);
1087 // validate the buffer.
1088 LYXERR(Debug::LATEX, " Validating buffer...");
1089 LaTeXFeatures features(*this, params(), runparams);
1091 LYXERR(Debug::LATEX, " Buffer validation done.");
1093 // The starting paragraph of the coming rows is the
1094 // first paragraph of the document. (Asger)
1095 if (output_preamble && runparams.nice) {
1096 os << "%% LyX " << lyx_version << " created this file. "
1097 "For more info, see http://www.lyx.org/.\n"
1098 "%% Do not edit unless you really know what "
1100 d->texrow.newline();
1101 d->texrow.newline();
1103 LYXERR(Debug::INFO, "lyx document header finished");
1105 // Don't move this behind the parent_buffer=0 code below,
1106 // because then the macros will not get the right "redefinition"
1107 // flag as they don't see the parent macros which are output before.
1110 // fold macros if possible, still with parent buffer as the
1111 // macros will be put in the prefix anyway.
1112 updateMacroInstances();
1114 // There are a few differences between nice LaTeX and usual files:
1115 // usual is \batchmode and has a
1116 // special input@path to allow the including of figures
1117 // with either \input or \includegraphics (what figinsets do).
1118 // input@path is set when the actual parameter
1119 // original_path is set. This is done for usual tex-file, but not
1120 // for nice-latex-file. (Matthias 250696)
1121 // Note that input@path is only needed for something the user does
1122 // in the preamble, included .tex files or ERT, files included by
1123 // LyX work without it.
1124 if (output_preamble) {
1125 if (!runparams.nice) {
1126 // code for usual, NOT nice-latex-file
1127 os << "\\batchmode\n"; // changed
1128 // from \nonstopmode
1129 d->texrow.newline();
1131 if (!original_path.empty()) {
1133 // We don't know the encoding of inputpath
1134 docstring const inputpath = from_utf8(latex_path(original_path));
1135 os << "\\makeatletter\n"
1136 << "\\def\\input@path{{"
1137 << inputpath << "/}}\n"
1138 << "\\makeatother\n";
1139 d->texrow.newline();
1140 d->texrow.newline();
1141 d->texrow.newline();
1144 // get parent macros (if this buffer has a parent) which will be
1145 // written at the document begin further down.
1146 MacroSet parentMacros;
1147 listParentMacros(parentMacros, features);
1149 // Write the preamble
1150 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1152 runparams.use_japanese = features.isRequired("japanese");
1158 os << "\\begin{document}\n";
1159 d->texrow.newline();
1161 // output the parent macros
1162 MacroSet::iterator it = parentMacros.begin();
1163 MacroSet::iterator end = parentMacros.end();
1164 for (; it != end; ++it)
1165 (*it)->write(os, true);
1166 } // output_preamble
1168 d->texrow.start(paragraphs().begin()->id(), 0);
1170 LYXERR(Debug::INFO, "preamble finished, now the body.");
1172 // if we are doing a real file with body, even if this is the
1173 // child of some other buffer, let's cut the link here.
1174 // This happens for example if only a child document is printed.
1175 Buffer const * save_parent = 0;
1176 if (output_preamble) {
1177 save_parent = d->parent();
1182 latexParagraphs(*this, text(), os, d->texrow, runparams);
1184 // Restore the parenthood if needed
1185 if (output_preamble)
1186 d->setParent(save_parent);
1188 // add this just in case after all the paragraphs
1190 d->texrow.newline();
1192 if (output_preamble) {
1193 os << "\\end{document}\n";
1194 d->texrow.newline();
1195 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1197 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1199 runparams_in.encoding = runparams.encoding;
1201 // Just to be sure. (Asger)
1202 d->texrow.newline();
1204 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1205 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1209 bool Buffer::isLatex() const
1211 return params().documentClass().outputType() == LATEX;
1215 bool Buffer::isLiterate() const
1217 return params().documentClass().outputType() == LITERATE;
1221 bool Buffer::isDocBook() const
1223 return params().documentClass().outputType() == DOCBOOK;
1227 void Buffer::makeDocBookFile(FileName const & fname,
1228 OutputParams const & runparams,
1229 bool const body_only) const
1231 LYXERR(Debug::LATEX, "makeDocBookFile...");
1234 if (!openFileWrite(ofs, fname))
1237 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1241 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1245 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1246 OutputParams const & runparams,
1247 bool const only_body) const
1249 LaTeXFeatures features(*this, params(), runparams);
1254 DocumentClass const & tclass = params().documentClass();
1255 string const top_element = tclass.latexname();
1258 if (runparams.flavor == OutputParams::XML)
1259 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1262 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1265 if (! tclass.class_header().empty())
1266 os << from_ascii(tclass.class_header());
1267 else if (runparams.flavor == OutputParams::XML)
1268 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1269 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1271 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1273 docstring preamble = from_utf8(params().preamble);
1274 if (runparams.flavor != OutputParams::XML ) {
1275 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1276 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1277 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1278 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1281 string const name = runparams.nice
1282 ? changeExtension(absFileName(), ".sgml") : fname;
1283 preamble += features.getIncludedFiles(name);
1284 preamble += features.getLyXSGMLEntities();
1286 if (!preamble.empty()) {
1287 os << "\n [ " << preamble << " ]";
1292 string top = top_element;
1294 if (runparams.flavor == OutputParams::XML)
1295 top += params().language->code();
1297 top += params().language->code().substr(0, 2);
1300 if (!params().options.empty()) {
1302 top += params().options;
1305 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1306 << " file was created by LyX " << lyx_version
1307 << "\n See http://www.lyx.org/ for more information -->\n";
1309 params().documentClass().counters().reset();
1313 sgml::openTag(os, top);
1315 docbookParagraphs(paragraphs(), *this, os, runparams);
1316 sgml::closeTag(os, top_element);
1320 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1321 // Other flags: -wall -v0 -x
1322 int Buffer::runChktex()
1326 // get LaTeX-Filename
1327 FileName const path(temppath());
1328 string const name = addName(path.absFilename(), latexName());
1329 string const org_path = filePath();
1331 PathChanger p(path); // path to LaTeX file
1332 message(_("Running chktex..."));
1334 // Generate the LaTeX file if neccessary
1335 OutputParams runparams(¶ms().encoding());
1336 runparams.flavor = OutputParams::LATEX;
1337 runparams.nice = false;
1338 makeLaTeXFile(FileName(name), org_path, runparams);
1341 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1342 int const res = chktex.run(terr); // run chktex
1345 Alert::error(_("chktex failure"),
1346 _("Could not run chktex successfully."));
1347 } else if (res > 0) {
1348 ErrorList & errlist = d->errorLists["ChkTeX"];
1350 bufferErrors(terr, errlist);
1361 void Buffer::validate(LaTeXFeatures & features) const
1363 params().validate(features);
1367 for_each(paragraphs().begin(), paragraphs().end(),
1368 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1370 if (lyxerr.debugging(Debug::LATEX)) {
1371 features.showStruct();
1376 void Buffer::getLabelList(vector<docstring> & list) const
1378 // If this is a child document, use the parent's list instead.
1379 Buffer const * const pbuf = d->parent();
1381 pbuf->getLabelList(list);
1386 Toc & toc = d->toc_backend.toc("label");
1387 TocIterator toc_it = toc.begin();
1388 TocIterator end = toc.end();
1389 for (; toc_it != end; ++toc_it) {
1390 if (toc_it->depth() == 0)
1391 list.push_back(toc_it->str());
1396 void Buffer::updateBibfilesCache(UpdateScope scope) const
1398 // If this is a child document, use the parent's cache instead.
1399 Buffer const * const pbuf = d->parent();
1400 if (pbuf && scope != UpdateChildOnly) {
1401 pbuf->updateBibfilesCache();
1405 d->bibfilesCache_.clear();
1406 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1407 if (it->lyxCode() == BIBTEX_CODE) {
1408 InsetBibtex const & inset =
1409 static_cast<InsetBibtex const &>(*it);
1410 support::FileNameList const bibfiles = inset.getBibFiles();
1411 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1414 } else if (it->lyxCode() == INCLUDE_CODE) {
1415 InsetInclude & inset =
1416 static_cast<InsetInclude &>(*it);
1417 inset.updateBibfilesCache();
1418 support::FileNameList const & bibfiles =
1419 inset.getBibfilesCache();
1420 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1425 // the bibinfo cache is now invalid
1426 d->bibinfoCacheValid_ = false;
1430 void Buffer::invalidateBibinfoCache()
1432 d->bibinfoCacheValid_ = false;
1436 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1438 // If this is a child document, use the parent's cache instead.
1439 Buffer const * const pbuf = d->parent();
1440 if (pbuf && scope != UpdateChildOnly)
1441 return pbuf->getBibfilesCache();
1443 // We update the cache when first used instead of at loading time.
1444 if (d->bibfilesCache_.empty())
1445 const_cast<Buffer *>(this)->updateBibfilesCache(scope);
1447 return d->bibfilesCache_;
1451 BiblioInfo const & Buffer::masterBibInfo() const
1453 // if this is a child document and the parent is already loaded
1454 // use the parent's list instead [ale990412]
1455 Buffer const * const tmp = masterBuffer();
1458 return tmp->masterBibInfo();
1459 return localBibInfo();
1463 BiblioInfo const & Buffer::localBibInfo() const
1465 if (d->bibinfoCacheValid_) {
1466 support::FileNameList const & bibfilesCache = getBibfilesCache();
1467 // compare the cached timestamps with the actual ones.
1468 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1469 support::FileNameList::const_iterator en = bibfilesCache.end();
1470 for (; ei != en; ++ ei) {
1471 time_t lastw = ei->lastModified();
1472 if (lastw != d->bibfileStatus_[*ei]) {
1473 d->bibinfoCacheValid_ = false;
1474 d->bibfileStatus_[*ei] = lastw;
1480 if (!d->bibinfoCacheValid_) {
1481 d->bibinfo_.clear();
1482 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1483 it->fillWithBibKeys(d->bibinfo_, it);
1484 d->bibinfoCacheValid_ = true;
1490 bool Buffer::isDepClean(string const & name) const
1492 DepClean::const_iterator const it = d->dep_clean.find(name);
1493 if (it == d->dep_clean.end())
1499 void Buffer::markDepClean(string const & name)
1501 d->dep_clean[name] = true;
1505 bool Buffer::dispatch(string const & command, bool * result)
1507 return dispatch(lyxaction.lookupFunc(command), result);
1511 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1513 bool dispatched = true;
1515 switch (func.action) {
1516 case LFUN_BUFFER_EXPORT: {
1517 bool const tmp = doExport(to_utf8(func.argument()), false);
1523 case LFUN_BRANCH_ACTIVATE:
1524 case LFUN_BRANCH_DEACTIVATE: {
1525 BranchList & branchList = params().branchlist();
1526 docstring const branchName = func.argument();
1527 // the case without a branch name is handled elsewhere
1528 if (branchName.empty()) {
1532 Branch * branch = branchList.find(branchName);
1534 LYXERR0("Branch " << branchName << " does not exist.");
1536 branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1548 void Buffer::changeLanguage(Language const * from, Language const * to)
1550 LASSERT(from, /**/);
1553 for_each(par_iterator_begin(),
1555 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1559 bool Buffer::isMultiLingual() const
1561 ParConstIterator end = par_iterator_end();
1562 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1563 if (it->isMultiLingual(params()))
1570 DocIterator Buffer::getParFromID(int const id) const
1572 Buffer * buf = const_cast<Buffer *>(this);
1574 // John says this is called with id == -1 from undo
1575 lyxerr << "getParFromID(), id: " << id << endl;
1576 return doc_iterator_end(buf);
1579 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
1580 if (it.paragraph().id() == id)
1583 return doc_iterator_end(buf);
1587 bool Buffer::hasParWithID(int const id) const
1589 return !getParFromID(id).atEnd();
1593 ParIterator Buffer::par_iterator_begin()
1595 return ParIterator(doc_iterator_begin(this));
1599 ParIterator Buffer::par_iterator_end()
1601 return ParIterator(doc_iterator_end(this));
1605 ParConstIterator Buffer::par_iterator_begin() const
1607 return ParConstIterator(doc_iterator_begin(this));
1611 ParConstIterator Buffer::par_iterator_end() const
1613 return ParConstIterator(doc_iterator_end(this));
1617 Language const * Buffer::language() const
1619 return params().language;
1623 docstring const Buffer::B_(string const & l10n) const
1625 return params().B_(l10n);
1629 bool Buffer::isClean() const
1631 return d->lyx_clean;
1635 bool Buffer::isBakClean() const
1637 return d->bak_clean;
1641 bool Buffer::isExternallyModified(CheckMethod method) const
1643 LASSERT(d->filename.exists(), /**/);
1644 // if method == timestamp, check timestamp before checksum
1645 return (method == checksum_method
1646 || d->timestamp_ != d->filename.lastModified())
1647 && d->checksum_ != d->filename.checksum();
1651 void Buffer::saveCheckSum(FileName const & file) const
1653 if (file.exists()) {
1654 d->timestamp_ = file.lastModified();
1655 d->checksum_ = file.checksum();
1657 // in the case of save to a new file.
1664 void Buffer::markClean() const
1666 if (!d->lyx_clean) {
1667 d->lyx_clean = true;
1670 // if the .lyx file has been saved, we don't need an
1672 d->bak_clean = true;
1676 void Buffer::markBakClean() const
1678 d->bak_clean = true;
1682 void Buffer::setUnnamed(bool flag)
1688 bool Buffer::isUnnamed() const
1694 // FIXME: this function should be moved to buffer_pimpl.C
1695 void Buffer::markDirty()
1698 d->lyx_clean = false;
1701 d->bak_clean = false;
1703 DepClean::iterator it = d->dep_clean.begin();
1704 DepClean::const_iterator const end = d->dep_clean.end();
1706 for (; it != end; ++it)
1711 FileName Buffer::fileName() const
1717 string Buffer::absFileName() const
1719 return d->filename.absFilename();
1723 string Buffer::filePath() const
1725 return d->filename.onlyPath().absFilename() + "/";
1729 bool Buffer::isReadonly() const
1731 return d->read_only;
1735 void Buffer::setParent(Buffer const * buffer)
1737 // Avoids recursive include.
1738 d->setParent(buffer == this ? 0 : buffer);
1743 Buffer const * Buffer::parent() const
1749 void Buffer::collectRelatives(BufferSet & bufs) const
1753 parent()->collectRelatives(bufs);
1755 // loop over children
1756 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
1757 Impl::BufferPositionMap::iterator end = d->children_positions.end();
1758 for (; it != end; ++it)
1759 bufs.insert(const_cast<Buffer *>(it->first));
1763 std::vector<Buffer const *> Buffer::allRelatives() const
1766 collectRelatives(bufs);
1767 BufferSet::iterator it = bufs.begin();
1768 std::vector<Buffer const *> ret;
1769 for (; it != bufs.end(); ++it)
1775 Buffer const * Buffer::masterBuffer() const
1777 Buffer const * const pbuf = d->parent();
1781 return pbuf->masterBuffer();
1785 bool Buffer::isChild(Buffer * child) const
1787 return d->children_positions.find(child) != d->children_positions.end();
1791 DocIterator Buffer::firstChildPosition(Buffer const * child)
1793 Impl::BufferPositionMap::iterator it;
1794 it = d->children_positions.find(child);
1795 if (it == d->children_positions.end())
1796 return DocIterator(this);
1801 std::vector<Buffer *> Buffer::getChildren() const
1803 std::vector<Buffer *> clist;
1804 // loop over children
1805 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
1806 Impl::BufferPositionMap::iterator end = d->children_positions.end();
1807 for (; it != end; ++it) {
1808 Buffer * child = const_cast<Buffer *>(it->first);
1809 clist.push_back(child);
1810 // there might be grandchildren
1811 std::vector<Buffer *> glist = child->getChildren();
1812 for (vector<Buffer *>::const_iterator git = glist.begin();
1813 git != glist.end(); ++git)
1814 clist.push_back(*git);
1820 template<typename M>
1821 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
1826 typename M::iterator it = m.lower_bound(x);
1827 if (it == m.begin())
1835 MacroData const * Buffer::getBufferMacro(docstring const & name,
1836 DocIterator const & pos) const
1838 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
1840 // if paragraphs have no macro context set, pos will be empty
1844 // we haven't found anything yet
1845 DocIterator bestPos = par_iterator_begin();
1846 MacroData const * bestData = 0;
1848 // find macro definitions for name
1849 Impl::NamePositionScopeMacroMap::iterator nameIt
1850 = d->macros.find(name);
1851 if (nameIt != d->macros.end()) {
1852 // find last definition in front of pos or at pos itself
1853 Impl::PositionScopeMacroMap::const_iterator it
1854 = greatest_below(nameIt->second, pos);
1855 if (it != nameIt->second.end()) {
1857 // scope ends behind pos?
1858 if (pos < it->second.first) {
1859 // Looks good, remember this. If there
1860 // is no external macro behind this,
1861 // we found the right one already.
1862 bestPos = it->first;
1863 bestData = &it->second.second;
1867 // try previous macro if there is one
1868 if (it == nameIt->second.begin())
1875 // find macros in included files
1876 Impl::PositionScopeBufferMap::const_iterator it
1877 = greatest_below(d->position_to_children, pos);
1878 if (it == d->position_to_children.end())
1879 // no children before
1883 // do we know something better (i.e. later) already?
1884 if (it->first < bestPos )
1887 // scope ends behind pos?
1888 if (pos < it->second.first) {
1889 // look for macro in external file
1890 d->macro_lock = true;
1891 MacroData const * data
1892 = it->second.second->getMacro(name, false);
1893 d->macro_lock = false;
1895 bestPos = it->first;
1901 // try previous file if there is one
1902 if (it == d->position_to_children.begin())
1907 // return the best macro we have found
1912 MacroData const * Buffer::getMacro(docstring const & name,
1913 DocIterator const & pos, bool global) const
1918 // query buffer macros
1919 MacroData const * data = getBufferMacro(name, pos);
1923 // If there is a master buffer, query that
1924 Buffer const * const pbuf = d->parent();
1926 d->macro_lock = true;
1927 MacroData const * macro = pbuf->getMacro(
1928 name, *this, false);
1929 d->macro_lock = false;
1935 data = MacroTable::globalMacros().get(name);
1944 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
1946 // set scope end behind the last paragraph
1947 DocIterator scope = par_iterator_begin();
1948 scope.pit() = scope.lastpit() + 1;
1950 return getMacro(name, scope, global);
1954 MacroData const * Buffer::getMacro(docstring const & name,
1955 Buffer const & child, bool global) const
1957 // look where the child buffer is included first
1958 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
1959 if (it == d->children_positions.end())
1962 // check for macros at the inclusion position
1963 return getMacro(name, it->second, global);
1967 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
1969 pit_type lastpit = it.lastpit();
1971 // look for macros in each paragraph
1972 while (it.pit() <= lastpit) {
1973 Paragraph & par = it.paragraph();
1975 // iterate over the insets of the current paragraph
1976 InsetList const & insets = par.insetList();
1977 InsetList::const_iterator iit = insets.begin();
1978 InsetList::const_iterator end = insets.end();
1979 for (; iit != end; ++iit) {
1980 it.pos() = iit->pos;
1982 // is it a nested text inset?
1983 if (iit->inset->asInsetText()) {
1984 // Inset needs its own scope?
1985 InsetText const * itext = iit->inset->asInsetText();
1986 bool newScope = itext->isMacroScope();
1988 // scope which ends just behind the inset
1989 DocIterator insetScope = it;
1992 // collect macros in inset
1993 it.push_back(CursorSlice(*iit->inset));
1994 updateMacros(it, newScope ? insetScope : scope);
1999 // is it an external file?
2000 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2001 // get buffer of external file
2002 InsetInclude const & inset =
2003 static_cast<InsetInclude const &>(*iit->inset);
2004 d->macro_lock = true;
2005 Buffer * child = inset.getChildBuffer();
2006 d->macro_lock = false;
2010 // register its position, but only when it is
2011 // included first in the buffer
2012 if (d->children_positions.find(child) ==
2013 d->children_positions.end())
2014 d->children_positions[child] = it;
2016 // register child with its scope
2017 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
2021 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2025 MathMacroTemplate & macroTemplate =
2026 static_cast<MathMacroTemplate &>(*iit->inset);
2027 MacroContext mc(*this, it);
2028 macroTemplate.updateToContext(mc);
2031 bool valid = macroTemplate.validMacro();
2032 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2033 // then the BufferView's cursor will be invalid in
2034 // some cases which leads to crashes.
2039 d->macros[macroTemplate.name()][it] =
2040 Impl::ScopeMacro(scope, MacroData(*this, it));
2050 void Buffer::updateMacros() const
2055 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2057 // start with empty table
2059 d->children_positions.clear();
2060 d->position_to_children.clear();
2062 // Iterate over buffer, starting with first paragraph
2063 // The scope must be bigger than any lookup DocIterator
2064 // later. For the global lookup, lastpit+1 is used, hence
2065 // we use lastpit+2 here.
2066 DocIterator it = par_iterator_begin();
2067 DocIterator outerScope = it;
2068 outerScope.pit() = outerScope.lastpit() + 2;
2069 updateMacros(it, outerScope);
2073 void Buffer::updateMacroInstances() const
2075 LYXERR(Debug::MACROS, "updateMacroInstances for "
2076 << d->filename.onlyFileName());
2077 DocIterator it = doc_iterator_begin(this);
2078 DocIterator end = doc_iterator_end(this);
2079 for (; it != end; it.forwardPos()) {
2080 // look for MathData cells in InsetMathNest insets
2081 Inset * inset = it.nextInset();
2085 InsetMath * minset = inset->asInsetMath();
2089 // update macro in all cells of the InsetMathNest
2090 DocIterator::idx_type n = minset->nargs();
2091 MacroContext mc = MacroContext(*this, it);
2092 for (DocIterator::idx_type i = 0; i < n; ++i) {
2093 MathData & data = minset->cell(i);
2094 data.updateMacros(0, mc);
2100 void Buffer::listMacroNames(MacroNameSet & macros) const
2105 d->macro_lock = true;
2107 // loop over macro names
2108 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2109 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2110 for (; nameIt != nameEnd; ++nameIt)
2111 macros.insert(nameIt->first);
2113 // loop over children
2114 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2115 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2116 for (; it != end; ++it)
2117 it->first->listMacroNames(macros);
2120 Buffer const * const pbuf = d->parent();
2122 pbuf->listMacroNames(macros);
2124 d->macro_lock = false;
2128 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2130 Buffer const * const pbuf = d->parent();
2135 pbuf->listMacroNames(names);
2138 MacroNameSet::iterator it = names.begin();
2139 MacroNameSet::iterator end = names.end();
2140 for (; it != end; ++it) {
2142 MacroData const * data =
2143 pbuf->getMacro(*it, *this, false);
2145 macros.insert(data);
2147 // we cannot access the original MathMacroTemplate anymore
2148 // here to calls validate method. So we do its work here manually.
2149 // FIXME: somehow make the template accessible here.
2150 if (data->optionals() > 0)
2151 features.require("xargs");
2157 Buffer::References & Buffer::references(docstring const & label)
2160 return const_cast<Buffer *>(masterBuffer())->references(label);
2162 RefCache::iterator it = d->ref_cache_.find(label);
2163 if (it != d->ref_cache_.end())
2164 return it->second.second;
2166 static InsetLabel const * dummy_il = 0;
2167 static References const dummy_refs;
2168 it = d->ref_cache_.insert(
2169 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2170 return it->second.second;
2174 Buffer::References const & Buffer::references(docstring const & label) const
2176 return const_cast<Buffer *>(this)->references(label);
2180 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2182 masterBuffer()->d->ref_cache_[label].first = il;
2186 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2188 return masterBuffer()->d->ref_cache_[label].first;
2192 void Buffer::clearReferenceCache() const
2195 d->ref_cache_.clear();
2199 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2202 //FIXME: This does not work for child documents yet.
2203 LASSERT(code == CITE_CODE, /**/);
2204 // Check if the label 'from' appears more than once
2205 vector<docstring> labels;
2207 BiblioInfo const & keys = masterBibInfo();
2208 BiblioInfo::const_iterator bit = keys.begin();
2209 BiblioInfo::const_iterator bend = keys.end();
2211 for (; bit != bend; ++bit)
2213 labels.push_back(bit->first);
2216 if (count(labels.begin(), labels.end(), from) > 1)
2219 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2220 if (it->lyxCode() == code) {
2221 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2222 docstring const oldValue = inset.getParam(paramName);
2223 if (oldValue == from)
2224 inset.setParam(paramName, to);
2230 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2231 pit_type par_end, bool full_source) const
2233 OutputParams runparams(¶ms().encoding());
2234 runparams.nice = true;
2235 runparams.flavor = OutputParams::LATEX;
2236 runparams.linelen = lyxrc.plaintext_linelen;
2237 // No side effect of file copying and image conversion
2238 runparams.dryrun = true;
2242 os << "% " << _("Preview source code") << "\n\n";
2243 d->texrow.newline();
2244 d->texrow.newline();
2246 writeDocBookSource(os, absFileName(), runparams, false);
2248 // latex or literate
2249 writeLaTeXSource(os, string(), runparams, true, true);
2251 runparams.par_begin = par_begin;
2252 runparams.par_end = par_end;
2253 if (par_begin + 1 == par_end) {
2255 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2259 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2260 convert<docstring>(par_begin),
2261 convert<docstring>(par_end - 1))
2264 d->texrow.newline();
2265 d->texrow.newline();
2266 // output paragraphs
2268 docbookParagraphs(paragraphs(), *this, os, runparams);
2270 // latex or literate
2271 latexParagraphs(*this, text(), os, d->texrow, runparams);
2276 ErrorList & Buffer::errorList(string const & type) const
2278 static ErrorList emptyErrorList;
2279 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2280 if (I == d->errorLists.end())
2281 return emptyErrorList;
2287 void Buffer::updateTocItem(std::string const & type,
2288 DocIterator const & dit) const
2291 gui_->updateTocItem(type, dit);
2295 void Buffer::structureChanged() const
2298 gui_->structureChanged();
2302 void Buffer::errors(string const & err) const
2309 void Buffer::message(docstring const & msg) const
2316 void Buffer::setBusy(bool on) const
2323 void Buffer::setReadOnly(bool on) const
2326 d->wa_->setReadOnly(on);
2330 void Buffer::updateTitles() const
2333 d->wa_->updateTitles();
2337 void Buffer::resetAutosaveTimers() const
2340 gui_->resetAutosaveTimers();
2344 bool Buffer::hasGuiDelegate() const
2350 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2359 class AutoSaveBuffer : public ForkedProcess {
2362 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2363 : buffer_(buffer), fname_(fname) {}
2365 virtual boost::shared_ptr<ForkedProcess> clone() const
2367 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2372 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2373 from_utf8(fname_.absFilename())));
2374 return run(DontWait);
2378 virtual int generateChild();
2380 Buffer const & buffer_;
2385 int AutoSaveBuffer::generateChild()
2387 // tmp_ret will be located (usually) in /tmp
2388 // will that be a problem?
2389 // Note that this calls ForkedCalls::fork(), so it's
2390 // ok cross-platform.
2391 pid_t const pid = fork();
2392 // If you want to debug the autosave
2393 // you should set pid to -1, and comment out the fork.
2394 if (pid != 0 && pid != -1)
2397 // pid = -1 signifies that lyx was unable
2398 // to fork. But we will do the save
2400 bool failed = false;
2401 FileName const tmp_ret = FileName::tempName("lyxauto");
2402 if (!tmp_ret.empty()) {
2403 buffer_.writeFile(tmp_ret);
2404 // assume successful write of tmp_ret
2405 if (!tmp_ret.moveTo(fname_))
2411 // failed to write/rename tmp_ret so try writing direct
2412 if (!buffer_.writeFile(fname_)) {
2413 // It is dangerous to do this in the child,
2414 // but safe in the parent, so...
2415 if (pid == -1) // emit message signal.
2416 buffer_.message(_("Autosave failed!"));
2420 if (pid == 0) // we are the child so...
2429 FileName Buffer::getAutosaveFilename() const
2431 string const fpath = isUnnamed() ? lyxrc.document_path : filePath();
2432 string const fname = "#" + d->filename.onlyFileName() + "#";
2433 return makeAbsPath(fname, fpath);
2437 void Buffer::removeAutosaveFile() const
2439 FileName const f = getAutosaveFilename();
2445 // Perfect target for a thread...
2446 void Buffer::autoSave() const
2448 if (isBakClean() || isReadonly()) {
2449 // We don't save now, but we'll try again later
2450 resetAutosaveTimers();
2454 // emit message signal.
2455 message(_("Autosaving current document..."));
2456 AutoSaveBuffer autosave(*this, getAutosaveFilename());
2460 resetAutosaveTimers();
2464 string Buffer::bufferFormat() const
2470 if (params().encoding().package() == Encoding::japanese)
2476 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2477 string & result_file) const
2479 string backend_format;
2480 OutputParams runparams(¶ms().encoding());
2481 runparams.flavor = OutputParams::LATEX;
2482 runparams.linelen = lyxrc.plaintext_linelen;
2483 vector<string> backs = backends();
2484 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2485 // Get shortest path to format
2486 Graph::EdgePath path;
2487 for (vector<string>::const_iterator it = backs.begin();
2488 it != backs.end(); ++it) {
2489 Graph::EdgePath p = theConverters().getPath(*it, format);
2490 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2491 backend_format = *it;
2496 runparams.flavor = theConverters().getFlavor(path);
2498 Alert::error(_("Couldn't export file"),
2499 bformat(_("No information for exporting the format %1$s."),
2500 formats.prettyName(format)));
2504 backend_format = format;
2505 // FIXME: Don't hardcode format names here, but use a flag
2506 if (backend_format == "pdflatex")
2507 runparams.flavor = OutputParams::PDFLATEX;
2510 string filename = latexName(false);
2511 filename = addName(temppath(), filename);
2512 filename = changeExtension(filename,
2513 formats.extension(backend_format));
2516 updateMacroInstances();
2518 // Plain text backend
2519 if (backend_format == "text")
2520 writePlaintextFile(*this, FileName(filename), runparams);
2522 else if (backend_format == "lyx")
2523 writeFile(FileName(filename));
2525 else if (isDocBook()) {
2526 runparams.nice = !put_in_tempdir;
2527 makeDocBookFile(FileName(filename), runparams);
2530 else if (backend_format == format) {
2531 runparams.nice = true;
2532 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2534 } else if (!lyxrc.tex_allows_spaces
2535 && contains(filePath(), ' ')) {
2536 Alert::error(_("File name error"),
2537 _("The directory path to the document cannot contain spaces."));
2540 runparams.nice = false;
2541 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2545 string const error_type = (format == "program")
2546 ? "Build" : bufferFormat();
2547 ErrorList & error_list = d->errorLists[error_type];
2548 string const ext = formats.extension(format);
2549 FileName const tmp_result_file(changeExtension(filename, ext));
2550 bool const success = theConverters().convert(this, FileName(filename),
2551 tmp_result_file, FileName(absFileName()), backend_format, format,
2553 // Emit the signal to show the error list.
2554 if (format != backend_format)
2559 if (put_in_tempdir) {
2560 result_file = tmp_result_file.absFilename();
2564 result_file = changeExtension(absFileName(), ext);
2565 // We need to copy referenced files (e. g. included graphics
2566 // if format == "dvi") to the result dir.
2567 vector<ExportedFile> const files =
2568 runparams.exportdata->externalFiles(format);
2569 string const dest = onlyPath(result_file);
2570 CopyStatus status = SUCCESS;
2571 for (vector<ExportedFile>::const_iterator it = files.begin();
2572 it != files.end() && status != CANCEL; ++it) {
2573 string const fmt = formats.getFormatFromFile(it->sourceName);
2574 status = copyFile(fmt, it->sourceName,
2575 makeAbsPath(it->exportName, dest),
2576 it->exportName, status == FORCE);
2578 if (status == CANCEL) {
2579 message(_("Document export cancelled."));
2580 } else if (tmp_result_file.exists()) {
2581 // Finally copy the main file
2582 status = copyFile(format, tmp_result_file,
2583 FileName(result_file), result_file,
2585 message(bformat(_("Document exported as %1$s "
2587 formats.prettyName(format),
2588 makeDisplayPath(result_file)));
2590 // This must be a dummy converter like fax (bug 1888)
2591 message(bformat(_("Document exported as %1$s"),
2592 formats.prettyName(format)));
2599 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2602 return doExport(format, put_in_tempdir, result_file);
2606 bool Buffer::preview(string const & format) const
2609 if (!doExport(format, true, result_file))
2611 return formats.view(*this, FileName(result_file), format);
2615 bool Buffer::isExportable(string const & format) const
2617 vector<string> backs = backends();
2618 for (vector<string>::const_iterator it = backs.begin();
2619 it != backs.end(); ++it)
2620 if (theConverters().isReachable(*it, format))
2626 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2628 vector<string> backs = backends();
2629 vector<Format const *> result =
2630 theConverters().getReachable(backs[0], only_viewable, true);
2631 for (vector<string>::const_iterator it = backs.begin() + 1;
2632 it != backs.end(); ++it) {
2633 vector<Format const *> r =
2634 theConverters().getReachable(*it, only_viewable, false);
2635 result.insert(result.end(), r.begin(), r.end());
2641 vector<string> Buffer::backends() const
2644 if (params().baseClass()->isTeXClassAvailable()) {
2645 v.push_back(bufferFormat());
2646 // FIXME: Don't hardcode format names here, but use a flag
2647 if (v.back() == "latex")
2648 v.push_back("pdflatex");
2650 v.push_back("text");
2656 bool Buffer::readFileHelper(FileName const & s)
2658 // File information about normal file
2660 docstring const file = makeDisplayPath(s.absFilename(), 50);
2661 docstring text = bformat(_("The specified document\n%1$s"
2662 "\ncould not be read."), file);
2663 Alert::error(_("Could not read document"), text);
2667 // Check if emergency save file exists and is newer.
2668 FileName const e(s.absFilename() + ".emergency");
2670 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2671 docstring const file = makeDisplayPath(s.absFilename(), 20);
2672 docstring const text =
2673 bformat(_("An emergency save of the document "
2675 "Recover emergency save?"), file);
2676 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2677 _("&Recover"), _("&Load Original"),
2681 // the file is not saved if we load the emergency file.
2691 // Now check if autosave file is newer.
2692 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2694 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2695 docstring const file = makeDisplayPath(s.absFilename(), 20);
2696 docstring const text =
2697 bformat(_("The backup of the document "
2698 "%1$s is newer.\n\nLoad the "
2699 "backup instead?"), file);
2700 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2701 _("&Load backup"), _("Load &original"),
2705 // the file is not saved if we load the autosave file.
2709 // Here we delete the autosave
2720 bool Buffer::loadLyXFile(FileName const & s)
2722 if (s.isReadableFile()) {
2723 if (readFileHelper(s)) {
2724 lyxvc().file_found_hook(s);
2725 if (!s.isWritable())
2730 docstring const file = makeDisplayPath(s.absFilename(), 20);
2731 // Here we probably should run
2732 if (LyXVC::file_not_found_hook(s)) {
2733 docstring const text =
2734 bformat(_("Do you want to retrieve the document"
2735 " %1$s from version control?"), file);
2736 int const ret = Alert::prompt(_("Retrieve from version control?"),
2737 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2740 // How can we know _how_ to do the checkout?
2741 // With the current VC support it has to be,
2742 // a RCS file since CVS do not have special ,v files.
2744 return loadLyXFile(s);
2752 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2754 TeXErrors::Errors::const_iterator cit = terr.begin();
2755 TeXErrors::Errors::const_iterator end = terr.end();
2757 for (; cit != end; ++cit) {
2760 int errorRow = cit->error_in_line;
2761 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2767 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2768 } while (found && id_start == id_end && pos_start == pos_end);
2770 errorList.push_back(ErrorItem(cit->error_desc,
2771 cit->error_text, id_start, pos_start, pos_end));
2776 void Buffer::setBuffersForInsets() const
2778 inset().setBuffer(const_cast<Buffer &>(*this));
2782 void Buffer::updateLabels(UpdateScope scope) const
2784 // Use the master text class also for child documents
2785 Buffer const * const master = masterBuffer();
2786 DocumentClass const & textclass = master->params().documentClass();
2788 // keep the buffers to be children in this set. If the call from the
2789 // master comes back we can see which of them were actually seen (i.e.
2790 // via an InsetInclude). The remaining ones in the set need still be updated.
2791 static std::set<Buffer const *> bufToUpdate;
2792 if (scope == UpdateMaster) {
2793 // If this is a child document start with the master
2794 if (master != this) {
2795 bufToUpdate.insert(this);
2796 master->updateLabels();
2797 // Do this here in case the master has no gui associated with it. Then,
2798 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
2802 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
2803 if (bufToUpdate.find(this) == bufToUpdate.end())
2807 // start over the counters in the master
2808 textclass.counters().reset();
2811 // update will be done below for this buffer
2812 bufToUpdate.erase(this);
2814 // update all caches
2815 clearReferenceCache();
2818 Buffer & cbuf = const_cast<Buffer &>(*this);
2820 LASSERT(!text().paragraphs().empty(), /**/);
2823 ParIterator parit = cbuf.par_iterator_begin();
2824 updateLabels(parit);
2827 // TocBackend update will be done later.
2830 cbuf.tocBackend().update();
2831 if (scope == UpdateMaster)
2832 cbuf.structureChanged();
2836 static depth_type getDepth(DocIterator const & it)
2838 depth_type depth = 0;
2839 for (size_t i = 0 ; i < it.depth() ; ++i)
2840 if (!it[i].inset().inMathed())
2841 depth += it[i].paragraph().getDepth() + 1;
2842 // remove 1 since the outer inset does not count
2846 static depth_type getItemDepth(ParIterator const & it)
2848 Paragraph const & par = *it;
2849 LabelType const labeltype = par.layout().labeltype;
2851 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
2854 // this will hold the lowest depth encountered up to now.
2855 depth_type min_depth = getDepth(it);
2856 ParIterator prev_it = it;
2859 --prev_it.top().pit();
2861 // start of nested inset: go to outer par
2863 if (prev_it.empty()) {
2864 // start of document: nothing to do
2869 // We search for the first paragraph with same label
2870 // that is not more deeply nested.
2871 Paragraph & prev_par = *prev_it;
2872 depth_type const prev_depth = getDepth(prev_it);
2873 if (labeltype == prev_par.layout().labeltype) {
2874 if (prev_depth < min_depth)
2875 return prev_par.itemdepth + 1;
2876 if (prev_depth == min_depth)
2877 return prev_par.itemdepth;
2879 min_depth = min(min_depth, prev_depth);
2880 // small optimization: if we are at depth 0, we won't
2881 // find anything else
2882 if (prev_depth == 0)
2888 static bool needEnumCounterReset(ParIterator const & it)
2890 Paragraph const & par = *it;
2891 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
2892 depth_type const cur_depth = par.getDepth();
2893 ParIterator prev_it = it;
2894 while (prev_it.pit()) {
2895 --prev_it.top().pit();
2896 Paragraph const & prev_par = *prev_it;
2897 if (prev_par.getDepth() <= cur_depth)
2898 return prev_par.layout().labeltype != LABEL_ENUMERATE;
2900 // start of nested inset: reset
2905 // set the label of a paragraph. This includes the counters.
2906 static void setLabel(Buffer const & buf, ParIterator & it)
2908 BufferParams const & bp = buf.masterBuffer()->params();
2909 DocumentClass const & textclass = bp.documentClass();
2910 Paragraph & par = it.paragraph();
2911 Layout const & layout = par.layout();
2912 Counters & counters = textclass.counters();
2914 if (par.params().startOfAppendix()) {
2915 // FIXME: only the counter corresponding to toplevel
2916 // sectionning should be reset
2918 counters.appendix(true);
2920 par.params().appendix(counters.appendix());
2922 // Compute the item depth of the paragraph
2923 par.itemdepth = getItemDepth(it);
2925 if (layout.margintype == MARGIN_MANUAL) {
2926 if (par.params().labelWidthString().empty())
2927 par.params().labelWidthString(par.translateIfPossible(layout.labelstring(), bp));
2929 par.params().labelWidthString(docstring());
2932 switch(layout.labeltype) {
2934 if (layout.toclevel <= bp.secnumdepth
2935 && (layout.latextype != LATEX_ENVIRONMENT
2936 || isFirstInSequence(it.pit(), it.plist()))) {
2937 counters.step(layout.counter);
2938 par.params().labelString(
2939 par.expandLabel(layout, bp));
2941 par.params().labelString(docstring());
2944 case LABEL_ITEMIZE: {
2945 // At some point of time we should do something more
2946 // clever here, like:
2947 // par.params().labelString(
2948 // bp.user_defined_bullet(par.itemdepth).getText());
2949 // for now, use a simple hardcoded label
2950 docstring itemlabel;
2951 switch (par.itemdepth) {
2953 itemlabel = char_type(0x2022);
2956 itemlabel = char_type(0x2013);
2959 itemlabel = char_type(0x2217);
2962 itemlabel = char_type(0x2219); // or 0x00b7
2965 par.params().labelString(itemlabel);
2969 case LABEL_ENUMERATE: {
2970 // FIXME: Yes I know this is a really, really! bad solution
2972 docstring enumcounter = from_ascii("enum");
2974 switch (par.itemdepth) {
2983 enumcounter += "iv";
2986 // not a valid enumdepth...
2990 // Maybe we have to reset the enumeration counter.
2991 if (needEnumCounterReset(it))
2992 counters.reset(enumcounter);
2994 counters.step(enumcounter);
2998 switch (par.itemdepth) {
3000 format = N_("\\arabic{enumi}.");
3003 format = N_("(\\alph{enumii})");
3006 format = N_("\\roman{enumiii}.");
3009 format = N_("\\Alph{enumiv}.");
3012 // not a valid enumdepth...
3016 par.params().labelString(counters.counterLabel(
3017 par.translateIfPossible(from_ascii(format), bp)));
3022 case LABEL_SENSITIVE: {
3023 string const & type = counters.current_float();
3024 docstring full_label;
3026 full_label = buf.B_("Senseless!!! ");
3028 docstring name = buf.B_(textclass.floats().getType(type).name());
3029 if (counters.hasCounter(from_utf8(type))) {
3030 counters.step(from_utf8(type));
3031 full_label = bformat(from_ascii("%1$s %2$s:"),
3033 counters.theCounter(from_utf8(type)));
3035 full_label = bformat(from_ascii("%1$s #:"), name);
3037 par.params().labelString(full_label);
3041 case LABEL_NO_LABEL:
3042 par.params().labelString(docstring());
3046 case LABEL_TOP_ENVIRONMENT:
3047 case LABEL_CENTERED_TOP_ENVIRONMENT:
3050 par.params().labelString(
3051 par.translateIfPossible(layout.labelstring(), bp));
3057 void Buffer::updateLabels(ParIterator & parit) const
3059 LASSERT(parit.pit() == 0, /**/);
3061 // set the position of the text in the buffer to be able
3062 // to resolve macros in it. This has nothing to do with
3063 // labels, but by putting it here we avoid implementing
3064 // a whole bunch of traversal routines just for this call.
3065 parit.text()->setMacrocontextPosition(parit);
3067 depth_type maxdepth = 0;
3068 pit_type const lastpit = parit.lastpit();
3069 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
3070 // reduce depth if necessary
3071 parit->params().depth(min(parit->params().depth(), maxdepth));
3072 maxdepth = parit->getMaxDepthAfter();
3074 // set the counter for this paragraph
3075 setLabel(*this, parit);
3078 InsetList::const_iterator iit = parit->insetList().begin();
3079 InsetList::const_iterator end = parit->insetList().end();
3080 for (; iit != end; ++iit) {
3081 parit.pos() = iit->pos;
3082 iit->inset->updateLabels(parit);
3088 bool Buffer::nextWord(DocIterator & from, DocIterator & to,
3089 docstring & word) const
3091 bool inword = false;
3092 bool ignoreword = false;
3094 // Go backward a bit if needed in order to return the word currently
3095 // pointed by 'from'.
3096 while (from && from.pos() && isLetter(from))
3098 // OK, we start from here.
3100 while (to.depth()) {
3107 lang_code = to.paragraph().getFontSettings(params(),
3108 to.pos()).language()->code();
3110 // Insets like optional hyphens and ligature
3111 // break are part of a word.
3112 if (!to.paragraph().isInset(to.pos())) {
3113 char_type const c = to.paragraph().getChar(to.pos());
3118 } else { // !isLetter(cur)
3119 if (inword && !word.empty() && !ignoreword)
3131 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
3132 WordLangTuple & word_lang, docstring_list & suggestions) const
3135 SpellChecker::Result res = SpellChecker::OK;
3136 SpellChecker * speller = theSpellChecker();
3137 suggestions.clear();
3139 while (nextWord(from, to, word)) {
3141 string lang_code = lyxrc.spellchecker_use_alt_lang
3142 ? lyxrc.spellchecker_alt_lang
3143 : from.paragraph().getFontSettings(params(), from.pos()).language()->code();
3144 WordLangTuple wl(word, lang_code);
3145 res = speller->check(wl);
3146 // ... just bail out if the spellchecker reports an error.
3147 if (!speller->error().empty()) {
3148 throw ExceptionMessage(WarningException,
3149 _("The spellchecker has failed."), speller->error());
3151 if (res != SpellChecker::OK && res != SpellChecker::IGNORED_WORD) {
3157 while (!(word = speller->nextMiss()).empty())
3158 suggestions.push_back(word);