]> git.lyx.org Git - lyx.git/blob - src/buffer.C
tostr -> convert and some bformat work
[lyx.git] / src / buffer.C
1 /**
2  * \file buffer.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "buffer.h"
14
15 #include "author.h"
16 #include "buffer_funcs.h"
17 #include "bufferlist.h"
18 #include "bufferparams.h"
19 #include "counters.h"
20 #include "Bullet.h"
21 #include "Chktex.h"
22 #include "debug.h"
23 #include "encoding.h"
24 #include "errorlist.h"
25 #include "exporter.h"
26 #include "format.h"
27 #include "funcrequest.h"
28 #include "gettext.h"
29 #include "insetiterator.h"
30 #include "language.h"
31 #include "LaTeX.h"
32 #include "LaTeXFeatures.h"
33 #include "LyXAction.h"
34 #include "lyxlex.h"
35 #include "lyxtext.h"
36 #include "lyxrc.h"
37 #include "lyxvc.h"
38 #include "lyx_main.h"
39 #include "messages.h"
40 #include "output.h"
41 #include "output_docbook.h"
42 #include "output_latex.h"
43 #include "output_linuxdoc.h"
44 #include "paragraph.h"
45 #include "paragraph_funcs.h"
46 #include "ParagraphParameters.h"
47 #include "pariterator.h"
48 #include "sgml.h"
49 #include "texrow.h"
50 #include "undo.h"
51 #include "version.h"
52
53 #include "insets/insetbibitem.h"
54 #include "insets/insetbibtex.h"
55 #include "insets/insetinclude.h"
56 #include "insets/insettext.h"
57
58 #include "mathed/math_macrotemplate.h"
59 #include "mathed/math_macrotable.h"
60 #include "mathed/math_support.h"
61
62 #include "frontends/Alert.h"
63
64 #include "graphics/Previews.h"
65
66 #include "support/FileInfo.h"
67 #include "support/filetools.h"
68 #include "support/gzstream.h"
69 #include "support/lyxlib.h"
70 #include "support/os.h"
71 #include "support/path.h"
72 #include "support/textutils.h"
73 #include "support/tostr.h"
74
75 #include <boost/bind.hpp>
76
77 #include <utime.h>
78
79 #include <iomanip>
80 #include <stack>
81 #include <sstream>
82
83
84 using lyx::pos_type;
85 using lyx::pit_type;
86
87 using lyx::support::AddName;
88 using lyx::support::bformat;
89 using lyx::support::ChangeExtension;
90 using lyx::support::cmd_ret;
91 using lyx::support::createBufferTmpDir;
92 using lyx::support::destroyDir;
93 using lyx::support::FileInfo;
94 using lyx::support::FileInfo;
95 using lyx::support::getFormatFromContents;
96 using lyx::support::IsDirWriteable;
97 using lyx::support::IsFileWriteable;
98 using lyx::support::LibFileSearch;
99 using lyx::support::ltrim;
100 using lyx::support::MakeAbsPath;
101 using lyx::support::MakeDisplayPath;
102 using lyx::support::MakeLatexName;
103 using lyx::support::OnlyFilename;
104 using lyx::support::OnlyPath;
105 using lyx::support::Path;
106 using lyx::support::QuoteName;
107 using lyx::support::removeAutosaveFile;
108 using lyx::support::rename;
109 using lyx::support::RunCommand;
110 using lyx::support::split;
111 using lyx::support::strToInt;
112 using lyx::support::subst;
113 using lyx::support::tempName;
114 using lyx::support::trim;
115
116 namespace os = lyx::support::os;
117
118 using std::endl;
119 using std::for_each;
120 using std::make_pair;
121
122 using std::ifstream;
123 using std::ios;
124 using std::map;
125 using std::ostream;
126 using std::ostringstream;
127 using std::ofstream;
128 using std::pair;
129 using std::stack;
130 using std::vector;
131 using std::string;
132
133
134 // all these externs should eventually be removed.
135 extern BufferList bufferlist;
136
137 namespace {
138
139 int const LYX_FORMAT = 238;
140
141 } // namespace anon
142
143
144 typedef std::map<string, bool> DepClean;
145
146 struct Buffer::Impl
147 {
148         Impl(Buffer & parent, string const & file, bool readonly);
149
150         limited_stack<Undo> undostack;
151         limited_stack<Undo> redostack;
152         BufferParams params;
153         LyXVC lyxvc;
154         string temppath;
155         TexRow texrow;
156
157         /// need to regenerate .tex?
158         DepClean dep_clean;
159
160         /// is save needed?
161         mutable bool lyx_clean;
162
163         /// is autosave needed?
164         mutable bool bak_clean;
165
166         /// is this a unnamed file (New...)?
167         bool unnamed;
168
169         /// buffer is r/o
170         bool read_only;
171
172         /// name of the file the buffer is associated with.
173         string filename;
174
175         /// The path to the document file.
176         string filepath;
177
178         boost::scoped_ptr<Messages> messages;
179
180         /** Set to true only when the file is fully loaded.
181          *  Used to prevent the premature generation of previews
182          *  and by the citation inset.
183          */
184         bool file_fully_loaded;
185
186         /// our LyXText that should be wrapped in an InsetText
187         InsetText inset;
188
189         ///
190         MacroTable macros;
191 };
192
193
194 Buffer::Impl::Impl(Buffer & parent, string const & file, bool readonly_)
195         : lyx_clean(true), bak_clean(true), unnamed(false), read_only(readonly_),
196           filename(file), filepath(OnlyPath(file)), file_fully_loaded(false),
197                 inset(params)
198 {
199         lyxvc.buffer(&parent);
200         temppath = createBufferTmpDir();
201         // FIXME: And now do something if temppath == string(), because we
202         // assume from now on that temppath points to a valid temp dir.
203         // See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg67406.html
204 }
205
206
207 Buffer::Buffer(string const & file, bool ronly)
208         : pimpl_(new Impl(*this, file, ronly))
209 {
210         lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
211 }
212
213
214 Buffer::~Buffer()
215 {
216         lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
217         // here the buffer should take care that it is
218         // saved properly, before it goes into the void.
219
220         closing();
221
222         if (!temppath().empty() && destroyDir(temppath()) != 0) {
223                 Alert::warning(_("Could not remove temporary directory"),
224                         bformat(_("Could not remove the temporary directory %1$s"), temppath()));
225         }
226
227         // Remove any previewed LaTeX snippets associated with this buffer.
228         lyx::graphics::Previews::get().removeLoader(*this);
229 }
230
231
232 LyXText & Buffer::text() const
233 {
234         return const_cast<LyXText &>(pimpl_->inset.text_);
235 }
236
237
238 InsetBase & Buffer::inset() const
239 {
240         return const_cast<InsetText &>(pimpl_->inset);
241 }
242
243
244 limited_stack<Undo> & Buffer::undostack()
245 {
246         return pimpl_->undostack;
247 }
248
249
250 limited_stack<Undo> const & Buffer::undostack() const
251 {
252         return pimpl_->undostack;
253 }
254
255
256 limited_stack<Undo> & Buffer::redostack()
257 {
258         return pimpl_->redostack;
259 }
260
261
262 limited_stack<Undo> const & Buffer::redostack() const
263 {
264         return pimpl_->redostack;
265 }
266
267
268 BufferParams & Buffer::params()
269 {
270         return pimpl_->params;
271 }
272
273
274 BufferParams const & Buffer::params() const
275 {
276         return pimpl_->params;
277 }
278
279
280 ParagraphList & Buffer::paragraphs()
281 {
282         return text().paragraphs();
283 }
284
285
286 ParagraphList const & Buffer::paragraphs() const
287 {
288         return text().paragraphs();
289 }
290
291
292 LyXVC & Buffer::lyxvc()
293 {
294         return pimpl_->lyxvc;
295 }
296
297
298 LyXVC const & Buffer::lyxvc() const
299 {
300         return pimpl_->lyxvc;
301 }
302
303
304 string const & Buffer::temppath() const
305 {
306         return pimpl_->temppath;
307 }
308
309
310 TexRow & Buffer::texrow()
311 {
312         return pimpl_->texrow;
313 }
314
315
316 TexRow const & Buffer::texrow() const
317 {
318         return pimpl_->texrow;
319 }
320
321
322 string const Buffer::getLatexName(bool const no_path) const
323 {
324         string const name = ChangeExtension(MakeLatexName(fileName()), ".tex");
325         return no_path ? OnlyFilename(name) : name;
326 }
327
328
329 pair<Buffer::LogType, string> const Buffer::getLogName() const
330 {
331         string const filename = getLatexName(false);
332
333         if (filename.empty())
334                 return make_pair(Buffer::latexlog, string());
335
336         string const path = temppath();
337
338         string const fname = AddName(path,
339                                      OnlyFilename(ChangeExtension(filename,
340                                                                   ".log")));
341         string const bname =
342                 AddName(path, OnlyFilename(
343                         ChangeExtension(filename,
344                                         formats.extension("literate") + ".out")));
345
346         // If no Latex log or Build log is newer, show Build log
347
348         FileInfo const f_fi(fname);
349         FileInfo const b_fi(bname);
350
351         if (b_fi.exist() &&
352             (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
353                 lyxerr[Debug::FILES] << "Log name calculated as: " << bname << endl;
354                 return make_pair(Buffer::buildlog, bname);
355         }
356         lyxerr[Debug::FILES] << "Log name calculated as: " << fname << endl;
357         return make_pair(Buffer::latexlog, fname);
358 }
359
360
361 void Buffer::setReadonly(bool const flag)
362 {
363         if (pimpl_->read_only != flag) {
364                 pimpl_->read_only = flag;
365                 readonly(flag);
366         }
367 }
368
369
370 void Buffer::setFileName(string const & newfile)
371 {
372         pimpl_->filename = MakeAbsPath(newfile);
373         pimpl_->filepath = OnlyPath(pimpl_->filename);
374         setReadonly(IsFileWriteable(pimpl_->filename) == 0);
375         updateTitles();
376 }
377
378
379 // We'll remove this later. (Lgb)
380 namespace {
381
382 void unknownClass(string const & unknown)
383 {
384         Alert::warning(_("Unknown document class"),
385                 bformat(_("Using the default document class, because the "
386                         "class %1$s is unknown."), unknown));
387 }
388
389 } // anon
390
391
392 int Buffer::readHeader(LyXLex & lex)
393 {
394         int unknown_tokens = 0;
395         int line = -1;
396         int begin_header_line = -1;
397
398         while (lex.isOK()) {
399                 lex.next();
400                 string const token = lex.getString();
401
402                 if (token.empty())
403                         continue;
404
405                 if (token == "\\end_header")
406                         break;
407
408                 ++line;
409                 if (token == "\\begin_header") {
410                         begin_header_line = line;
411                         continue;
412                 }
413
414                 lyxerr[Debug::PARSER] << "Handling header token: `"
415                                       << token << '\'' << endl;
416
417                 string unknown = params().readToken(lex, token);
418                 if (!unknown.empty()) {
419                         if (unknown[0] != '\\' and token == "\\textclass") {
420                                 unknownClass(unknown);
421                         } else {
422                                 ++unknown_tokens;
423                                 string const s = bformat(_("Unknown token: "
424                                                            "%1$s %2$s\n"),
425                                                          token,
426                                                          lex.getString());
427                                 error(ErrorItem(_("Header error"), s,
428                                                 -1, 0, 0));
429                         }
430                 }
431         }
432         if (begin_header_line) {
433                 string const s = _("\\begin_header is missing");
434                 error(ErrorItem(_("Header error"), s, -1, 0, 0));
435         }
436         return unknown_tokens;
437 }
438
439
440 // Uwe C. Schroeder
441 // changed to be public and have one parameter
442 // Returns false if "\end_document" is not read (Asger)
443 bool Buffer::readDocument(LyXLex & lex)
444 {
445         lex.next();
446         string const token = lex.getString();
447         if (token != "\\begin_document") {
448                 string const s = _("\\begin_document is missing");
449                 error(ErrorItem(_("Header error"), s, -1, 0, 0));
450         }
451
452         if (paragraphs().empty()) {
453                 readHeader(lex);
454                 if (!params().getLyXTextClass().load()) {
455                         string theclass = params().getLyXTextClass().name();
456                         Alert::error(_("Can't load document class"), bformat(
457                                         "Using the default document class, because the "
458                                         " class %1$s could not be loaded.", theclass));
459                         params().textclass = 0;
460                 }
461         } else {
462                 // We don't want to adopt the parameters from the
463                 // document we insert, so read them into a temporary buffer
464                 // and then discard it
465
466                 Buffer tmpbuf("", false);
467                 tmpbuf.readHeader(lex);
468         }
469
470         return text().read(*this, lex);
471 }
472
473
474 // needed to insert the selection
475 void Buffer::insertStringAsLines(ParagraphList & pars,
476         pit_type & par, pos_type & pos,
477         LyXFont const & fn, string const & str, bool autobreakrows)
478 {
479         LyXLayout_ptr const & layout = pars[par].layout();
480
481         LyXFont font = fn;
482
483         pars[par].checkInsertChar(font);
484         // insert the string, don't insert doublespace
485         bool space_inserted = true;
486         for (string::const_iterator cit = str.begin();
487             cit != str.end(); ++cit) {
488                 if (*cit == '\n') {
489                         if (autobreakrows && (!pars[par].empty() || pars[par].allowEmpty())) {
490                                 breakParagraph(params(), paragraphs(), par, pos,
491                                                layout->isEnvironment());
492                                 ++par;
493                                 pos = 0;
494                                 space_inserted = true;
495                         } else {
496                                 continue;
497                         }
498                         // do not insert consecutive spaces if !free_spacing
499                 } else if ((*cit == ' ' || *cit == '\t') &&
500                            space_inserted && !pars[par].isFreeSpacing()) {
501                         continue;
502                 } else if (*cit == '\t') {
503                         if (!pars[par].isFreeSpacing()) {
504                                 // tabs are like spaces here
505                                 pars[par].insertChar(pos, ' ', font);
506                                 ++pos;
507                                 space_inserted = true;
508                         } else {
509                                 const pos_type n = 8 - pos % 8;
510                                 for (pos_type i = 0; i < n; ++i) {
511                                         pars[par].insertChar(pos, ' ', font);
512                                         ++pos;
513                                 }
514                                 space_inserted = true;
515                         }
516                 } else if (!IsPrintable(*cit)) {
517                         // Ignore unprintables
518                         continue;
519                 } else {
520                         // just insert the character
521                         pars[par].insertChar(pos, *cit, font);
522                         ++pos;
523                         space_inserted = (*cit == ' ');
524                 }
525
526         }
527 }
528
529
530 bool Buffer::readFile(string const & filename)
531 {
532         // Check if the file is compressed.
533         string const format = getFormatFromContents(filename);
534         if (format == "gzip" || format == "zip" || format == "compress") {
535                 params().compressed = true;
536         }
537
538         // remove dummy empty par
539         paragraphs().clear();
540         bool ret = readFile(filename, paragraphs().size());
541
542         // After we have read a file, we must ensure that the buffer
543         // language is set and used in the gui.
544         // If you know of a better place to put this, please tell me. (Lgb)
545         updateDocLang(params().language);
546
547         return ret;
548 }
549
550
551 bool Buffer::readFile(string const & filename, pit_type const pit)
552 {
553         LyXLex lex(0, 0);
554         lex.setFile(filename);
555         return readFile(lex, filename, pit);
556 }
557
558
559 bool Buffer::fully_loaded() const
560 {
561         return pimpl_->file_fully_loaded;
562 }
563
564
565 void Buffer::fully_loaded(bool const value)
566 {
567         pimpl_->file_fully_loaded = value;
568 }
569
570
571 bool Buffer::readFile(LyXLex & lex, string const & filename, pit_type const pit)
572 {
573         BOOST_ASSERT(!filename.empty());
574
575         if (!lex.isOK()) {
576                 Alert::error(_("Document could not be read"),
577                              bformat(_("%1$s could not be read."), filename));
578                 return false;
579         }
580
581         lex.next();
582         string const token(lex.getString());
583
584         if (!lex.isOK()) {
585                 Alert::error(_("Document could not be read"),
586                              bformat(_("%1$s could not be read."), filename));
587                 return false;
588         }
589
590         // the first token _must_ be...
591         if (token != "\\lyxformat") {
592                 lyxerr << "Token: " << token << endl;
593
594                 Alert::error(_("Document format failure"),
595                              bformat(_("%1$s is not a LyX document."),
596                                        filename));
597                 return false;
598         }
599
600         lex.next();
601         string tmp_format = lex.getString();
602         //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
603         // if present remove ".," from string.
604         string::size_type dot = tmp_format.find_first_of(".,");
605         //lyxerr << "           dot found at " << dot << endl;
606         if (dot != string::npos)
607                         tmp_format.erase(dot, 1);
608         int file_format = strToInt(tmp_format);
609         //lyxerr << "format: " << file_format << endl;
610
611         if (file_format != LYX_FORMAT) {
612                 string const tmpfile = tempName();
613                 if (tmpfile.empty()) {
614                         Alert::error(_("Conversion failed"),
615                                      bformat(_("%1$s is from an earlier"
616                                               " version of LyX, but a temporary"
617                                               " file for converting it could"
618                                               " not be created."),
619                                               filename));
620                         return false;
621                 }
622                 string command = LibFileSearch("lyx2lyx", "lyx2lyx");
623                 if (command.empty()) {
624                         Alert::error(_("Conversion script not found"),
625                                      bformat(_("%1$s is from an earlier"
626                                                " version of LyX, but the"
627                                                " conversion script lyx2lyx"
628                                                " could not be found."),
629                                                filename));
630                         return false;
631                 }
632                 command += " -t"
633                         + convert<string>(LYX_FORMAT)
634                         + " -o " + tmpfile + ' '
635                         + QuoteName(filename);
636                 lyxerr[Debug::INFO] << "Running '"
637                                     << command << '\''
638                                     << endl;
639                 cmd_ret const ret = RunCommand(command);
640                 if (ret.first != 0) {
641                         Alert::error(_("Conversion script failed"),
642                                      bformat(_("%1$s is from an earlier version"
643                                               " of LyX, but the lyx2lyx script"
644                                               " failed to convert it."),
645                                               filename));
646                         return false;
647                 } else {
648                         bool ret = readFile(tmpfile, pit);
649                         // Do stuff with tmpfile name and buffer name here.
650                         return ret;
651                 }
652
653         }
654
655         if (readDocument(lex)) {
656                 Alert::error(_("Document format failure"),
657                              bformat(_("%1$s ended unexpectedly, which means"
658                                        " that it is probably corrupted."),
659                                        filename));
660         }
661
662         //lyxerr << "removing " << MacroTable::localMacros().size()
663         //      << " temporary macro entries" << endl;
664         //MacroTable::localMacros().clear();
665         params().setPaperStuff();
666
667         pimpl_->file_fully_loaded = true;
668         return true;
669 }
670
671
672 // Should probably be moved to somewhere else: BufferView? LyXView?
673 bool Buffer::save() const
674 {
675         // We don't need autosaves in the immediate future. (Asger)
676         resetAutosaveTimers();
677
678         // make a backup
679         string s;
680         if (lyxrc.make_backup) {
681                 s = fileName() + '~';
682                 if (!lyxrc.backupdir_path.empty())
683                         s = AddName(lyxrc.backupdir_path,
684                                     subst(os::internal_path(s),'/','!'));
685
686                 // Rename is the wrong way of making a backup,
687                 // this is the correct way.
688                 /* truss cp fil fil2:
689                    lstat("LyXVC3.lyx", 0xEFFFF898)                 Err#2 ENOENT
690                    stat("LyXVC.lyx", 0xEFFFF688)                   = 0
691                    open("LyXVC.lyx", O_RDONLY)                     = 3
692                    open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
693                    fstat(4, 0xEFFFF508)                            = 0
694                    fstat(3, 0xEFFFF508)                            = 0
695                    read(3, " # T h i s   f i l e   w".., 8192)     = 5579
696                    write(4, " # T h i s   f i l e   w".., 5579)    = 5579
697                    read(3, 0xEFFFD4A0, 8192)                       = 0
698                    close(4)                                        = 0
699                    close(3)                                        = 0
700                    chmod("LyXVC3.lyx", 0100644)                    = 0
701                    lseek(0, 0, SEEK_CUR)                           = 46440
702                    _exit(0)
703                 */
704
705                 // Should probably have some more error checking here.
706                 // Doing it this way, also makes the inodes stay the same.
707                 // This is still not a very good solution, in particular we
708                 // might loose the owner of the backup.
709                 FileInfo finfo(fileName());
710                 if (finfo.exist()) {
711                         mode_t fmode = finfo.getMode();
712                         struct utimbuf times = {
713                                 finfo.getAccessTime(),
714                                 finfo.getModificationTime() };
715
716                         ifstream ifs(fileName().c_str());
717                         ofstream ofs(s.c_str(), ios::out|ios::trunc);
718                         if (ifs && ofs) {
719                                 ofs << ifs.rdbuf();
720                                 ifs.close();
721                                 ofs.close();
722                                 ::chmod(s.c_str(), fmode);
723
724                                 if (::utime(s.c_str(), &times)) {
725                                         lyxerr << "utime error." << endl;
726                                 }
727                         } else {
728                                 lyxerr << "LyX was not able to make "
729                                         "backup copy. Beware." << endl;
730                         }
731                 }
732         }
733
734         if (writeFile(fileName())) {
735                 markClean();
736                 removeAutosaveFile(fileName());
737         } else {
738                 // Saving failed, so backup is not backup
739                 if (lyxrc.make_backup)
740                         rename(s, fileName());
741                 return false;
742         }
743         return true;
744 }
745
746
747 bool Buffer::writeFile(string const & fname) const
748 {
749         if (pimpl_->read_only && fname == fileName())
750                 return false;
751
752         FileInfo finfo(fname);
753         if (finfo.exist() && !finfo.writable())
754                 return false;
755
756         bool retval = false;
757
758         if (params().compressed) {
759                 gz::ogzstream ofs(fname.c_str());
760                 if (!ofs)
761                         return false;
762
763                 retval = do_writeFile(ofs);
764
765         } else {
766                 ofstream ofs(fname.c_str());
767                 if (!ofs)
768                         return false;
769
770                 retval = do_writeFile(ofs);
771         }
772
773         return retval;
774 }
775
776
777 bool Buffer::do_writeFile(ostream & ofs) const
778 {
779 #ifdef HAVE_LOCALE
780         // Use the standard "C" locale for file output.
781         ofs.imbue(std::locale::classic());
782 #endif
783
784         // The top of the file should not be written by params().
785
786         // write out a comment in the top of the file
787         ofs << "#LyX " << lyx_version
788             << " created this file. For more info see http://www.lyx.org/\n"
789             << "\\lyxformat " << LYX_FORMAT << "\n"
790             << "\\begin_document\n";
791
792         // now write out the buffer parameters.
793         ofs << "\\begin_header\n";
794         params().writeFile(ofs);
795         ofs << "\\end_header\n";
796
797         // write the text
798         ofs << "\n\\begin_body\n";
799         text().write(*this, ofs);
800         ofs << "\n\\end_body\n";
801
802         // Write marker that shows file is complete
803         ofs << "\\end_document" << endl;
804
805         // Shouldn't really be needed....
806         //ofs.close();
807
808         // how to check if close went ok?
809         // Following is an attempt... (BE 20001011)
810
811         // good() returns false if any error occured, including some
812         //        formatting error.
813         // bad()  returns true if something bad happened in the buffer,
814         //        which should include file system full errors.
815
816         bool status = true;
817         if (!ofs) {
818                 status = false;
819                 lyxerr << "File was not closed properly." << endl;
820         }
821
822         return status;
823 }
824
825
826 void Buffer::makeLaTeXFile(string const & fname,
827                            string const & original_path,
828                            OutputParams const & runparams,
829                            bool output_preamble, bool output_body)
830 {
831         lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
832
833         ofstream ofs;
834         if (!openFileWrite(ofs, fname))
835                 return;
836
837         makeLaTeXFile(ofs, original_path,
838                       runparams, output_preamble, output_body);
839
840         ofs.close();
841         if (ofs.fail())
842                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
843 }
844
845
846 void Buffer::makeLaTeXFile(ostream & os,
847                            string const & original_path,
848                            OutputParams const & runparams_in,
849                            bool const output_preamble, bool const output_body)
850 {
851         OutputParams runparams = runparams_in;
852
853         // validate the buffer.
854         lyxerr[Debug::LATEX] << "  Validating buffer..." << endl;
855         LaTeXFeatures features(*this, params(), runparams.nice);
856         validate(features);
857         lyxerr[Debug::LATEX] << "  Buffer validation done." << endl;
858
859         texrow().reset();
860
861         // The starting paragraph of the coming rows is the
862         // first paragraph of the document. (Asger)
863         texrow().start(paragraphs().begin()->id(), 0);
864
865         if (output_preamble && runparams.nice) {
866                 os << "%% LyX " << lyx_version << " created this file.  "
867                         "For more info, see http://www.lyx.org/.\n"
868                         "%% Do not edit unless you really know what "
869                         "you are doing.\n";
870                 texrow().newline();
871                 texrow().newline();
872         }
873         lyxerr[Debug::INFO] << "lyx header finished" << endl;
874         // There are a few differences between nice LaTeX and usual files:
875         // usual is \batchmode and has a
876         // special input@path to allow the including of figures
877         // with either \input or \includegraphics (what figinsets do).
878         // input@path is set when the actual parameter
879         // original_path is set. This is done for usual tex-file, but not
880         // for nice-latex-file. (Matthias 250696)
881         // Note that input@path is only needed for something the user does
882         // in the preamble, included .tex files or ERT, files included by
883         // LyX work without it.
884         if (output_preamble) {
885                 if (!runparams.nice) {
886                         // code for usual, NOT nice-latex-file
887                         os << "\\batchmode\n"; // changed
888                         // from \nonstopmode
889                         texrow().newline();
890                 }
891                 if (!original_path.empty()) {
892                         string inputpath = os::external_path(original_path);
893                         subst(inputpath, "~", "\\string~");
894                         os << "\\makeatletter\n"
895                             << "\\def\\input@path{{"
896                             << inputpath << "/}}\n"
897                             << "\\makeatother\n";
898                         texrow().newline();
899                         texrow().newline();
900                         texrow().newline();
901                 }
902
903                 // Write the preamble
904                 runparams.use_babel = params().writeLaTeX(os, features, texrow());
905
906                 if (!output_body)
907                         return;
908
909                 // make the body.
910                 os << "\\begin{document}\n";
911                 texrow().newline();
912         } // output_preamble
913         lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
914
915         if (!lyxrc.language_auto_begin) {
916                 os << subst(lyxrc.language_command_begin, "$$lang",
917                              params().language->babel())
918                     << endl;
919                 texrow().newline();
920         }
921
922         // if we are doing a real file with body, even if this is the
923         // child of some other buffer, let's cut the link here.
924         // This happens for example if only a child document is printed.
925         string save_parentname;
926         if (output_preamble) {
927                 save_parentname = params().parentname;
928                 params().parentname.erase();
929         }
930
931         // the real stuff
932         latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
933
934         // Restore the parenthood if needed
935         if (output_preamble)
936                 params().parentname = save_parentname;
937
938         // add this just in case after all the paragraphs
939         os << endl;
940         texrow().newline();
941
942         if (!lyxrc.language_auto_end) {
943                 os << subst(lyxrc.language_command_end, "$$lang",
944                              params().language->babel())
945                     << endl;
946                 texrow().newline();
947         }
948
949         if (output_preamble) {
950                 os << "\\end{document}\n";
951                 texrow().newline();
952
953                 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
954         } else {
955                 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
956                                      << endl;
957         }
958
959         // Just to be sure. (Asger)
960         texrow().newline();
961
962         lyxerr[Debug::INFO] << "Finished making LaTeX file." << endl;
963         lyxerr[Debug::INFO] << "Row count was " << texrow().rows() - 1
964                             << '.' << endl;
965 }
966
967
968 bool Buffer::isLatex() const
969 {
970         return params().getLyXTextClass().outputType() == LATEX;
971 }
972
973
974 bool Buffer::isLinuxDoc() const
975 {
976         return params().getLyXTextClass().outputType() == LINUXDOC;
977 }
978
979
980 bool Buffer::isLiterate() const
981 {
982         return params().getLyXTextClass().outputType() == LITERATE;
983 }
984
985
986 bool Buffer::isDocBook() const
987 {
988         return params().getLyXTextClass().outputType() == DOCBOOK;
989 }
990
991
992 bool Buffer::isSGML() const
993 {
994         LyXTextClass const & tclass = params().getLyXTextClass();
995
996         return tclass.outputType() == LINUXDOC ||
997                tclass.outputType() == DOCBOOK;
998 }
999
1000
1001 void Buffer::makeLinuxDocFile(string const & fname,
1002                               OutputParams const & runparams,
1003                               bool const body_only)
1004 {
1005         ofstream ofs;
1006         if (!openFileWrite(ofs, fname))
1007                 return;
1008
1009         LaTeXFeatures features(*this, params(), runparams.nice);
1010         validate(features);
1011
1012         texrow().reset();
1013
1014         LyXTextClass const & tclass = params().getLyXTextClass();
1015
1016         string const & top_element = tclass.latexname();
1017
1018         if (!body_only) {
1019                 ofs << tclass.class_header();
1020
1021                 string preamble = params().preamble;
1022                 string const name = runparams.nice ? ChangeExtension(pimpl_->filename, ".sgml")
1023                          : fname;
1024                 preamble += features.getIncludedFiles(name);
1025                 preamble += features.getLyXSGMLEntities();
1026
1027                 if (!preamble.empty()) {
1028                         ofs << " [ " << preamble << " ]";
1029                 }
1030                 ofs << ">\n\n";
1031
1032                 if (params().options.empty())
1033                         sgml::openTag(ofs, top_element);
1034                 else {
1035                         string top = top_element;
1036                         top += ' ';
1037                         top += params().options;
1038                         sgml::openTag(ofs, top);
1039                 }
1040         }
1041
1042         ofs << "<!-- LyX "  << lyx_version
1043             << " created this file. For more info see http://www.lyx.org/"
1044             << " -->\n";
1045
1046         linuxdocParagraphs(*this, paragraphs(), ofs, runparams);
1047
1048         if (!body_only) {
1049                 ofs << "\n\n";
1050                 sgml::closeTag(ofs, top_element);
1051         }
1052
1053         ofs.close();
1054         if (ofs.fail())
1055                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1056 }
1057
1058
1059 void Buffer::makeDocBookFile(string const & fname,
1060                              OutputParams const & runparams,
1061                              bool const only_body)
1062 {
1063         ofstream ofs;
1064         if (!openFileWrite(ofs, fname))
1065                 return;
1066
1067         LaTeXFeatures features(*this, params(), runparams.nice);
1068         validate(features);
1069
1070         texrow().reset();
1071
1072         LyXTextClass const & tclass = params().getLyXTextClass();
1073         string const & top_element = tclass.latexname();
1074
1075         if (!only_body) {
1076                 if (runparams.flavor == OutputParams::XML)
1077                         ofs << "<?xml version=\"1.0\" encoding=\""
1078                             << params().language->encoding()->Name() << "\"?>\n";
1079
1080                 ofs << "<!DOCTYPE " << top_element << " ";
1081
1082                 if (! tclass.class_header().empty()) ofs << tclass.class_header();
1083                 else if (runparams.flavor == OutputParams::XML)
1084                         ofs << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1085                             << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1086                 else
1087                         ofs << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1088
1089                 string preamble = params().preamble;
1090                 if (runparams.flavor != OutputParams::XML ) {
1091                         preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1092                         preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1093                         preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1094                         preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1095                 }
1096
1097                 string const name = runparams.nice ? ChangeExtension(pimpl_->filename, ".sgml")
1098                          : fname;
1099                 preamble += features.getIncludedFiles(name);
1100                 preamble += features.getLyXSGMLEntities();
1101
1102                 if (!preamble.empty()) {
1103                         ofs << "\n [ " << preamble << " ]";
1104                 }
1105                 ofs << ">\n\n";
1106         }
1107
1108         string top = top_element;
1109         top += " lang=\"";
1110         if (runparams.flavor == OutputParams::XML)
1111                 top += params().language->code();
1112         else
1113                 top += params().language->code().substr(0,2);
1114         top += '"';
1115
1116         if (!params().options.empty()) {
1117                 top += ' ';
1118                 top += params().options;
1119         }
1120
1121         ofs << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1122             << " file was created by LyX " << lyx_version
1123             << "\n  See http://www.lyx.org/ for more information -->\n";
1124
1125         params().getLyXTextClass().counters().reset();
1126
1127         sgml::openTag(ofs, top);
1128         ofs << '\n';
1129         docbookParagraphs(paragraphs(), *this, ofs, runparams);
1130         sgml::closeTag(ofs, top_element);
1131
1132         ofs.close();
1133         if (ofs.fail())
1134                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1135 }
1136
1137
1138 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1139 // Other flags: -wall -v0 -x
1140 int Buffer::runChktex()
1141 {
1142         busy(true);
1143
1144         // get LaTeX-Filename
1145         string const name = getLatexName();
1146         string const path = temppath();
1147         string const org_path = filePath();
1148
1149         Path p(path); // path to LaTeX file
1150         message(_("Running chktex..."));
1151
1152         // Generate the LaTeX file if neccessary
1153         OutputParams runparams;
1154         runparams.flavor = OutputParams::LATEX;
1155         runparams.nice = false;
1156         makeLaTeXFile(name, org_path, runparams);
1157
1158         TeXErrors terr;
1159         Chktex chktex(lyxrc.chktex_command, name, filePath());
1160         int const res = chktex.run(terr); // run chktex
1161
1162         if (res == -1) {
1163                 Alert::error(_("chktex failure"),
1164                              _("Could not run chktex successfully."));
1165         } else if (res > 0) {
1166                 // Insert all errors as errors boxes
1167                 bufferErrors(*this, terr);
1168         }
1169
1170         busy(false);
1171
1172         return res;
1173 }
1174
1175
1176 void Buffer::validate(LaTeXFeatures & features) const
1177 {
1178         LyXTextClass const & tclass = params().getLyXTextClass();
1179
1180         if (params().tracking_changes) {
1181                 features.require("dvipost");
1182                 features.require("color");
1183         }
1184
1185         // AMS Style is at document level
1186         if (params().use_amsmath == BufferParams::AMS_ON
1187             || tclass.provides(LyXTextClass::amsmath))
1188                 features.require("amsmath");
1189
1190         for_each(paragraphs().begin(), paragraphs().end(),
1191                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1192
1193         // the bullet shapes are buffer level not paragraph level
1194         // so they are tested here
1195         for (int i = 0; i < 4; ++i) {
1196                 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1197                         int const font = params().user_defined_bullet(i).getFont();
1198                         if (font == 0) {
1199                                 int const c = params()
1200                                         .user_defined_bullet(i)
1201                                         .getCharacter();
1202                                 if (c == 16
1203                                    || c == 17
1204                                    || c == 25
1205                                    || c == 26
1206                                    || c == 31) {
1207                                         features.require("latexsym");
1208                                 }
1209                         } else if (font == 1) {
1210                                 features.require("amssymb");
1211                         } else if ((font >= 2 && font <= 5)) {
1212                                 features.require("pifont");
1213                         }
1214                 }
1215         }
1216
1217         if (lyxerr.debugging(Debug::LATEX)) {
1218                 features.showStruct();
1219         }
1220 }
1221
1222
1223 void Buffer::getLabelList(vector<string> & list) const
1224 {
1225         /// if this is a child document and the parent is already loaded
1226         /// Use the parent's list instead  [ale990407]
1227         Buffer const * tmp = getMasterBuffer();
1228         if (!tmp) {
1229                 lyxerr << "getMasterBuffer() failed!" << endl;
1230                 BOOST_ASSERT(tmp);
1231         }
1232         if (tmp != this) {
1233                 tmp->getLabelList(list);
1234                 return;
1235         }
1236
1237         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1238                 it.nextInset()->getLabelList(*this, list);
1239 }
1240
1241
1242 // This is also a buffer property (ale)
1243 void Buffer::fillWithBibKeys(vector<pair<string, string> > & keys)
1244         const
1245 {
1246         /// if this is a child document and the parent is already loaded
1247         /// use the parent's list instead  [ale990412]
1248         Buffer const * tmp = getMasterBuffer();
1249         BOOST_ASSERT(tmp);
1250         if (tmp != this) {
1251                 tmp->fillWithBibKeys(keys);
1252                 return;
1253         }
1254
1255         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1256                 if (it->lyxCode() == InsetBase::BIBTEX_CODE) {
1257                         InsetBibtex const & inset =
1258                                 dynamic_cast<InsetBibtex const &>(*it);
1259                         inset.fillWithBibKeys(*this, keys);
1260                 } else if (it->lyxCode() == InsetBase::INCLUDE_CODE) {
1261                         InsetInclude const & inset =
1262                                 dynamic_cast<InsetInclude const &>(*it);
1263                         inset.fillWithBibKeys(*this, keys);
1264                 } else if (it->lyxCode() == InsetBase::BIBITEM_CODE) {
1265                         InsetBibitem const & inset =
1266                                 dynamic_cast<InsetBibitem const &>(*it);
1267                         string const key = inset.getContents();
1268                         string const opt = inset.getOptions();
1269                         string const ref; // = pit->asString(this, false);
1270                         string const info = opt + "TheBibliographyRef" + ref;
1271                         keys.push_back(pair<string, string>(key, info));
1272                 }
1273         }
1274 }
1275
1276
1277 bool Buffer::isDepClean(string const & name) const
1278 {
1279         DepClean::const_iterator const it = pimpl_->dep_clean.find(name);
1280         if (it == pimpl_->dep_clean.end())
1281                 return true;
1282         return it->second;
1283 }
1284
1285
1286 void Buffer::markDepClean(string const & name)
1287 {
1288         pimpl_->dep_clean[name] = true;
1289 }
1290
1291
1292 bool Buffer::dispatch(string const & command, bool * result)
1293 {
1294         return dispatch(lyxaction.lookupFunc(command), result);
1295 }
1296
1297
1298 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1299 {
1300         bool dispatched = true;
1301
1302         switch (func.action) {
1303                 case LFUN_EXPORT: {
1304                         bool const tmp = Exporter::Export(this, func.argument, false);
1305                         if (result)
1306                                 *result = tmp;
1307                         break;
1308                 }
1309
1310                 default:
1311                         dispatched = false;
1312         }
1313         return dispatched;
1314 }
1315
1316
1317 void Buffer::changeLanguage(Language const * from, Language const * to)
1318 {
1319         BOOST_ASSERT(from);
1320         BOOST_ASSERT(to);
1321
1322         lyxerr << "Changing Language!" << endl;
1323
1324         // Take care of l10n/i18n
1325         updateDocLang(to);
1326
1327         for_each(par_iterator_begin(),
1328                  par_iterator_end(),
1329                  bind(&Paragraph::changeLanguage, _1, params(), from, to));
1330 }
1331
1332
1333 void Buffer::updateDocLang(Language const * nlang)
1334 {
1335         BOOST_ASSERT(nlang);
1336
1337         pimpl_->messages.reset(new Messages(nlang->code()));
1338 }
1339
1340
1341 bool Buffer::isMultiLingual() const
1342 {
1343         ParConstIterator end = par_iterator_end();
1344         for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1345                 if (it->isMultiLingual(params()))
1346                         return true;
1347
1348         return false;
1349 }
1350
1351
1352 ParIterator Buffer::getParFromID(int const id) const
1353 {
1354         ParConstIterator it = par_iterator_begin();
1355         ParConstIterator const end = par_iterator_end();
1356
1357         if (id < 0) {
1358                 // John says this is called with id == -1 from undo
1359                 lyxerr << "getParFromID(), id: " << id << endl;
1360                 return end;
1361         }
1362
1363         for (; it != end; ++it)
1364                 if (it->id() == id)
1365                         return it;
1366
1367         return end;
1368 }
1369
1370
1371 bool Buffer::hasParWithID(int const id) const
1372 {
1373         ParConstIterator const it = getParFromID(id);
1374         return it != par_iterator_end();
1375 }
1376
1377
1378 ParIterator Buffer::par_iterator_begin()
1379 {
1380         return ::par_iterator_begin(inset());
1381 }
1382
1383
1384 ParIterator Buffer::par_iterator_end()
1385 {
1386         return ::par_iterator_end(inset());
1387 }
1388
1389
1390 ParConstIterator Buffer::par_iterator_begin() const
1391 {
1392         return ::par_const_iterator_begin(inset());
1393 }
1394
1395
1396 ParConstIterator Buffer::par_iterator_end() const
1397 {
1398         return ::par_const_iterator_end(inset());
1399 }
1400
1401
1402 Language const * Buffer::getLanguage() const
1403 {
1404         return params().language;
1405 }
1406
1407
1408 string const Buffer::B_(string const & l10n) const
1409 {
1410         if (pimpl_->messages.get()) {
1411                 return pimpl_->messages->get(l10n);
1412         }
1413
1414         return _(l10n);
1415 }
1416
1417
1418 bool Buffer::isClean() const
1419 {
1420         return pimpl_->lyx_clean;
1421 }
1422
1423
1424 bool Buffer::isBakClean() const
1425 {
1426         return pimpl_->bak_clean;
1427 }
1428
1429
1430 void Buffer::markClean() const
1431 {
1432         if (!pimpl_->lyx_clean) {
1433                 pimpl_->lyx_clean = true;
1434                 updateTitles();
1435         }
1436         // if the .lyx file has been saved, we don't need an
1437         // autosave
1438         pimpl_->bak_clean = true;
1439 }
1440
1441
1442 void Buffer::markBakClean()
1443 {
1444         pimpl_->bak_clean = true;
1445 }
1446
1447
1448 void Buffer::setUnnamed(bool flag)
1449 {
1450         pimpl_->unnamed = flag;
1451 }
1452
1453
1454 bool Buffer::isUnnamed() const
1455 {
1456         return pimpl_->unnamed;
1457 }
1458
1459
1460 #warning this function should be moved to buffer_pimpl.C
1461 void Buffer::markDirty()
1462 {
1463         if (pimpl_->lyx_clean) {
1464                 pimpl_->lyx_clean = false;
1465                 updateTitles();
1466         }
1467         pimpl_->bak_clean = false;
1468
1469         DepClean::iterator it = pimpl_->dep_clean.begin();
1470         DepClean::const_iterator const end = pimpl_->dep_clean.end();
1471
1472         for (; it != end; ++it) {
1473                 it->second = false;
1474         }
1475 }
1476
1477
1478 string const & Buffer::fileName() const
1479 {
1480         return pimpl_->filename;
1481 }
1482
1483
1484 string const & Buffer::filePath() const
1485 {
1486         return pimpl_->filepath;
1487 }
1488
1489
1490 bool Buffer::isReadonly() const
1491 {
1492         return pimpl_->read_only;
1493 }
1494
1495
1496 void Buffer::setParentName(string const & name)
1497 {
1498         params().parentname = name;
1499 }
1500
1501
1502 Buffer const * Buffer::getMasterBuffer() const
1503 {
1504         if (!params().parentname.empty()
1505             && bufferlist.exists(params().parentname)) {
1506                 Buffer const * buf = bufferlist.getBuffer(params().parentname);
1507                 if (buf)
1508                         return buf->getMasterBuffer();
1509         }
1510
1511         return this;
1512 }
1513
1514
1515 MacroData const & Buffer::getMacro(std::string const & name) const
1516 {
1517         return pimpl_->macros.get(name);
1518 }
1519
1520
1521 bool Buffer::hasMacro(string const & name) const
1522 {
1523         return pimpl_->macros.has(name);
1524 }
1525
1526
1527 void Buffer::insertMacro(string const & name, MacroData const & data)
1528 {
1529         MacroTable::globalMacros().insert(name, data);
1530         pimpl_->macros.insert(name, data);
1531 }
1532
1533
1534 void Buffer::buildMacros()
1535 {
1536         // Start with global table.
1537         pimpl_->macros = MacroTable::globalMacros();
1538
1539         // Now add our own.
1540         ParagraphList & pars = text().paragraphs();
1541         for (size_t i = 0, n = pars.size(); i != n; ++i) {
1542                 //lyxerr << "searching main par " << i
1543                 //      << " for macro definitions" << std::endl;
1544                 InsetList::iterator it = pars[i].insetlist.begin();
1545                 InsetList::iterator end = pars[i].insetlist.end();
1546                 for ( ; it != end; ++it) {
1547                         //lyxerr << "found inset code " << it->inset->lyxCode() << std::endl;
1548                         if (it->inset->lyxCode() == InsetBase::MATHMACRO_CODE) {
1549                                 MathMacroTemplate & mac
1550                                         = static_cast<MathMacroTemplate &>(*it->inset);
1551                                 insertMacro(mac.name(), mac.asMacroData());
1552                         }
1553                 }
1554         }
1555 }