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