]> git.lyx.org Git - lyx.git/blob - src/Buffer.h
* Buffer.cpp:
[lyx.git] / src / Buffer.h
1 // -*- C++ -*-
2 /**
3  * \file Buffer.h
4  * This file is part of LyX, the document processor.
5  * Licence details can be found in the file COPYING.
6  *
7  * \author Lars Gullik Bjønnes
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #ifndef BUFFER_H
13 #define BUFFER_H
14
15 #include "update_flags.h"
16
17 #include "insets/InsetCode.h"
18
19 #include "support/strfwd.h"
20 #include "support/types.h"
21 #include "support/SignalSlot.h"
22
23 #include <string>
24 #include <vector>
25
26
27 namespace lyx {
28
29 class BiblioInfo;
30 class BufferParams;
31 class BufferSet;
32 class DispatchResult;
33 class DocIterator;
34 class docstring_list;
35 class ErrorItem;
36 class ErrorList;
37 class FuncRequest;
38 class FuncStatus;
39 class Inset;
40 class InsetRef;
41 class InsetLabel;
42 class Font;
43 class Format;
44 class Lexer;
45 class LyXRC;
46 class Text;
47 class LyXVC;
48 class LaTeXFeatures;
49 class Language;
50 class MacroData;
51 class MacroNameSet;
52 class MacroSet;
53 class OutputParams;
54 class Paragraph;
55 class ParConstIterator;
56 class ParIterator;
57 class ParagraphList;
58 class TeXErrors;
59 class TexRow;
60 class TocBackend;
61 class Undo;
62 class WordLangTuple;
63
64 namespace frontend {
65 class GuiBufferDelegate;
66 class WorkAreaManager;
67 }
68
69 namespace support {
70 class FileName;
71 class FileNameList;
72 }
73
74 /** The buffer object.
75  * This is the buffer object. It contains all the informations about
76  * a document loaded into LyX.
77  * The buffer object owns the Text (wrapped in an InsetText), which
78  * contains the individual paragraphs of the document.
79  *
80  *
81  * I am not sure if the class is complete or
82  * minimal, probably not.
83  * \author Lars Gullik Bjønnes
84  */
85 class Buffer {
86 public:
87         /// What type of log will \c getLogName() return?
88         enum LogType {
89                 latexlog, ///< LaTeX log
90                 buildlog  ///< Literate build log
91         };
92
93         /// Result of \c readFile()
94         enum ReadStatus {
95                 failure, ///< The file could not be read
96                 success, ///< The file could not be read
97                 wrongversion ///< The version of the file does not match ours
98         };
99
100
101         /// Method to check if a file is externally modified, used by
102         /// isExternallyModified()
103         /**
104          * timestamp is fast but inaccurate. For example, the granularity
105          * of timestamp on a FAT filesystem is 2 second. Also, various operations
106          * may touch the timestamp of a file even when its content is unchanged.
107          *
108          * checksum is accurate but slow, which can be a problem when it is
109          * frequently used, or used for a large file on a slow (network) file
110          * system.
111          *
112          * FIXME: replace this method with support/FileMonitor.
113          */
114         enum CheckMethod {
115                 checksum_method,  ///< Use file checksum
116                 timestamp_method, ///< Use timestamp, and checksum if timestamp has changed
117         };
118
119         ///
120         enum UpdateScope {
121                 UpdateMaster,
122                 UpdateChildOnly
123         };
124
125         /// Constructor
126         explicit Buffer(std::string const & file, bool b = false);
127
128         /// Destructor
129         ~Buffer();
130
131         /** High-level interface to buffer functionality.
132             This function parses a command string and executes it.
133         */
134         void dispatch(std::string const & command, DispatchResult & result);
135
136         /// Maybe we know the function already by number...
137         void dispatch(FuncRequest const & func, DispatchResult & result);
138
139         /// Can this function be exectued?
140         /// \return true if we made a decision
141         bool getStatus(FuncRequest const & cmd, FuncStatus & flag);
142
143         /// read a new document from a string
144         bool readString(std::string const &);
145         /// load a new file
146         bool readFile(support::FileName const & filename);
147
148         /// read the header, returns number of unknown tokens
149         int readHeader(Lexer & lex);
150
151         /** Reads a file without header.
152             \param par if != 0 insert the file.
153             \return \c true if file is not completely read.
154         */
155         bool readDocument(Lexer &);
156
157         ///
158         void insertStringAsLines(ParagraphList & plist,
159                 pit_type &, pos_type &,
160                 Font const &, docstring const &, bool);
161         ///
162         DocIterator getParFromID(int id) const;
163         /// do we have a paragraph with this id?
164         bool hasParWithID(int id) const;
165
166         ///
167         frontend::WorkAreaManager & workAreaManager() const;
168
169         /** Save file.
170             Takes care of auto-save files and backup file if requested.
171             Returns \c true if the save is successful, \c false otherwise.
172         */
173         bool save() const;
174
175         /// Write document to stream. Returns \c false if unsuccesful.
176         bool write(std::ostream &) const;
177         /// Write file. Returns \c false if unsuccesful.
178         bool writeFile(support::FileName const &) const;
179
180         /// Loads LyX file \c filename into buffer, *  and \return success
181         bool loadLyXFile(support::FileName const & s);
182
183         /// Fill in the ErrorList with the TeXErrors
184         void bufferErrors(TeXErrors const &, ErrorList &) const;
185
186         /// Just a wrapper for writeLaTeXSource, first creating the ofstream.
187         bool makeLaTeXFile(support::FileName const & filename,
188                            std::string const & original_path,
189                            OutputParams const &,
190                            bool output_preamble = true,
191                            bool output_body = true) const;
192         /** Export the buffer to LaTeX.
193             If \p os is a file stream, and params().inputenc is "auto" or
194             "default", and the buffer contains text in different languages
195             with more than one encoding, then this method will change the
196             encoding associated to \p os. Therefore you must not call this
197             method with a string stream if the output is supposed to go to a
198             file. \code
199             ofdocstream ofs;
200             ofs.open("test.tex");
201             writeLaTeXSource(ofs, ...);
202             ofs.close();
203             \endcode is NOT equivalent to \code
204             odocstringstream oss;
205             writeLaTeXSource(oss, ...);
206             ofdocstream ofs;
207             ofs.open("test.tex");
208             ofs << oss.str();
209             ofs.close();
210             \endcode
211          */
212         void writeLaTeXSource(odocstream & os,
213                            std::string const & original_path,
214                            OutputParams const &,
215                            bool output_preamble = true,
216                            bool output_body = true) const;
217         ///
218         void makeDocBookFile(support::FileName const & filename,
219                              OutputParams const & runparams_in,
220                              bool only_body = false) const;
221         ///
222         void writeDocBookSource(odocstream & os, std::string const & filename,
223                              OutputParams const & runparams_in,
224                              bool only_body = false) const;
225         ///
226         void makeLyXHTMLFile(support::FileName const & filename,
227                              OutputParams const & runparams_in,
228                              bool only_body = false) const;
229         ///
230         void writeLyXHTMLSource(odocstream & os,
231                              OutputParams const & runparams_in,
232                              bool only_body = false) const;
233         /// returns the main language for the buffer (document)
234         Language const * language() const;
235         /// get l10n translated to the buffers language
236         docstring const B_(std::string const & l10n) const;
237
238         ///
239         int runChktex();
240         /// return true if the main lyx file does not need saving
241         bool isClean() const;
242         ///
243         bool isBakClean() const;
244         ///
245         bool isDepClean(std::string const & name) const;
246
247         /// whether or not disk file has been externally modified
248         bool isExternallyModified(CheckMethod method) const;
249
250         /// save timestamp and checksum of the given file.
251         void saveCheckSum(support::FileName const & file) const;
252
253         /// mark the main lyx file as not needing saving
254         void markClean() const;
255
256         ///
257         void markBakClean() const;
258
259         ///
260         void markDepClean(std::string const & name);
261
262         ///
263         void setUnnamed(bool flag = true);
264
265         ///
266         bool isUnnamed() const;
267
268         /// Mark this buffer as dirty.
269         void markDirty();
270
271         /// Returns the buffer's filename. It is always an absolute path.
272         support::FileName fileName() const;
273
274         /// Returns the buffer's filename. It is always an absolute path.
275         std::string absFileName() const;
276
277         /// Returns the the path where the buffer lives.
278         /// It is always an absolute path.
279         std::string filePath() const;
280
281         /** A transformed version of the file name, adequate for LaTeX.
282             \param no_path optional if \c true then the path is stripped.
283         */
284         std::string latexName(bool no_path = true) const;
285
286         /// Get the name and type of the log.
287         std::string logName(LogType * type = 0) const;
288
289         /// Change name of buffer. Updates "read-only" flag.
290         void setFileName(std::string const & newfile);
291
292         /// Set document's parent Buffer.
293         void setParent(Buffer const *);
294         Buffer const * parent() const;
295
296         // Collect all relative buffer
297         std::vector<Buffer const *> allRelatives() const;
298
299         /** Get the document's master (or \c this if this is not a
300             child document)
301          */
302         Buffer const * masterBuffer() const;
303
304         /// \return true if \p child is a child of this \c Buffer.
305         bool isChild(Buffer * child) const;
306         
307         /// return a vector with all children and grandchildren
308         std::vector<Buffer *> getChildren() const;
309
310         /// Is buffer read-only?
311         bool isReadonly() const;
312
313         /// Set buffer read-only flag
314         void setReadonly(bool flag = true);
315
316         /// returns \c true if the buffer contains a LaTeX document
317         bool isLatex() const;
318         /// returns \c true if the buffer contains a DocBook document
319         bool isDocBook() const;
320         /// returns \c true if the buffer contains a Wed document
321         bool isLiterate() const;
322
323         /** Validate a buffer for LaTeX.
324             This validates the buffer, and returns a struct for use by
325             #makeLaTeX# and others. Its main use is to figure out what
326             commands and packages need to be included in the LaTeX file.
327             It (should) also check that the needed constructs are there
328             (i.e. that the \refs points to coresponding \labels). It
329             should perhaps inset "error" insets to help the user correct
330             obvious mistakes.
331         */
332         void validate(LaTeXFeatures &) const;
333
334         /// Update the cache with all bibfiles in use (including bibfiles
335         /// of loaded child documents).
336         void updateBibfilesCache(UpdateScope scope = UpdateMaster) const;
337         ///
338         void invalidateBibinfoCache();
339         /// Return the cache with all bibfiles in use (including bibfiles
340         /// of loaded child documents).
341         support::FileNameList const & 
342                 getBibfilesCache(UpdateScope scope = UpdateMaster) const;
343         /// \return the bibliography information for this buffer's master,
344         /// or just for it, if it isn't a child.
345         BiblioInfo const & masterBibInfo() const;
346         /// \return the bibliography information for this buffer ONLY.
347         BiblioInfo const & localBibInfo() const;
348         ///
349         void getLabelList(std::vector<docstring> &) const;
350
351         ///
352         void changeLanguage(Language const * from, Language const * to);
353
354         ///
355         bool isMultiLingual() const;
356
357         ///
358         BufferParams & params();
359         BufferParams const & params() const;
360
361         /** The list of paragraphs.
362             This is a linked list of paragraph, this list holds the
363             whole contents of the document.
364          */
365         ParagraphList & paragraphs();
366         ParagraphList const & paragraphs() const;
367
368         /// LyX version control object.
369         LyXVC & lyxvc();
370         LyXVC const & lyxvc() const;
371
372         /// Where to put temporary files.
373         std::string const temppath() const;
374
375         /// Used when typesetting to place errorboxes.
376         TexRow const & texrow() const;
377         TexRow & texrow();
378
379         ///
380         ParIterator par_iterator_begin();
381         ///
382         ParConstIterator par_iterator_begin() const;
383         ///
384         ParIterator par_iterator_end();
385         ///
386         ParConstIterator par_iterator_end() const;
387
388         // Position of the child buffer where it appears first in the master.
389         DocIterator firstChildPosition(Buffer const * child);
390
391         /** \returns true only when the file is fully loaded.
392          *  Used to prevent the premature generation of previews
393          *  and by the citation inset.
394          */
395         bool isFullyLoaded() const;
396         /// Set by buffer_funcs' newFile.
397         void setFullyLoaded(bool);
398
399         /// Our main text (inside the top InsetText)
400         Text & text() const;
401
402         /// Our top InsetText
403         Inset & inset() const;
404
405         //
406         // Macro handling
407         //
408         /// Collect macro definitions in paragraphs
409         void updateMacros() const;
410         /// Iterate through the whole buffer and try to resolve macros
411         void updateMacroInstances() const;
412
413         /// List macro names of this buffer, the parent and the children
414         void listMacroNames(MacroNameSet & macros) const;
415         /// Collect macros of the parent and its children in front of this buffer.
416         void listParentMacros(MacroSet & macros, LaTeXFeatures & features) const;
417
418         /// Return macro defined before pos (or in the master buffer)
419         MacroData const * getMacro(docstring const & name, DocIterator const & pos, bool global = true) const;
420         /// Return macro defined anywhere in the buffer (or in the master buffer)
421         MacroData const * getMacro(docstring const & name, bool global = true) const;
422         /// Return macro defined before the inclusion of the child
423         MacroData const * getMacro(docstring const & name, Buffer const & child, bool global = true) const;
424
425         /// Replace the inset contents for insets which InsetCode is equal
426         /// to the passed \p inset_code.
427         void changeRefsIfUnique(docstring const & from, docstring const & to,
428                 InsetCode code);
429
430         /// get source code (latex/docbook) for some paragraphs, or all paragraphs
431         /// including preamble
432         void getSourceCode(odocstream & os, pit_type par_begin, pit_type par_end,
433                 bool full_source) const;
434
435         /// Access to error list.
436         /// This method is used only for GUI visualisation of Buffer related
437         /// errors (like parsing or LateX compilation). This method is const
438         /// because modifying the returned ErrorList does not touch the document
439         /// contents.
440         ErrorList & errorList(std::string const & type) const;
441
442         /// The Toc backend.
443         /// This is useful only for screen visualisation of the Buffer. This
444         /// method is const because modifying this backend does not touch
445         /// the document contents.
446         TocBackend & tocBackend() const;
447
448         ///
449         Undo & undo();
450
451         /// This function is called when the buffer is changed.
452         void changed() const;
453         ///
454         void updateTocItem(std::string const &, DocIterator const &) const;
455         /// This function is called when the buffer structure is changed.
456         void structureChanged() const;
457         /// This function is called when some parsing error shows up.
458         void errors(std::string const & err) const;
459         /// This function is called when the buffer busy status change.
460         void setBusy(bool on) const;
461         /// This function is called when the buffer readonly status change.
462         void setReadOnly(bool on) const;
463         /// Update window titles of all users.
464         void updateTitles() const;
465         /// Reset autosave timers for all users.
466         void resetAutosaveTimers() const;
467         ///
468         void message(docstring const & msg) const;
469
470         ///
471         void setGuiDelegate(frontend::GuiBufferDelegate * gui);
472         ///
473         bool hasGuiDelegate() const;
474
475         ///
476         void autoSave() const;
477         ///
478         void removeAutosaveFile() const;
479         ///
480         void moveAutosaveFile(support::FileName const & old) const;
481         ///
482         support::FileName getAutosaveFilename() const;
483
484         /// return the format of the buffer on a string
485         std::string bufferFormat() const;
486         /// return the default output format of the current backend
487         std::string getDefaultOutputFormat() const;
488
489         ///
490         bool doExport(std::string const & format, bool put_in_tempdir,
491                 std::string & result_file) const;
492         ///
493         bool doExport(std::string const & format, bool put_in_tempdir) const;
494         ///
495         bool preview(std::string const & format) const;
496         ///
497         bool isExportable(std::string const & format) const;
498         ///
499         std::vector<Format const *> exportableFormats(bool only_viewable) const;
500
501         ///
502         typedef std::vector<std::pair<InsetRef *, ParIterator> > References;
503         References & references(docstring const & label);
504         References const & references(docstring const & label) const;
505         void clearReferenceCache() const;
506         void setInsetLabel(docstring const & label, InsetLabel const * il);
507         InsetLabel const * insetLabel(docstring const & label) const;
508
509         /// sets the buffer_ member for every inset in this buffer.
510         // FIXME This really shouldn't be needed, but at the moment it's not
511         // clear how to do it just for the individual pieces we need.
512         void setBuffersForInsets() const;
513         ///
514         void updateLabels(UpdateScope = UpdateMaster) const;
515         ///
516         void updateLabels(ParIterator & parit) const;
517
518         /// Find next word starting from \p from.
519         /// \p from initial position to search, will then points to the next
520         ///    word.
521         /// \p to will points to the end of the next word.
522         /// \p word will contain the found word if any.
523         /// \return true if a new word was found.
524         bool nextWord(DocIterator & from, DocIterator & to,
525                 docstring & word) const;
526
527         int spellCheck(DocIterator & from, DocIterator & to,
528                 WordLangTuple & word_lang, docstring_list & suggestions) const;
529
530 private:
531         /// search for macro in local (buffer) table or in children
532         MacroData const * getBufferMacro(docstring const & name,
533                                          DocIterator const & pos) const;
534         /** Update macro table starting with position of it
535             \param it in some text inset
536         */
537         void updateMacros(DocIterator & it,
538                                      DocIterator & scope) const;
539
540         ///
541         void collectRelatives(BufferSet & bufs) const;
542
543         ///
544         bool readFileHelper(support::FileName const & s);
545         ///
546         std::vector<std::string> backends() const;
547         /** Inserts a file into a document
548             \return \c false if method fails.
549         */
550         ReadStatus readFile(Lexer &, support::FileName const & filename,
551                             bool fromString = false);
552
553         /// Use the Pimpl idiom to hide the internals.
554         class Impl;
555         /// The pointer never changes although *pimpl_'s contents may.
556         Impl * const d;
557
558         frontend::GuiBufferDelegate * gui_;
559
560         /// This function is called when the buffer structure is changed.
561         Signal structureChanged_;
562         /// This function is called when some parsing error shows up.
563         //Signal errors(std::string const &) = 0;
564         /// This function is called when some message shows up.
565         //Signal message(docstring const &) = 0;
566         /// This function is called when the buffer busy status change.
567         //Signal setBusy(bool) = 0;
568         /// Reset autosave timers for all users.
569         Signal resetAutosaveTimers_;
570 };
571
572
573 } // namespace lyx
574
575 #endif