diff --git a/src/data/help/latexhelp.html b/src/data/help/latexhelp.html index f99dd32e..3f0d2a39 100644 --- a/src/data/help/latexhelp.html +++ b/src/data/help/latexhelp.html @@ -1,3633 +1,3633 @@ Kile : LaTex Reference

LaTeX Reference

Alphabetical Index
 #   A   B   C   D   E   F   H   I   K   L   M   N   O   P   Q   R   S   T   U   V   W 



Index by subject
Counters Internal counters used by LaTeX.
 
Cross References Automatic referencing.
 
Definitions Define your own commands etc.
 
Document Classes Some of the various classes available.
Environments Such as enumerate & itemize.
 
Footnotes How to produce footnotes.
 
Layout Controlling the page layout.
 
Lengths The length commands.
 
Letters The letter class.
 
Line & Page Breaking How to insert pagebreaks etc.
 
Making Paragraphs Paragraph commands.
 
Margin Notes Putting remarks in the margin.
Math Formulae How to create mathematical formulae.
 
Modes Paragraph, Math or LR modes.
Page Styles Various styles of page layout.
 
Sectioning How to section properly.
Spaces & Boxes All the associated commands.
 
Special Characters Special reserved characters.
Splitting the Input Dealing with big files by splitting.
 
Starting & Ending The formal start & end layouts.
Table of Contents How to create a table of contents.
 
Terminal Input/Output User interaction.
 
Typefaces Such as bold, italics etc.
 

Alphabetical index
 # 
 A 
 B 
 C 
 D 
 E 
 F 
 H 
 I 
 K 
 L 
 M 
 N 
 O 
 P 
 Q 
 R 
 S 
 T 
 U 
 V 
 W 



 Counters

Everything LaTeX numbers for you has a counter associated with it. The name of the counter is the same as the name of the environment or command that produces the number, except with no \. (enumi - enumiv are used for the nested enumerate environment.) Below is a list of the counters used in LaTeX's standard document classes to control numbering.

  part            paragraph       figure          enumi
  chapter         subparagraph    table           enumii
  section         page            footnote        enumiii
  subsection      equation        mpfootnote      enumiv
  subsubsection
 

\addtocounter

\addtocounter{counter}{value}

The \addtocounter command increments the counter by the amount specified by the value argument. The value argument can be negative.

\alph

\alph{counter}

This command causes the value of the counter to be printed in alphabetic characters. The \alph command -uses lower case alphabetic alphabetic characters, i.e., a, b, +uses lower case alphabetic characters, i.e., a, b, c... while the \Alph command uses upper case alphabetic characters, i.e., A, B, C....

\arabic

\arabic{counter}

The \arabic command causes the value of the counter to be printed in Arabic numbers, i.e., 3.

\fnsymbol

\fnsymbol{counter}

The \fnsymbol command causes the value of the counter to be printed in a specific sequence of nine symbols that can be used for numbering footnotes.

eg. From 1-9:

NB. counter must have a value between 1 and 9 inclusive.

\newcounter

\newcounter{foo}[counter]

The \newcounter command defines a new counter named foo. The counter is initialized to zero.

The optional argument [counter] causes the counter foo to be reset whenever the counter named in the optional argument is incremented.

\refstepcounter

\refstepcounter{counter}

The \refstepcounter command works like \stepcounter See section \stepcounter, except it also defines the current \ref value to be the result of \thecounter.

\roman

\roman{counter}

This command causes the value of the counter to be printed in Roman numerals. The \roman command uses lower case Roman numerals, i.e., i, ii, iii..., while the \Roman command uses upper case Roman numerals, i.e., I, II, III....

\stepcounter

\stepcounter{counter}

The \stepcounter command adds one to the counter and resets all subsidiary counters.

\setcounter

\setcounter{counter}{value}

The \setcounter command sets the value of the counter to that specified by the value argument.

\usecounter

\usecounter{counter}

The \usecounter command is used in the second argument of the list environment to allow the counter specified to be used to number the list items.

\value

\value{counter}

The \value command produces the value of the counter named in the mandatory argument. It can be used where LaTeX expects an integer or number, such as the second argument of a \setcounter or \addtocounter command, or in:

         \hspace{\value{foo}\parindent}
 

It is useful for doing arithmetic with counters.

Cross References

One reason for numbering things like figures and equations is to refer the reader to them, as in "See Figure 3 for more details."

\label

\label{key}

A \label command appearing in ordinary text assigns to the key the number of the current sectional unit; one appearing inside a numbered environment assigns that number to the key.

A key can consist of any sequence of letters, digits, or punctuation characters. Upper and lowercase letters are different.

To avoid accidentally creating two labels with the same name, it is common to use labels consisting of a prefix and a suffix separated by a colon. The prefixes conventionally used are

Thus, a label for a figure would look like fig:bandersnatch.

\pageref

\pageref{key}

The \pageref command produces the page number of the place in the text where the corresponding \label command appears. ie. where \label{key} appears.

\ref

\ref{key}

The \ref command produces the number of the sectional unit, equation number, ... of the corresponding \label command.

Definitions

\newcommand

  \newcommand{cmd}[args]{definition}
  \newcommand{cmd}[args][default]{definition}
  \renewcommand{cmd}[args]{definition}
  \renewcommand{cmd}[args][default]{definition}
 

These commands define (or redefine) a command.

cmd
A command name beginning with a \. For \newcommand it must not be already defined and must not begin with \end; for \renewcommand it must already be defined.
args
An integer from 1 to 9 denoting the number of arguments of the command being defined. The default is for the command to have no arguments.
def
If this optional parameter is present, it means that the command's first argument is optional. The default value of the optional argument is def.
definition
The text to be substituted for every occurrence of cmd; a parameter of the form #n in cmd is replaced by the text of the nth argument when this substitution takes place.

\newenvironment

  \newenvironment{nam}[args]{begdef}{enddef}
  \newenvironment{nam}[args][default]{begdef}{enddef}
  \renewenvironment{nam}[args]{begdef}{enddef}
 

These commands define or redefine an environment.

nam
The name of the environment. For \newenvironment there must be no currently defined environment by that name, and the command \nam must be undefined. For \renewenvironment the environment must already be defined.
args
An integer from 1 to 9 denoting the number of arguments of the newly-defined environment. The default is no arguments.
default
If this is specified, the first argument is optional, and default gives the default value for that argument.
begdef
The text substituted for every occurrence of \begin{nam}; a parameter of the form #n in cmd is replaced by the text of the nth argument when this substitution takes place.
enddef
The text substituted for every occurrence of \end{nam}. It may not contain any argument parameters.

\newtheorem

  \newtheorem{env_name}{caption}[within]
  \newtheorem{env_name}[numbered_like]{caption}
 

This command defines a theorem-like environment.

env_name
The name of the environment to be defined. A string of letters. It must not be the name of an existing environment or counter.
caption
The text printed at the beginning of the environment, right before the number. This may simply say "Theorem", for example.
within
The name of an already defined counter, usually of a sectional unit. Provides a means of resetting the new theorem counter within the sectional unit.
numbered_like
The name of an already defined theorem-like environment.

The \newtheorem command may have at most one optional argument.

\newfont

\newfont{cmd}{font_name}

Defines the command name cmd, which must not be currently defined, to be a declaration that selects the font named font_name to be the current font.

Document Classes

Valid LaTeX document classes include:

Other document classes are often available. They are selected with the following command:

\documentclass [options] {class}

All the standard classes (except slides) accept the following options for selecting the typeface size (10 pt is default):

10pt, 11pt, 12pt

All classes accept these options for selecting the paper size (default is letter):

a4paper, a5paper, b5paper, letterpaper, legalpaper, executivepaper

Miscellaneous options:

These options are not available with the slides class:

The slides class offers the option clock for printing the time at the bottom of each note.

If you specify more than one option, they must be separated by a comma.

Additional packages are loaded by a

\usepackage[options]{pkg}

command. If you specify more than one package, they must be separated by a comma.

Any options given in the \documentclass command that are unknown by the selected document class are passed on to the packages loaded with \usepackage.

Layout

Miscellaneous commands for controlling the general layout of the page.

\flushbottom

The \flushbottom declaration makes all text pages the same height, adding extra vertical space when necessary to fill out the page.

This is the standard if twocolumn mode is selected.

\onecolumn

The \onecolumn declaration starts a new page and produces single-column output.

\raggedbottom

The \raggedbottom declaration makes all pages the height of the text on that page. No extra vertical space is added.

\twocolumn

\twocolumn[text]

The \twocolumn declaration starts a new page and produces two-column output. If the optional text argument is present, it is typeset in one-column mode.

Environments

LaTeX provides a number of different paragraph-making environments. Each environment begins and ends in the same manner.

         \begin{environment-name}
         .
         .
         .
         \end{environment-name}
 

array

 \begin{array}{col1col2...coln}
 column 1 entry & column 2 entry ... & column n entry \\
  .
  .
  .
 \end{array}
 

Math arrays are produced with the array environment. It has a single mandatory argument describing the number of columns and the alignment within them. Each column, coln, is specified by a single letter that tells how items in that row should be formatted.

Column entries must be separated by an &. Column entries may include other LaTeX commands. Each row of the array must be terminated with the string \\.

Note that the array environment can only be used in math mode, so normally it is used inside an equation environment.

center

  \begin{center}
  Text on line 1 \\
  Text on line 2 \\
  .
  .
  .
  \end{center}
 

The center environment allows you to create a paragraph consisting of lines that are centred within the left and right margins on the current page. Each line must be terminated with the string \\.

\centering

This declaration corresponds to the center environment. This declaration can be used inside an environment such as quote or in a parbox. The text of a figure or table can be centred on the page by putting a \centering command at the beginning of the figure or table environment.

Unlike the center environment, the \centering command does not start a new paragraph; it simply changes how LaTeX formats paragraph units. To affect a paragraph unit's format, the scope of the declaration must contain the blank line or \end command (of an environment like quote) that ends the paragraph unit.

description

  \begin{description}
  \item [label] First item
  \item [label] Second item
  .
  .
  .
  \end{description}
 

The description environment is used to make labelled lists. The label is bold face and flushed right.

enumerate

  \begin{enumerate}
  \item First item
  \item Second item
  .
  .
  .
  \end{enumerate}
 

The enumerate environment produces a numbered list. Enumerations can be nested within one another, up to four levels deep. They can also be nested within other paragraph-making environments.

Each item of an enumerated list begins with an \item command. There must be at least one \item command within the environment.

The enumerate environment uses the enumi through enumiv counters (see section Counters). The type of numbering can be changed by redefining \theenumi etc.

eqnarray

  \begin{eqnarray}
  math formula 1 \\
  math formula 2 \\
  .
  .
  .
  \end{eqnarray}
 

The eqnarray environment is used to display a sequence of equations or inequalities. It is very much like a three-column array environment, with consecutive rows separated by \\ and consecutive items within a row separated by an &.

An equation number is placed on every line unless that line has a \nonumber command.

The command \lefteqn is used for splitting long formulas across lines. It typesets its argument in display style flush left in a box of zero width.

equation

  \begin{equation}
   math formula
  \end{equation}
 

The equation environment centres your equation on the page and places the equation number in the right margin.

figure

  \begin{figure}[placement]
 
   body of the figure
 
  \caption{figure title}
  \end{figure}
 

Figures are objects that are not part of the normal text, and are usually "floated" to a convenient place, like the top of a page. Figures will not be split between two pages.

The optional argument [placement] determines where LaTeX will try to place your figure. There are four places where LaTeX can possibly put a float:

  1. h (Here) - at the position in the text where the figure environment appears.
  2. t (Top) - at the top of a text page.
  3. b (Bottom) - at the bottom of a text page.
  4. p (Page of floats) - on a separate float page, which is a page containing no text, only floats.

The standard report and article classes use the default placement tbp.

The body of the figure is made up of whatever text, LaTeX commands, etc. you wish. The \caption command allows you to title your figure.

flushleft

  \begin{flushleft}
  Text on line 1 \\
  Text on line 2 \\
  .
  .
  .
  \end{flushleft}
 

The flushleft environment allows you to create a paragraph consisting of lines that are flushed left, to the left-hand margin. Each line must be terminated with the string \\.

\raggedright

This declaration corresponds to the flushleft environment. This declaration can be used inside an environment such as quote or in a parbox.

Unlike the flushleft environment, the \raggedright command does not start a new paragraph; it simply changes how LaTeX formats paragraph units. To affect a paragraph unit's format, the scope of the declaration must contain the blank line or \end command (of an environment like quote) that ends the paragraph unit.

flushright

  \begin{flushright}
  Text on line 1 \\
  Text on line 2 \\
  .
  .
  .
  \end{flushright}
 

The flushright environment allows you to create a paragraph consisting of lines that are flushed right, to the right-hand margin. Each line must be terminated with the string \\.

\raggedleft

This declaration corresponds to the flushright environment. This declaration can be used inside an environment such as quote or in a parbox.

Unlike the flushright environment, the \raggedleft command does not start a new paragraph; it simply changes how LaTeX formats paragraph units. To affect a paragraph unit's format, the scope of the declaration must contain the blank line or \end command (of an environment like quote) that ends the paragraph unit.

itemize

  \begin{itemize}
  \item First item
  \item Second item
  .
  .
  .
  \end{itemize}
 

The itemize environment produces a "bulleted" list. Itemizations can be nested within one another, up to four levels deep. They can also be nested within other paragraph-making environments.

Each item of an itemized list begins with an \item command. There must be at least one \item command within the environment.

The itemize environment uses the itemi through itemiv counters (see section Counters). The type of numbering can be changed by redefining \theitemi etc.

letter

This environment is used for creating letters. See section Letters.

list

The list environment is a generic environment which is used for defining many of the more specific environments. It is seldom used in documents, but often in macros.

  \begin{list}{label}{spacing}
  \item First item
  \item Second item
  .
  .
  .
  \end{list}
 

The {label} argument specifies how items should be labelled. This argument is a piece of text that is inserted in a box to form the label. This argument can and usually does contain other LaTeX commands.

The {spacing} argument contains commands to change the spacing parameters for the list. This argument will most often be null, i.e., {}. This will select all default spacing which should suffice for most cases.

minipage

  \begin{minipage}[position]{width}
   text
  \end{minipage}
 

The minipage environment is similar to a \parbox command. It takes the same optional position argument and mandatory width argument. You may use other paragraph-making environments inside a minipage.

Footnotes in a minipage environment are handled in a way that is particularly useful for putting footnotes in figures or tables. A \footnote or \footnotetext command puts the footnote at the bottom of the minipage instead of at the bottom of the page, and it uses the mpfootnote counter instead of the ordinary footnote counter See section Counters.

NOTE: Don't put one minipage inside another if you are using footnotes; they may wind up at the bottom of the wrong minipage.

picture

  \begin{picture}(width,height)(x offset,y offset)
   .
   .
   picture commands
   .
   .
  \end{picture}
 

The picture environment allows you to create just about any kind of picture you want containing text, lines, arrows and circles. You tell LaTeX where to put things in the picture by specifying their coordinates. A coordinate is a number that may have a decimal point and a minus sign -- a number like 5, 2.3 or -3.1416. A coordinate specifies a length in multiples of the unit length \unitlength, so if \unitlength has been set to 1cm, then the coordinate 2.54 specifies a length of 2.54 centimetres. You can change the value of \unitlength anywhere you want, using the \setlength command, but strange things will happen if you try changing it inside the picture environment.

A position is a pair of coordinates, such as (2.4,-5), specifying the point with x-coordinate 2.4 and y-coordinate -5. Coordinates are specified in the usual way with respect to an origin, which is normally at the lower-left corner of the picture. Note that when a position appears as an argument, it is not enclosed in braces; the parentheses serve to delimit the argument.

The picture environment has one mandatory argument, which is a position. It specifies the size of the picture. The environment produces a rectangular box with width and height determined by this argument's x- and y-coordinates.

The picture environment also has an optional position argument, following the size argument, that can change the origin. (Unlike ordinary optional arguments, this argument is not contained in square brackets.) The optional argument gives the coordinates of the point at the lower-left corner of the picture (thereby determining the origin). For example, if \unitlength has been set to 1mm, the command

    \begin{picture}(100,200)(10,20)
 

produces a picture of width 100 millimeters and height 200 millimeters, whose lower-left corner is the point (10,20) and whose upper-right corner is therefore the point (110,220). When you first draw a picture, you will omit the optional argument, leaving the origin at the lower-left corner. If you then want to modify your picture by shifting everything, you just add the appropriate optional argument.

The environment's mandatory argument determines the nominal size of the picture. This need bear no relation to how large the picture really is; LaTeX will happily allow you to put things outside the picture, or even off the page. The picture's nominal size is used by LaTeX in determining how much room to leave for it.

Everything that appears in a picture is drawn by the \put command. The command

    \put (11.3,-.3){...}
 

puts the object specified by ... in the picture, with its reference point at coordinates (11.3,-.3). The reference points for various objects will be described below.

The \put command creates an LR box. You can put anything in the text argument of the \put command that you'd put into the argument of an \mbox and related commands. When you do this, the reference point will be the lower left corner of the box.

Picture commands:

\circle

\circle[*]{diameter}

The \circle command produces a circle with a diameter as close to the specified one as possible. If the *-form of the command is used, LaTeX draws a solid circle.

Note that only circles up to 40 pt can be drawn.

\dashbox

Draws a box with a dashed line.

\dashbox{dash_length}(width,height){...}

The \dashbox has an extra argument which specifies the width of each dash. A dashed box looks best when the width and height are multiples of the dash_length.

\frame

\frame{...}

The \frame command puts a rectangular frame around the object specified in the argument. The reference point is the bottom left corner of the frame. No extra space is put between the frame and the object.

\framebox

\framebox(width,height)[position]{...}

The \framebox command is exactly the same as the \makebox command, except that it puts a frame around the outside of the box that it creates.

The framebox command produces a rule of thickness \fboxrule, and leaves a space \fboxsep between the rule and the contents of the box.

\line

\line(x slope,y slope){length}

The \line command draws a line of the specified length and slope.

Note that LaTeX can only draw lines with slope = x/y, where x and y have integer values from -6 through 6.

\linethickness

\linethickness{dimension}

Declares the thickness of horizontal and vertical lines in a picture environment to be dimension, which must be a positive length. It does not affect the thickness of slanted lines and circles, or the quarter circles drawn by \oval to form the corners of an oval.

\makebox

\makebox(width,height)[position]{...}

The \makebox command for the picture environment is similar to the normal \makebox command except that you must specify a width and height in multiples of \unitlength.

The optional argument, [position], specifies the quadrant that your text appears in. You may select up to two of the following:

See section \makebox.

\multiput

\multiput(x coord,y coord)(delta x,delta y){number of copies}{object}

The \multiput command can be used when you are putting the same object in a regular pattern across a picture.

\oval

\oval(width,height)[portion]

The \oval command produces a rectangle with rounded corners. The optional argument, [portion], allows you to select part of the oval.

Note that the "corners" of the oval are made with quarter circles with a maximum radius of 20 pt, so large "ovals" will look more like boxes with rounded corners.

\put

\put(x coord,y coord){ ... }

The \put command places the item specified by the mandatory argument at the given coordinates.

\shortstack

\shortstack[position]{... \\ ... \\ ...}

The \shortstack command produces a stack of objects. The valid positions are:

\vector

\vector(x slope,y slope){length}

The \vector command draws a line with an arrow of the specified length and slope. The x and y values must lie between -4 and +4, inclusive.

quotation

  \begin{quotation}
   text
  \end{quotation}
 

The margins of the quotation environment are indented on the left and the right. The text is justified at both margins and there is paragraph indentation. Leaving a blank line between text produces a new paragraph.

quote

  \begin{quote}
   text
  \end{quote}
 

The margins of the quote environment are indented on the left and the right. The text is justified at both margins. Leaving a blank line between text produces a new paragraph.

tabbing

  \begin{tabbing}
  text \= more text \= still more text \= last text \\
  second row \>  \> more \\
  .
  .
  .
  \end{tabbing}
 

The tabbing environment provides a way to align text in columns. It works by setting tab stops and tabbing to them much the way you do with an ordinary typewriter.

It is best suited for cases where the width of each column is constant and known in advance.

This environment can be broken across pages, unlike the tabular environment.

The following commands can be used inside a tabbing environment:

\=
Sets a tab stop at the current position.
\>
Advances to the next tab stop.
\<
This command allows you to put something to the left of the local margin without changing the margin. Can only be used at the start of the line.
\+
Moves the left margin of the next and all the following commands one tab stop to the right.
\-
Moves the left margin of the next and all the following commands one tab stop to the left.
\'
Moves everything that you have typed so far in the current column, i.e. everything from the most recent \>, \<, \', \\, or \kill command, to the right of the previous column, flush against the current column's tab stop.
\`
Allows you to put text flush right against any tab stop, including tab stop 0. However, it can't move text to the right of the last column because there's no tab stop there. The \` command moves all the text that follows it, up to the \\ or \end{tabbing} command that ends the line, to the right margin of the tabbing environment. There must be no \> or \' command between the \` and the command that ends the line.
\kill
Sets tab stops without producing text. Works just like \\ except that it throws away the current line instead of producing output for it. The effect of any \=, \+ or \- commands in that line remain in effect.
\pushtabs
Saves all current tab stop positions. Useful for temporarily changing tab stop positions in the middle of a tabbing environment.
\pushtabs
Restores the tab stop positions saved by the last \pushtabs.
\a
In a tabbing environment, the commands \=, \' and \` do not produce accents as normal. Instead, the commands \a=, \a' and \a` are used.

This example typesets a Pascal function in a traditional format:

         \begin{tabbing}
         function \= fact(n : integer) : integer;\\
                  \> begin \= \+ \\
                        \> if \= n $>$ 1 then \+ \\
                                 fact := n * fact(n-1) \- \\
                           else \+ \\
                                 fact := 1; \-\- \\
                     end;\\
         \end{tabbing}
 

table

  \begin{table}[placement]
 
   body of the table
 
  \caption{table title}
  \end{table}
 

Tables are objects that are not part of the normal text, and are usually "floated" to a convenient place, like the top of a page. Tables will not be split between two pages.

The optional argument [placement] determines where LaTeX will try to place your table. There are four places where LaTeX can possibly put a float:

The standard report and article classes use the default placement [tbp].

The body of the table is made up of whatever text, LaTeX commands, etc., you wish. The \caption command allows you to title your table.

tabular

  \begin{tabular}[pos]{cols}
  column 1 entry & column 2 entry ... & column n entry \\
  .
  .
  .
  \end{tabular}
 

or

  \begin{tabular*}{width}[pos]{cols}
  column 1 entry & column 2 entry ... & column n entry \\
  .
  .
  .
  \end{tabular*}
 

These environments produce a box consisting of a sequence of rows of items, aligned vertically in columns. The mandatory and optional arguments consist of:

width
Specifies the width of the tabular* environment. There must be rubber space between columns that can stretch to fill out the specified width.
pos
Specifies the vertical position; default is alignment on the center of the environment.
  • t - align on top row
  • b - align on bottom row
cols
Specifies the column formatting. It consists of a sequence of the following specifiers, corresponding to the sequence of columns and intercolumn material.
  • l - A column of left-aligned items.
  • r - A column of right-aligned items.
  • c - A column of centred items.
  • | - A vertical line the full height and depth of the environment.
  • @{text} - This inserts text in every row. An @-expression suppresses the intercolumn space normally inserted between columns; any desired space between the inserted text and the adjacent items must be included in text. An \extracolsep{wd} command in an @-expression causes an extra space of width wd to appear to the left of all subsequent columns, until countermanded by another \extracolsep command. Unlike ordinary intercolumn space, this extra space is not suppressed by an @-expression. An \extracolsep command can be used only in an @-expression in the cols argument.
  • p{wd} - Produces a column with each item typeset in a parbox of width wd, as if it were the argument of a \parbox[t]{wd} command. However, a \\ may not appear in the item, except in the following situations:
    1. inside an environment like minipage, array, or tabular.
    2. inside an explicit \parbox.
    3. in the scope of a \centering, \raggedright, or \raggedleft declaration. The latter declarations must appear inside braces or an environment when used in a p-column element.
  • *{num}{cols} - Equivalent to num copies of cols, where num is any positive integer and cols is any list of column-specifiers, which may contain another *-expression.

These commands can be used inside a tabular environment:

\cline

\cline{i-j}

The \cline command draws horizontal lines across the columns specified, beginning in column i and ending in column j, which are identified in the mandatory argument.

\hline

The \hline command will draw a horizontal line the width of the table. It's most commonly used to draw a line at the top, bottom, and between the rows of the table.

\multicolumn

\multicolumn{cols}{pos}{text}

The \multicolumn is used to make an entry that spans several columns. The first mandatory argument, cols, specifies the number of columns to span. The second mandatory argument, pos, specifies the formatting of the entry; c for centred, l for flushleft, r for flushright. The third mandatory argument, text, specifies what text is to make up the entry.

\vline

The \vline command will draw a vertical line extending the full height and depth of its row. An \hfill command can be used to move the line to the edge of the column. It can also be used in an @-expression.

thebibliography

  \begin{thebibliography}{widest-label}
  \bibitem[label]{cite_key}
  .
  .
  .
  \end{thebibliography}
 

The thebibliography environment produces a bibliography or reference list. In the article class, this reference list is labelled "References"; in the report class, it is labelled "Bibliography".

\bibitem

\bibitem[label]{cite_key}

The \bibitem command generates an entry labelled by label. If the label argument is missing, a number is generated as the label, using the enumi counter. The cite_key is any sequence of letters, numbers, and punctuation symbols not containing a comma. This command writes an entry on the `.aux' file containing cite_key and the item's label. When this `.aux' file is read by the \begin{document} command, the item's label is associated with cite_key, causing the reference to cite_key by a \cite command to produce the associated label.

\cite

\cite[text]{key_list}

The key_list argument is a list of citation keys. This command generates an in-text citation to the references associated with the keys in key_list by entries on the `.aux' file read by the \begin{document} command.

The optional text argument will appear after the citation, i.e. \cite[p. 2]{knuth} might produce `[Knuth, p. 2]'.

\nocite

\nocite{key_list}

The \nocite command produces no text, but writes key_list, which is a list of one or more citation keys, on the `.aux' file.

Using BibTeX

If you use the BibTeX program by Oren Patashnik (highly recommended if you need a bibliography of more than a couple of titles) to maintain your bibliography, you don't use the thebibliography environment. Instead, you include the lines

         \bibliographystyle{style}
         \bibliography{bibfile}
 

where style refers to a file style.bst, which defines how your citations will look. The standard styles distributed with BibTeX are:

alpha
Sorted alphabetically. Labels are formed from name of author and year of publication.
plain
Sorted alphabetically. Labels are numeric.
unsrt
Like plain, but entries are in order of citation.
abbrv
Like plain, but more compact labels.

In addition, numerous other BibTeX style files exist tailored to the demands of various publications.

The argument to \bibliography refers to the file bibfile.bib, which should contain your database in BibTeX format. Only the entries referred to via \cite and \nocite will be listed in the bibliography.

theorem

  \begin{theorem}
   theorem text
  \end{theorem}
 

The theorem environment produces "Theorem x" in boldface followed by your theorem text.

titlepage

  \begin{titlepage}
   text
  \end{titlepage}
 

The titlepage environment creates a title page, i.e. a page with no printed page number or heading. It also causes the following page to be numbered page one. Formatting the title page is left to you. The \today command comes in handy for title pages.

Note that you can use the \maketitle (see section \maketitle) command to produce a standard title page.

verbatim

  \begin{verbatim}
   text
  \end{verbatim}
 

The verbatim environment is a paragraph-making environment that gets LaTeX to print exactly what you type in. It turns LaTeX into a typewriter with carriage returns and blanks having the same effect that they would on a typewriter.

\verb

\verb char literal_text char

\verb*char literal_text char

Typesets literal_text exactly as typed, including special characters and spaces, using a typewriter (\tt) type style. There may be no space between \verb or \verb* and char (space is shown here only for clarity). The *-form differs only in that spaces are printed as `\verb*| |'.

verse

  \begin{verse}
   text
  \end{verse}
 

The verse environment is designed for poetry, though you may find other uses for it.

The margins are indented on the left and the right. Separate the lines of each stanza with \\, and use one or more blank lines to separate the stanzas.

Footnotes

Footnotes can be produced in one of two ways. They can be produced with one command, the \footnote command. They can also be produced with two commands, the \footnotemark and the \footnotetext commands. See the specific command for information on why you would use one over the other.

\footnote

\footnote[number]{text}

The \footnote command places the numbered footnote text at the bottom of the current page. The optional argument, number, is used to change the default footnote number. This command can only be used in outer paragraph mode; i.e., you cannot use it in sectioning commands like \chapter, in figures, tables or in a tabular environment.

\footnotemark

The \footnotemark command puts the footnote number in the text. This command can be used in inner paragraph mode. The text of the footnote is supplied by the \footnotetext command.

This command can be used to produce several consecutive footnote markers referring to the same footnote by using

\footnotemark[\value{footnote}]

after the first \footnote command.

\footnotetext

\footnotetext[number]{text}

The \footnotetext command produces the text to be placed at the bottom of the page. This command can come anywhere after the \footnotemark command. The \footnotetext command must appear in outer paragraph mode.

The optional argument, number, is used to change the default footnote number.

Lengths

A length is a measure of distance. Many LaTeX commands take a length as an argument.

\newlength

\newlength{\gnat}

The \newlength command defines the mandatory argument, \gnat, as a length command with a value of 0in. An error occurs if a \gnat command already exists.

\setlength

\setlength{\gnat}{length}

The \setlength command is used to set the value of a length command. The length argument can be expressed in any terms of length LaTeX understands, i.e., inches (in), millimeters (mm), points (pt), etc.

\addtolength

\addtolength{\gnat}{length}

The \addtolength command increments a "length command" by the amount specified in the length argument. It can be a negative amount.

\settodepth

\settodepth{\gnat}{text}

The \settodepth command sets the value of a length command equal to the depth of the text argument.

\settoheight

\settoheight{\gnat}{text}

The \settoheight command sets the value of a length command equal to the height of the text argument.

\settowidth

\settowidth{\gnat}{text}

The \settowidth command sets the value of a length command equal to the width of the text argument.

Predefined lengths

\width

\height

\depth

\totalheight

These length parameters can be used in the arguments of the box-making commands See section Spaces & Boxes. They specify the natural width etc. of the text in the box. \totalheight equals \height + \depth. To make a box with the text stretched to double the natural size, e.g., say

\makebox[2\width]{Get a stretcher}

Letters

You can use LaTeX to typeset letters, both personal and business. The letter document class is designed to make a number of letters at once, although you can make just one if you so desire.

Your `.tex' source file has the same minimum commands as the other document classes, i.e., you must have the following commands as a minimum:

  \documentclass{letter}
  \begin{document}
   ... letters ...
  \end{document}
 

Each letter is a letter environment, whose argument is the name and address of the recipient. For example, you might have:

  \begin{letter}{Mr. Joe Smith\\ 2345 Princess St.
       \\ Edinburgh, EH1 1AA}
    ...
  \end{letter}
 

The letter itself begins with the \opening command. The text of the letter follows. It is typed as ordinary LaTeX input. Commands that make no sense in a letter, like \chapter, do not work. The letter closes with a \closing command.

After the closing, you can have additional material. The \cc command produces the usual "cc: ...". There's also a similar \encl command for a list of enclosures. With both these commands, use \\ to separate the items.

These commands are used with the letter class:

\address

\address{Return address}

The return address, as it should appear on the letter and the envelope. Separate lines of the address should be separated by \\ commands. If you do not make an \address declaration, then the letter will be formatted for copying onto your organization's standard letterhead. If you give an \address declaration, then the letter will be formatted as a personal letter.

\cc

\cc{Kate Schechter\\Rob McKenna}

Generate a list of other persons the letter was sent to. Each name is printed on a separate line.

\closing

\closing{text}

The letter closes with a \closing command, i.e.,

  \closing{Best Regards,}
 

\encl

\encl{CV\\Certificates}

Generate a list of enclosed material.

\location

\location{address}

This modifies your organization's standard address. This only appears if the firstpage pagestyle is selected.

\makelabels

\makelabels{number}

If you issue this command in the preamble, LaTeX will create a sheet of address labels. This sheet will be output before the letters.

\name

\name{June Davenport}

Your name, used for printing on the envelope together with the return address.

\opening

\opening{text}

The letter begins with the \opening command. The mandatory argument, text, is whatever text you wish to start your letter, i.e.,

  \opening{Dear Joe,}
 

\ps

\ps

Use this command before a postscript.

\signature

\signature{Harvey Swick}

Your name, as it should appear at the end of the letter underneath the space for your signature. Items that should go on separate lines should be separated by \\ commands.

\startbreaks

\startbreaks

Used after a \stopbreaks command to allow page breaks again.

\stopbreaks

\stopbreaks

Inhibit page breaks until a \startbreaks command occurs.

\telephone

\telephone{number}

This is your telephone number. This only appears if the firstpage pagestyle is selected.

Line & Page Breaking

The first thing LaTeX does when processing ordinary text is to translate your input file into a string of glyphs and spaces. To produce a printed document, this string must be broken into lines, and these lines must be broken into pages. In some environments, you do the line breaking yourself with the \\ command, but LaTeX usually does it for you.

\\

\\[*][extra-space]

The \\ command tells LaTeX to start a new line. It has an optional argument, extra-space, that specifies how much extra vertical space is to be inserted before the next line. This can be a negative amount.

The \\* command is the same as the ordinary \\ command except that it tells LaTeX not to start a new page after the line.

\-

The \- command tells LaTeX that it may hyphenate the word at that point. LaTeX is very good at hyphenating, and it will usually find all correct hyphenation points. The \- command is used for the exceptional cases.

Note that when you insert \- commands in a word, the word will only be hyphenated at those points and not at any of the hyphenation points that LaTeX might otherwise have chosen.

\cleardoublepage

The \cleardoublepage command ends the current page and causes all figures and tables that have so far appeared in the input to be printed. In a two-sided printing style, it also makes the next page a right-hand (odd-numbered) page, producing a blank page if necessary.

\clearpage

The \clearpage command ends the current page and causes all figures and tables that have so far appeared in the input to be printed.

\enlargethispage

\enlargethispage{size}

\enlargethispage*{size}

Enlarge the \textheight for the current page by the specified amount; e.g. \enlargethispage{\baselineskip} will allow one additional line.

The starred form tries to squeeze the material together on the page as much as possible. This is normally used together with an explicit \pagebreak.

\fussy

\fussy

This declaration (which is the default) makes TeX more fussy about line breaking. This can avoids too much space between words, but may produce overfull boxes.

This command cancels the effect of a previous \sloppy command. section \sloppy

\hyphenation

\hyphenation{words}

The \hyphenation command declares allowed hyphenation points, where words is a list of words, separated by spaces, in which each hyphenation point is indicated by a - character.

\linebreak

\linebreak[number]

The \linebreak command tells LaTeX to break the current line at the point of the command. With the optional argument, number, you can convert the \linebreak command from a demand to a request. The number must be a number from 0 to 4. The higher the number, the more insistent the request is.

The \linebreak command causes LaTeX to stretch the line so it extends to the right margin.

\newline

The \newline command breaks the line right where it is. It can only be used in paragraph mode.

\newpage

The \newpage command ends the current page.

\nolinebreak

\nolinebreak[number]

The \nolinebreak command prevents LaTeX from breaking the current line at the point of the command. With the optional argument, number, you can convert the \nolinebreak command from a demand to a request. The number must be a number from 0 to 4. The higher the number, the more insistent the request is.

\nopagebreak

\nopagebreak[number]

The \nopagebreak command prevents LaTeX from breaking the current page at the point of the command. With the optional argument, number, you can convert the \nopagebreak command from a demand to a request. The number must be a number from 0 to 4. The higher the number, the more insistent the request is.

\pagebreak

\pagebreak[number]

The \pagebreak command tells LaTeX to break the current page at the point of the command. With the optional argument, number, you can convert the \pagebreak command from a demand to a request. The number must be a number from 0 to 4. The higher the number, the more insistent the request is.

\sloppy

\sloppy

This declaration makes TeX less fussy about line breaking. This can prevent overfull boxes, but may leave too much space between words.

Lasts until a \fussy command is issued. section \fussy.

Making Paragraphs

A paragraph is ended by one or more completely blank lines -- lines not containing even a %. A blank line should not appear where a new paragraph cannot be started, such as in math mode or in the argument of a sectioning command.

\indent

\indent

This produces a horizontal space whose width equals the width of the paragraph indentation. It is used to add paragraph indentation where it would otherwise be suppressed.

\noindent

\noindent

When used at the beginning of the paragraph, it suppresses the paragraph indentation. It has no effect when used in the middle of a paragraph.

\par

Equivalent to a blank line; often used to make command or environment definitions easier to read.

Margin Notes

The command \marginpar[left]{right} creates a note in the margin. The first line will be at the same height as the line in the text where the \marginpar occurs.

When you only specify the mandatory argument right, the text will be placed

By issuing the command \reversemarginpar, you can force the marginal notes to go into the opposite (inside) margin.

When you specify both arguments, left is used for the left margin, and right is used for the right margin.

The first word will normally not be hyphenated; you can enable hyphenation by prefixing the first word with a \hspace{0pt} command.

Math Formulae

There are three environments that put LaTeX in math mode:

math
For Formulae that appear right in the text.
displaymath
For Formulae that appear on their own line.
equation
The same as the displaymath environment except that it adds an equation number in the right margin.

The math environment can be used in both paragraph and LR mode, but the displaymath and equation environments can be used only in paragraph mode. The math and displaymath environments are used so often that they have the following short forms:

     \(...\)     instead of     \begin{math}...\end{math}
 
     \[...\]     instead of     \begin{displaymath}...\end{displaymath}
 

In fact, the math environment is so common that it has an even shorter form:

     $ ... $     instead of     \(...\)
 

Subscripts & Superscripts

To get an expression exp to appear as a subscript, you just type _{exp}. To get exp to appear as a superscript, you type ^{exp}. LaTeX handles superscripted superscripts and all of that stuff in the natural way. It even does the right thing when something has both a subscript and a superscript.

Math Symbols

LaTeX provides almost any mathematical symbol you're likely to need. The commands for generating them can be used only in math mode. For example, if you include $\pi$ in your source, you will get the symbol in your output.

Spacing in Math Mode

In a math environment, LaTeX ignores the spaces you type and puts in the spacing that it thinks is best. LaTeX formats mathematics the way it's done in mathematics texts. If you want different spacing, LaTeX provides the following four commands for use in math mode:

  1. \; - a thick space
  2. \: - a medium space
  3. \, - a thin space
  4. \! - a negative thin space

Math Miscellany

\cdots
Produces a horizontal ellipsis where the dots are raised to the center of the line. eg.
\ddots
Produces a diagonal ellipsis. eg.
\frac{num}{den}
Produces the fraction num divided by den. eg.
\ldots
Produces an ellipsis. This command works in any mode, not just math mode. eg.
\overbrace{text}
Generates a brace over text. eg.
\overline{text}
Causes the argument text to be overlined. eg.
\sqrt[root]{arg}
Produces the square root of its argument. The optional argument, root, determines what root to produce, i.e., the cube root of x+y would be typed as $\sqrt[3]{x+y}$. eg.
\underbrace{text}
Generates text with a brace underneath. eg.
\underline{text}
Causes the argument text to be underlined. This command can also be used in paragraph and LR modes. eg.
\vdots
Produces a vertical ellipsis. eg.
Modes

When LaTeX is processing your input text, it is always in one of three modes:

LaTeX changes mode only when it goes up or down a staircase to a different level, though not all level changes produce mode changes. Mode changes occur only when entering or leaving an environment, or when LaTeX is processing the argument of certain text-producing commands.

"Paragraph mode" is the most common; it's the one LaTeX is in when processing ordinary text. In that mode, LaTeX breaks your text into lines and breaks the lines into pages. LaTeX is in "math mode" when it's generating a mathematical formula. In "LR mode", as in paragraph mode, LaTeX considers the output that it produces to be a string of words with spaces between them. However, unlike paragraph mode, LaTeX keeps going from left to right; it never starts a new line in LR mode. Even if you put a hundred words into an \mbox, LaTeX would keep typesetting them from left to right inside a single box, and then complain because the resulting box was too wide to fit on the line.

LaTeX is in LR mode when it starts making a box with an \mbox command. You can get it to enter a different mode inside the box - for example, you can make it enter math mode to put a formula in the box. There are also several text-producing commands and environments for making a box that put LaTeX in paragraph mode. The box make by one of these commands or environments will be called a parbox. When LaTeX is in paragraph mode while making a box, it is said to be in "inner paragraph mode". Its normal paragraph mode, which it starts out in, is called "outer paragraph mode".

Page Styles

The \documentclass command determines the size and position of the page's head and foot. The page style determines what goes in them.

\maketitle

\maketitle

The \maketitle command generates a title on a separate title page - except in the article class, where the title normally goes at the top of the first page. Information used to produce the title is obtained from the following declarations:

See section Page Styles for the commands to give the information.

\author

\author{names}

The \author command declares the author(s), where names is a list of authors separated by \and commands. Use \\ to separate lines within a single author's entry -- for example, to give the author's institution or address.

\date

\date{text}

The \date command declares text to be the document's date. With no \date command, the current date is used.

\thanks

\thanks{text}

The \thanks command produces a \footnote to the title.

\title

\title{text}

The \title command declares text to be the title. Use \\ to tell LaTeX where to start a new line in a long title.

\pagenumbering

\pagenumbering{num_style}

Specifies the style of page numbers. Possible values of num_style are:

\pagestyle

\pagestyle{option}

The \pagestyle command changes the style from the current page on throughout the remainder of your document.

The valid options are:

\markboth

 \markboth{left head}{right head}
 

The \markboth command is used in conjunction with the page style myheadings for setting both the left and the right heading. You should note that a "left-hand heading" is generated by the last \markboth command before the end of the page, while a "right-hand heading" is generated by the first \markboth or \markright that comes on the page if there is one, otherwise by the last one before the page.

\markright

 \markright{right head}
 

The \markright command is used in conjunction with the page style myheadings for setting the right heading, leaving the left heading unchanged. You should note that a "left-hand heading" is generated by the last \markboth command before the end of the page, while a "right-hand heading" is generated by the first \markboth or \markright that comes on the page if there is one, otherwise by the last one before the page.

\thispagestyle

\thispagestyle{option}

The \thispagestyle command works in the same manner as the \pagestyle command except that it changes the style for the current page only.

Sectioning

Sectioning commands provide the means to structure your text into units.

All sectioning commands take the same general form, i.e.,

\chapter[optional]{title}

In addition to providing the heading in the text, the mandatory argument of the sectioning command can appear in two other places:

  1. The table of contents
  2. The running head at the top of the page

You may not want the same thing to appear in these other two places as appears in the text heading. To handle this situation, the sectioning commands have an optional argument that provides the text for these other two purposes.

All sectioning commands have *-forms that print a title, but do not include a number and do not make an entry in the table of contents.

\appendix

The \appendix command changes the way sectional units are numbered. The \appendix command generates no text and does not affect the numbering of parts. The normal use of this command is something like

 \chapter{The First Chapter}
 ...
 \appendix
 \chapter{The First Appendix}
 
Spaces & Boxes

All the predefined length parameters See section Predefined lengths can be used in the arguments of the box-making commands.

\dotfill

The \dotfill command produces a "rubber length" that produces dots instead of just spaces.

\hfill

The \hfill fill command produces a "rubber length" which can stretch or shrink horizontally. It will be filled with spaces.

\hrulefill

The \hrulefill fill command produces a "rubber length" which can stretch or shrink horizontally. It will be filled with a horizontal rule.

\hspace

\hspace[*]{length}

The \hspace command adds horizontal space. The length of the space can be expressed in any terms that LaTeX understands, i.e., points, inches, etc. You can add negative as well as positive space with an \hspace command. Adding negative space is like backspacing.

LaTeX removes horizontal space that comes at the end of a line. If you don't want LaTeX to remove this space, include the optional * argument. Then the space is never removed.

\addvspace

\addvspace{length}

The \addvspace command normally adds a vertical space of height length. However, if vertical space has already been added to the same point in the output by a previous \addvspace command, then this command will not add more space than needed to make the natural length of the total vertical space equal to length.

\bigskip

The \bigskip command is equivalent to \vspace{bigskipamount} where bigskipamount is determined by the document class.

\medskip

The \medskip command is equivalent to \vspace{medskipamount} where medskipamount is determined by the document class.

\smallskip

\smallskip

The \smallskip command is equivalent to \vspace{smallskipamount} where smallskipamount is determined by the document class.

\vfill

The \vfill fill command produces a rubber length which can stretch or shrink vertically.

\vspace

\vspace[*]{length}

The \vspace command adds vertical space. The length of the space can be expressed in any terms that LaTeX understands, i.e., points, inches, etc. You can add negative as well as positive space with an \vspace command.

LaTeX removes vertical space that comes at the end of a page. If you don't want LaTeX to remove this space, include the optional * argument. Then the space is never removed.

\fbox

\fbox{text}

The \fbox command is exactly the same as the \mbox command, except that it puts a frame around the outside of the box that it creates.

\framebox

\framebox[width][position]{text}

The \framebox command is exactly the same as the \makebox command, except that it puts a frame around the outside of the box that it creates.

The framebox command produces a rule of thickness \fboxrule, and leaves a space \fboxsep between the rule and the contents of the box.

lrbox

\begin{lrbox}{cmd} text \end{lrbox}

This is the environment form of \sbox.

The text inside the environment is saved in the box cmd, which must have been declared with \newsavebox.

\makebox

\makebox[width][position]{text}

The \makebox command creates a box just wide enough to contain the text specified. The width of the box is specified by the optional width argument. The position of the text within the box is determined by the optional position argument.

See section \makebox.

\mbox

\mbox{text}

The \mbox command creates a box just wide enough to hold the text created by its argument.

Use this command to prevent text from being split across lines.

\newsavebox

\newsavebox{cmd}

Declares cmd, which must be a command name that is not already defined, to be a bin for saving boxes.

\parbox

\parbox[position][height][inner-pos]{width}{text}

A parbox is a box whose contents are created in paragraph mode. The \parbox has two mandatory arguments:

LaTeX will position a parbox so its center lines up with the center of the text line. The optional position argument allows you to line up either the top or bottom line in the parbox (default is top).

If the height argument is not given, the box will have the natural height of the text.

The inner-pos argument controls the placement of the text inside the box. If it is not specified, position is used.

A \parbox command is used for a parbox containing a small piece of text, with nothing fancy inside. In particular, you shouldn't use any of the paragraph-making environments inside a \parbox argument. For larger pieces of text, including ones containing a paragraph-making environment, you should use a minipage environment See section minipage.

\raisebox

\raisebox{distance}[extend-above][extend-below]{text}

The \raisebox command is used to raise or lower text. The first mandatory argument specifies how high the text is to be raised (or lowered if it is a negative amount). The text itself is processed in LR mode.

Sometimes it's useful to make LaTeX think something has a different size than it really does - or a different size than LaTeX would normally think it has. The \raisebox command lets you tell LaTeX how tall it is.

The first optional argument, extend-above, makes LaTeX think that the text extends above the line by the amount specified. The second optional argument, extend-below, makes LaTeX think that the text extends below the line by the amount specified.

\rule

\rule[raise-height]{width}{thickness}

The \rule command is used to produce horizontal lines. The arguments are defined as follows:

\savebox

  \savebox{cmd}[width][pos]{text}
 

This command typeset text in a box just as for \makebox. However, instead of printing the resulting box, it saves it in bin cmd, which must have been declared with \newsavebox.

\sbox

\sbox{text}

This commands typeset text in a box just as for \mbox. However, instead of printing the resulting box, it saves it in bin cmd, which must have been declared with \newsavebox.

\usebox

\usebox{cmd}

Prints the box most recently saved in bin cmd by a \savebox command.

Special Characters

The following characters play a special role in LaTeX and are called "special printing characters", or simply "special characters".

                        # $ % & ~ _ ^ \ { }
 

Whenever you put one of these special characters into your file, you are doing something special. If you simply want the character to be printed just as any other letter, include a \ in front of the character. For example, \$ will produce $ in your output.

One exception to this rule is the \ itself because \\ has its own special meaning. A \ is produced by typing $\backslash$ in your file.

Also, \~ means `place a tilde accent over the following letter', so you will probably want to use \verb instead.

In addition, you can access any character of a font once you know its number by using the \symbol command. For example, the character used for displaying spaces in the \verb* command has the code decimal 32, so it can be typed as \symbol{32}.

You can also specify octal numbers with ' or hexadecimal numbers with ", so the previous example could also be written as \symbol{'40} or \symbol{"20}.

Splitting the Input

A large document requires a lot of input. Rather than putting the whole input in a single large file, it's more efficient to split it into several smaller ones. Regardless of how many separate files you use, there is one that is the root file; it is the one whose name you type when you run LaTeX.

\include

\include{file}

The \include command is used in conjunction with the \includeonly command for selective inclusion of files. The file argument is the first name of a file, denoting `file.tex'. If file is one the file names in the file list of the \includeonly command or if there is no \includeonly command, the \include command is equivalent to

 \clearpage \input{file} \clearpage
 

except that if the file `file.tex' does not exist, then a warning message rather than an error is produced. If the file is not in the file list, the \include command is equivalent to \clearpage.

The \include command may not appear in the preamble or in a file read by another \include command.

\includeonly

\includeonly{file_list}

The \includeonly command controls which files will be read in by an \include command. file_list should be a comma-separated list of filenames. Each filename must match exactly a filename specified in a \include command. This command can only appear in the preamble.

\input

\input{file}

The \input command causes the indicated file to be read and processed, exactly as if its contents had been inserted in the current file at that point. The file name may be a complete file name with extension or just a first name, in which case the file `file.tex' is used.

Starting & Ending

Your input file must contain the following commands as a minimum:

  \documentclass{class}
  \begin{document}
    ... your text goes here ...
  \end{document}
 

where the class selected is one of the valid classes for LaTeX. See section Document Classes for details of the various document classes available locally.

You may include other LaTeX commands between the \documentclass and the \begin{document} commands (i.e., in the `preamble').

Table of Contents

A table of contents is produced with the \tableofcontents command. You put the command right where you want the table of contents to go; LaTeX does the rest for you. It produces a heading, but it does not automatically start a new page. If you want a new page after the table of contents, include a \newpage command after the \tableofcontents command.

There are similar commands \listoffigures and \listoftables for producing a list of figures and a list of tables, respectively. Everything works exactly the same as for the table of contents.

NOTE: If you want any of these items to be generated, you cannot have the \nofiles command in your document.

\addcontentsline

\addcontentsline{file}{sec_unit}{entry}

The \addcontentsline command adds an entry to the specified list or table where:

\addtocontents

\addtocontents{file}{text}

The \addtocontents command adds text (or formatting commands) directly to the file that generates the table of contents or list of figures or tables.

Terminal Input/Output

\typein

\typein[cmd]{msg}

Prints msg on the terminal and causes LaTeX to stop and wait for you to type a line of input, ending with return. If the cmd argument is missing, the typed input is processed as if it had been included in the input file in place of the \typein command. If the cmd argument is present, it must be a command name. This command name is then defined or redefined to be the typed input.

\typeout

\typeout{msg}

Prints msg on the terminal and in the log file. Commands in msg that are defined with \newcommand or \renewcommand are replaced by their definitions before being printed.

LaTeX's usual rules for treating multiple spaces as a single space and ignoring spaces after a command name apply to msg. A \space command in msg causes a single space to be printed. A ^^J in msg prints a newline.

Typefaces

The typeface is specified by giving the "size" and "style". A typeface is also called a "font".

Styles

The following type style commands are supported by LaTeX.

These commands are used like \textit{italics text}. The corresponding command in parenthesis is the "declaration form", which takes no arguments. The scope of the declaration form lasts until the next type style command or the end of the current group.

The declaration forms are cumulative; i.e., you can say \sffamily\bfseries to get sans serif boldface.

You can also use the environment form of the declaration forms; e.g. \begin{ttfamily}...\end{ttfamily}.

\textrm (\rmfamily)
Roman.
\textit (\itshape)
\emph
Emphasis (toggles between \textit and \textrm).
\textmd (\mdseries)
Medium weight (default). The opposite of boldface.
\textbf (\bfseries)
Boldface.
\textup (\upshape)
Upright (default). The opposite of slanted.
\textsl (\slshape)
Slanted.
\textsf (\sffamily)
Sans serif.
\textsc (\scshape)
Small caps.
\texttt (\ttfamily)
Typewriter.
\textnormal (\normalfont)
Main document font.
\mathrm
Roman, for use in math mode.
\mathbf
Boldface, for use in math mode.
\mathsf
Sans serif, for use in math mode.
\mathtt
Typewriter, for use in math mode.
\mathit
Italics, for use in math mode, e.g. variable names with several letters.
\mathnormal
For use in math mode, e.g. inside another type style declaration.
\mathcal
`Calligraphic' letters, for use in math mode.

In addition, the command \mathversion{bold} can be used for switching to bold letters and symbols in formulas. \mathversion{normal} restores the default.

Sizes

The following standard type size commands are supported by LaTeX.

The commands as listed here are "declaration forms". The scope of the declaration form lasts until the next type style command or the end of the current group.

You can also use the environment form of these commands; e.g. \begin{tiny}...\end{tiny}.

\tiny
\scriptsize
\footnotesize
\small
\normalsize
(default)
\large
\Large
\LARGE
\huge
\Huge

Low-level font commands

These commands are primarily intended for writers of macros and packages. The commands listed here are only a subset of the available ones. For full details, you should consult Chapter 7 of The LaTeX Companion.

\fontencoding{enc}
Select font encoding. Valid encodings include OT1 and T1.
\fontfamily{family}
Select font family. Valid families include:
  • cmr for Computer Modern Roman
  • cmss for Computer Modern Sans Serif
  • cmtt for Computer Modern Typewriter
and numerous others.
\fontseries{series}
Select font series. Valid series include:
  • m Medium (normal)
  • b Bold
  • c Condensed
  • bc Bold condensed
  • bx Bold extended
and various other combinations.
\fontshape{shape}
Select font shape. Valid shapes are:
  • n Upright (normal)
  • it Italic
  • sl Slanted (oblique)
  • sc Small caps
  • ui Upright italics
  • ol Outline
The two last shapes are not available for most font families.
\fontsize{size}{skip}
Set font size. The first parameter is the font size to switch to; the second is the \baselineskip to use. The unit of both parameters defaults to pt. A rule of thumb is that the baselineskip should be 1.2 times the font size.
\selectfont
The changes made by calling the four font commands described above do not come into effect until \selectfont is called.
\usefont{enc}{family}{series}{shape}
Equivalent to calling \fontencoding, \fontfamily, \fontseries and \fontshape with the given parameters, followed by \selectfont.

LaTeX Reference
Kile
diff --git a/src/dialogs/pdf-wizard/pdfdialog.cpp b/src/dialogs/pdf-wizard/pdfdialog.cpp index d9f3caad..7a4504ea 100755 --- a/src/dialogs/pdf-wizard/pdfdialog.cpp +++ b/src/dialogs/pdf-wizard/pdfdialog.cpp @@ -1,1790 +1,1790 @@ /****************************************************************************** Copyright (C) 2009-2011 by Holger Danielsson (holger.danielsson@versanet.de) ******************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "pdfdialog.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "errorhandler.h" #include "kileconfig.h" #include "kiledebug.h" namespace KileDialog { PdfDialog::PdfDialog(QWidget *parent, const QString &texfilename,const QString &startdir, const QString &latexextensions, KileTool::Manager *manager, KileErrorHandler *errorHandler, KileWidget::OutputView *output) : QDialog(parent) , m_startdir(startdir) , m_manager(manager) , m_errorHandler(errorHandler) , m_output(output) , m_proc(Q_NULLPTR) , m_rearrangeButton(new QPushButton) , m_buttonBox(new QDialogButtonBox(QDialogButtonBox::Help|QDialogButtonBox::Close)) { setWindowTitle(i18n("PDF Wizard")); setModal(true); QVBoxLayout *mainLayout = new QVBoxLayout; setLayout(mainLayout); m_rearrangeButton->setDefault(true); // determine if a pdffile already exists QString pdffilename; if(!texfilename.isEmpty()) { // working with a pdf document, so we try to determine the LaTeX source file QStringList extlist = latexextensions.split(' '); for (QStringList::Iterator it = extlist.begin(); it != extlist.end(); ++it) { if (texfilename.indexOf((*it), -(*it).length()) >= 0) { pdffilename = texfilename.left(texfilename.length() - (*it).length()) + ".pdf"; if (!QFileInfo(pdffilename).exists()) pdffilename.clear(); break; } } } // prepare dialog QWidget *page = new QWidget(this); mainLayout->addWidget(page); m_PdfDialog.setupUi(page); page->setMinimumWidth(500); m_PdfDialog.m_pbPrinting->setIcon(QIcon::fromTheme("printer")); m_PdfDialog.m_pbAll->setIcon(QIcon::fromTheme("list-add")); m_PdfDialog.m_pbBackgroundColor->setColor(QColor(255, 255, 224)); // insert KileWidget::CategoryComboBox m_cbTask = new KileWidget::CategoryComboBox(m_PdfDialog.m_gbParameter); QGridLayout *paramLayout = (QGridLayout *)m_PdfDialog.m_gbParameter->layout(); paramLayout->addWidget(m_cbTask, 4, 1); // setup filenames m_PdfDialog.m_edInfile->setFilter(i18n("*.pdf|PDF Files")); m_PdfDialog.m_edInfile->lineEdit()->setText(pdffilename); m_PdfDialog.m_edOutfile->setFilter(i18n("*.pdf|PDF Files")); m_PdfDialog.m_edOutfile->setMode(KFile::File | KFile::LocalOnly ); m_PdfDialog.m_edOutfile->lineEdit()->setText( getOutfileName(pdffilename) ); //max password length for pdf files m_PdfDialog.m_edPassword->setMaxLength(32); // set an user button to execute the task and icon for help button m_rearrangeButton->setText(i18n("Re&arrange")); m_rearrangeButton->setIcon(QIcon::fromTheme("system-run")); m_PdfDialog.m_lbParameterIcon->setPixmap(KIconLoader::global()->loadIcon("help-about", KIconLoader::NoGroup, KIconLoader::SizeSmallMedium)); // init important variables m_numpages = 0; m_encrypted = false; m_pdftk = false; m_pdfpages = false; m_scriptrunning = false; m_pagesize = QSize(0,0); // setup tasks m_tasklist << i18n("1 Page + Empty Page --> 2up") // 0 PDF_PAGE_EMPTY << i18n("1 Page + Duplicate --> 2up") // 1 PDF_PAGE_DUPLICATE << i18n("2 Pages --> 2up") // 2 PDF_2UP << i18n("2 Pages (landscape) --> 2up") // 3 PDF_2UP_LANDSCAPE << i18n("4 Pages --> 4up") // 4 PDF_4UP << i18n("4 Pages (landscape) --> 4up") // 5 PDF_4UP_LANDSCAPE << i18n("Select Even Pages") // 6 PDF_EVEN << i18n("Select Odd Pages") // 7 PDF_ODD << i18n("Select Even Pages (reverse order)") // 8 PDF_EVEN_REV << i18n("Select Odd Pages (reverse order)") // 9 PDF_ODD_REV << i18n("Reverse All Pages") // 10 PDF_REVERSE << i18n("Decrypt") // 11 PDF_DECRYPT << i18n("Select Pages") // 12 PDF_SELECT << i18n("Delete Pages") // 13 PDF_DELETE << i18n("Apply a background watermark") // 14 PDF_PDFTK_BACKGROUND << i18n("Apply a background color") // 15 PDF_PDFTK_BGCOLOR << i18n("Apply a foreground stamp") // 16 PDF_PDFTK_STAMP << i18n("pdftk: Choose Parameter") // 17 PDF_PDFTK_FREE << i18n("pdfpages: Choose Parameter") // 18 PDF_PDFPAGES_FREE ; // set data for properties: key/widget m_pdfInfoKeys << "Title" << "Subject" << "Author" << "Creator" << "Producer" << "Keywords"; m_pdfInfoWidget["Title"] = m_PdfDialog.m_leTitle; m_pdfInfoWidget["Subject"] = m_PdfDialog.m_leSubject; m_pdfInfoWidget["Keywords"] = m_PdfDialog.m_leKeywords; m_pdfInfoWidget["Author"] = m_PdfDialog.m_leAuthor; m_pdfInfoWidget["Creator"] = m_PdfDialog.m_leCreator; m_pdfInfoWidget["Producer"] = m_PdfDialog.m_leProducer; // set data for permissions: key/widget m_pdfPermissionKeys << AllowModify << AllowCopy << AllowPrint << AllowNotes << AllowFillForms; m_pdfPermissionWidgets << m_PdfDialog.m_cbModify << m_PdfDialog.m_cbCopy << m_PdfDialog.m_cbPrinting << m_PdfDialog.m_cbAnnotations << m_PdfDialog.m_cbFormFeeds; m_pdfPermissionPdftk << "ModifyContents" << "CopyContents" << "Printing" << "ModifyAnnotations" << "FillIn"; // default permissions m_pdfPermissionState << false << false << false << false << false; // check for libpoppler pdf library #if LIBPOPPLER_AVAILABLE m_poppler = true; KILE_DEBUG_MAIN << "working with libpoppler pdf library"; #else m_poppler = false; KILE_DEBUG_MAIN << "working without libpoppler pdf library"; m_PdfDialog.tabWidget->removeTab(2); m_PdfDialog.tabWidget->removeTab(1); #endif // init Dialog m_PdfDialog.m_lbParameterInfo->setTextFormat(Qt::RichText); m_PdfDialog.m_cbOverwrite->setChecked(true); updateDialog(); // create tempdir m_tempdir = new QTemporaryDir(QDir::tempPath() + QLatin1Char('/') + "pdfwizard/pdf-"); KILE_DEBUG_MAIN << "tempdir: " << m_tempdir->path() ; connect(this, &PdfDialog::output, m_output, &KileWidget::OutputView::receive); connect(m_PdfDialog.m_edInfile->lineEdit(), &QLineEdit::textChanged, this, &PdfDialog::slotInputfileChanged); #if LIBPOPPLER_AVAILABLE connect(m_PdfDialog.tabWidget, SIGNAL(currentChanged(int)), this, SLOT(slotTabwidgetChanged(int))); connect(m_PdfDialog.m_pbPrinting, SIGNAL(clicked()), this, SLOT(slotPrintingClicked())); connect(m_PdfDialog.m_pbAll, SIGNAL(clicked()), this, SLOT(slotAllClicked())); #endif m_buttonBox->addButton(m_rearrangeButton, QDialogButtonBox::ActionRole); connect(m_buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept); connect(m_buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); connect(m_buttonBox, &QDialogButtonBox::helpRequested, this, &PdfDialog::slotShowHelp); connect(m_rearrangeButton, &QPushButton::clicked, this, &PdfDialog::slotExecute); mainLayout->addWidget(m_buttonBox); // find available utilities for this dialog executeScript("kpsewhich pdfpages.sty", QString(), PDF_SCRIPTMODE_TOOLS); } PdfDialog::~PdfDialog() { if (m_cbTask->currentIndex() != -1) { KileConfig::setPdfWizardLastTask(m_cbTask->currentIndex()); } delete m_tempdir; delete m_proc; } void PdfDialog::initUtilities() { // find pdfpages.sty? m_pdfpages = m_outputtext.contains("pdfpages.sty"); // additionally look for pdftk m_pdftk = !QStandardPaths::findExecutable("pdftk").isEmpty(); //m_pdfpages = false; // <----------- only for testing HACK //m_pdftk = false; // <----------- only for testing HACK KILE_DEBUG_MAIN << "Looking for pdf tools: pdftk=" << m_pdftk << " pdfpages.sty=" << m_pdfpages; #if !LIBPOPPLER_AVAILABLE m_imagemagick = KileConfig::imagemagick(); // we can't use libpoppler pdf library and need to find another method to determine the number of pdf pages // Kile will use three options before giving up if ( m_pdftk ) m_numpagesMode = PDF_SCRIPTMODE_NUMPAGES_PDFTK; else if ( m_imagemagick ) m_numpagesMode = PDF_SCRIPTMODE_NUMPAGES_IMAGEMAGICK; else m_numpagesMode = PDF_SCRIPTMODE_NUMPAGES_GHOSTSCRIPT; #endif // no pdftk, so properties and permissions are readonly if ( !m_pdftk ) { // set readonly properties for (QStringList::const_iterator it = m_pdfInfoKeys.constBegin(); it != m_pdfInfoKeys.constEnd(); ++it) { m_pdfInfoWidget[*it]->setReadOnly(true); } #if LIBPOPPLER_AVAILABLE // connect permission widgets for (int i=0; ilineEdit(), SIGNAL(textChanged(const QString &)), this, SLOT(slotOutputfileChanged(const QString &))); connect(m_PdfDialog.m_cbOverwrite, SIGNAL(stateChanged(int)), this, SLOT(slotOverwriteChanged(int))); connect(m_cbTask, SIGNAL(activated(int)), this, SLOT(slotTaskChanged(int))); } // setup dialog slotInputfileChanged(m_PdfDialog.m_edInfile->lineEdit()->text()); } // read properties and permissions from the PDF document void PdfDialog::pdfParser(const QString &filename) { #if LIBPOPPLER_AVAILABLE Poppler::Document *doc = Poppler::Document::load(filename); if ( !doc || doc->isLocked() ) { KILE_DEBUG_MAIN << "Error: could not open pdf document '" << filename << "'"; return; } KILE_DEBUG_MAIN << "Parse pdf document: " << filename; // read encryption m_encrypted = doc->isEncrypted(); m_PdfDialog.m_lbEncryption->setText( (m_encrypted) ? i18n("yes") : i18n("no") ); // read properties for (QStringList::const_iterator it = m_pdfInfoKeys.constBegin(); it != m_pdfInfoKeys.constEnd(); ++it) { QString value = doc->info(*it); m_pdfInfo[*it] = value; m_pdfInfoWidget[*it]->setText(value); } // read creation date and modification date m_PdfDialog.m_lbCreationDate->setText(QLocale().toString(doc->date("CreationDate"))); m_PdfDialog.m_lbModDate->setText(QLocale().toString(doc->date("ModDate"))); // read PDF version int major,minor; doc->getPdfVersion(&major,&minor); m_PdfDialog.m_lbFormat->setText( QString("PDF version %1.%2").arg(major).arg(minor) ); // read permissions for (int i=0; isetChecked(value); if ( !m_pdftk ) { m_pdfPermissionState[i] = value; } } // determine and set number of pages setNumberOfPages( doc->numPages() ); // look if all pages have the same size m_pagesize = allPagesSize(doc); delete doc; #else /* libpoppler pdf library is not available: * - we use a brute force method to determine, if this file is encrypted * - then we try to determine the number of pages with * - pdftk (always first choice, if installed) * - imagemagick (second choice) * - gs (third and last choice) * - if the pdf file is encrypted, pdftk will ask for a password */ // look if the pdf file is encrypted (brute force) m_encrypted = readEncryption(filename); KILE_DEBUG_MAIN << "PDF encryption: " << m_encrypted; // determine the number of pages of the pdf file determineNumberOfPages(filename,m_encrypted); KILE_DEBUG_MAIN << "PDF number of pages: " << m_numpages; // clear pagesize m_pagesize = QSize(0,0); #endif } #if LIBPOPPLER_AVAILABLE bool PdfDialog::isAllowed(Poppler::Document *doc, PDF_Permission permission) const { bool b = true; switch ( permission ) { case AllowModify: b = doc->okToChange(); break; case AllowCopy: b = doc->okToCopy(); break; case AllowPrint: b = doc->okToPrint(); break; case AllowNotes: b = doc->okToAddNotes(); break; case AllowFillForms: b = doc->okToFillForm(); break; default: ; } return b; } QSize PdfDialog::allPagesSize(Poppler::Document *doc) { QSize commonsize = QSize(0,0); // Access all pages of the PDF file (m_numpages is known) for ( int i=0; ipage(i); if ( pdfpage == 0 ) { KILE_DEBUG_MAIN << "Cannot parse all pages of the PDF file"; delete pdfpage; return QSize(0,0); } if ( i == 0 ) { commonsize = pdfpage->pageSize(); } else if ( commonsize != pdfpage->pageSize() ) { delete pdfpage; return QSize(0,0); } // documentation says: after the usage, the page must be deleted delete pdfpage; } return commonsize; } #endif void PdfDialog::setNumberOfPages(int numpages) { m_numpages = numpages; if (m_numpages > 0) { // show all, if the number of pages is known m_PdfDialog.tabWidget->widget(0)->setEnabled(true); QString pages; if ( m_encrypted ) m_PdfDialog.m_lbPages->setText(pages.setNum(m_numpages)+" "+i18n("(encrypted)")); else m_PdfDialog.m_lbPages->setText(pages.setNum(m_numpages)); } else { // hide all, if the number of pages can't be determined m_PdfDialog.tabWidget->widget(0)->setEnabled(false); m_PdfDialog.m_lbPages->setText(i18n("Error: unknown number of pages")); } } #if !LIBPOPPLER_AVAILABLE void PdfDialog::determineNumberOfPages(const QString &filename, bool askForPassword) { // determine the number of pages of the pdf file (delegate this task) QString command; QString passwordparam; int scriptmode = m_numpagesMode; if ( scriptmode==PDF_SCRIPTMODE_NUMPAGES_PDFTK && askForPassword ) { QString password = QInputDialog::getText(this, i18n("PDFTK-Password"), i18n("This PDF file is encrypted and 'pdftk' cannot open it.\n" "Please enter the password for this PDF file\n or leave it blank to try another method: "), QLineEdit::Normal, QString()).trimmed(); if(!password.isEmpty()) { passwordparam = " input_pw " + password; } else { scriptmode = ( m_imagemagick ) ? PDF_SCRIPTMODE_NUMPAGES_IMAGEMAGICK : PDF_SCRIPTMODE_NUMPAGES_GHOSTSCRIPT; } } // now take the original or changed mode if ( scriptmode == PDF_SCRIPTMODE_NUMPAGES_PDFTK ) { command = "pdftk \"" + filename + "\"" + passwordparam + " dump_data | grep NumberOfPages"; } else if ( scriptmode == PDF_SCRIPTMODE_NUMPAGES_IMAGEMAGICK ) { command = "identify -format \"%n\" \"" + filename + "\""; } else { command = "gs -q -c \"(" + filename + ") (r) file runpdfbegin pdfpagecount = quit\""; } // run Process KILE_DEBUG_MAIN << "execute for NumberOfPages: " << command; executeScript(command, m_tempdir->path(), scriptmode); } void PdfDialog::readNumberOfPages(int scriptmode, const QString &output) { int numpages = 0; bool ok; if ( scriptmode == PDF_SCRIPTMODE_NUMPAGES_PDFTK ) { KILE_DEBUG_MAIN << "pdftk output for NumberOfPages: " << output; if ( output.contains("OWNER PASSWORD REQUIRED") ) { QString filename = m_PdfDialog.m_edInfile->lineEdit()->text().trimmed(); determineNumberOfPages(m_PdfDialog.m_edInfile->lineEdit()->text().trimmed(),true); return; } else { QRegExp re("\\d+"); if ( re.indexIn(output) >= 0) { numpages = re.cap(0).toInt(&ok); } } } else { QString s = output; numpages = s.remove("\n").toInt(&ok); } setNumberOfPages(numpages); } bool PdfDialog::readEncryption(const QString &filename) { QFile file(filename); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { return false; } KILE_DEBUG_MAIN << "search for encryption "; QRegExp re("/Encrypt(\\W|\\s|$)"); QTextStream in(&file); QString line = in.readLine(); while ( !line.isNull() ) { if ( re.indexIn(line) >= 0 ) { KILE_DEBUG_MAIN << "pdf file is encrypted !!!"; return true; } line = in.readLine(); } return false; } #endif void PdfDialog::clearDocumentInfo() { m_numpages = 0; m_encrypted = false; m_PdfDialog.m_lbPassword->setEnabled(false); m_PdfDialog.m_edPassword->setEnabled(false); m_PdfDialog.m_edPassword->clear(); for (QStringList::const_iterator it = m_pdfInfoKeys.constBegin(); it != m_pdfInfoKeys.constEnd(); ++it) { m_pdfInfoWidget[*it]->clear(); } m_PdfDialog.m_lbCreationDate->clear(); m_PdfDialog.m_lbModDate->clear(); for (int i=0; isetChecked(false); } m_PdfDialog.m_lbPages->clear(); m_PdfDialog.m_lbFormat->clear(); m_PdfDialog.m_lbEncryption->clear(); } void PdfDialog::updateOwnerPassword(bool infile_exists) { int tabindex = m_PdfDialog.tabWidget->currentIndex(); bool state = ( infile_exists && (m_encrypted || (!m_encrypted && tabindex==2)) ) ? m_pdftk : false; m_PdfDialog.m_lbPassword->setEnabled(state); m_PdfDialog.m_edPassword->setEnabled(state); } // update dialog widgets void PdfDialog::updateDialog() { QString infile = m_PdfDialog.m_edInfile->lineEdit()->text().trimmed(); bool infile_exists = QFile(infile).exists(); updateOwnerPassword(infile_exists); updateTasks(); updateToolsInfo(); bool pstate = ( m_encrypted ) ? infile_exists && m_pdftk : infile_exists && (m_pdftk || m_pdfpages); m_PdfDialog.m_gbParameter->setEnabled(pstate); m_PdfDialog.m_gbProperties->setEnabled(infile_exists); m_PdfDialog.m_gbPermissions->setEnabled(infile_exists); m_PdfDialog.m_lbPrinting->setEnabled(infile_exists); m_PdfDialog.m_pbPrinting->setEnabled(infile_exists); m_PdfDialog.m_lbAll->setEnabled(infile_exists); m_PdfDialog.m_pbAll->setEnabled(infile_exists); // and exec button QString outfile = m_PdfDialog.m_edOutfile->lineEdit()->text().trimmed(); bool destination = m_PdfDialog.m_cbOverwrite->isChecked() || m_PdfDialog.m_cbView->isChecked(); bool state = ( infile_exists && (destination || (!destination && !outfile.isEmpty())) ); if ( m_PdfDialog.tabWidget->currentIndex() == 0 ) { state = state && (m_pdfpages || m_pdftk); } else { state = state && m_pdftk; } m_rearrangeButton->setEnabled(state&&!m_scriptrunning); } // update tools information void PdfDialog::updateToolsInfo() { QString info; QString newline = "
"; QString password = i18n("A password is necessary to set or change the current settings."); int tabindex = m_PdfDialog.tabWidget->currentIndex(); if (tabindex == 2 ) { info = ( m_pdftk ) ? i18n("The permissions of this document can be changed with pdftk.") + newline + password : i18n("pdftk is not available, so no permission can be changed."); } else if ( tabindex == 1 ) { if ( ! m_pdftk ) { info = i18n("pdftk is not available, so no property can be changed."); } else { info = i18n("The properties of this document can be changed with pdftk."); if ( m_encrypted ) { info += newline + password; } } } else { // if ( tabindex == 0 ) if ( m_encrypted ) { info = ( m_pdftk ) ? i18n("This input file is encrypted, so only pdftk works.") + newline + i18n("A password is necessary to rearrange pages.") : i18n("This input file is encrypted, but pdftk is not installed."); } else { if ( m_pdftk ) { // not encrypted and pdftk info = ( m_pdfpages ) ? i18n("This wizard will use pdftk and the LaTeX package pdfpages.") : i18n("This wizard will only use pdftk (pdfpages.sty is not installed)."); } else { // not encrypted and not pdftk info = ( m_pdfpages ) ? i18n("This wizard will only use the LaTeX package pdfpages (pdftk was not found).") : i18n("This wizard can't work, because no tool was found (see help section)."); } } } QString popplerinfo = (m_poppler ) ? QString() : newline + i18n("(Compiled without libpoppler pdf library. Not all tasks are available.)"); info += popplerinfo; // set info text m_PdfDialog.m_lbParameterInfo->setText(info); } // it is important to calculate the task index from the combobox index, // as not all tasks are available, when an utility was not found void PdfDialog::updateTasks() { // according to QT 4.4 docu the index of QComboBox might change if adding or removing items // but because we populate the QComboBox before we start the dialog, we can use the index here int lastindex = m_cbTask->currentIndex(); QString lasttext = m_cbTask->currentText(); int group = 0; m_cbTask->clear(); if (m_pdfpages && !m_encrypted) { // task index m_cbTask->addItem( m_tasklist[PDF_PAGE_EMPTY] ); // 0 PDF_PAGE_EMPTY m_cbTask->addItem( m_tasklist[PDF_PAGE_DUPLICATE] ); // 1 PDF_PAGE_DUPLICATE m_cbTask->addItem( m_tasklist[PDF_2UP] ); // 2 PDF_2UP m_cbTask->addItem( m_tasklist[PDF_2UP_LANDSCAPE] ); // 3 PDF_2UP_LANDSCAPE m_cbTask->addItem( m_tasklist[PDF_4UP] ); // 4 PDF_4UP m_cbTask->addItem( m_tasklist[PDF_4UP_LANDSCAPE] ); // 5 PDF_4UP_LANDSCAPE group = 1; } if ( (m_pdfpages && !m_encrypted) || m_pdftk ){ if ( group > 0 ) { m_cbTask->addCategoryItem(""); } m_cbTask->addItem( m_tasklist[PDF_EVEN] ); // 6 PDF_EVEN m_cbTask->addItem( m_tasklist[PDF_ODD] ); // 7 PDF_ODD m_cbTask->addItem( m_tasklist[PDF_EVEN_REV] ); // 8 PDF_EVEN_REV m_cbTask->addItem( m_tasklist[PDF_ODD_REV] ); // 9 PDF_ODD_REV m_cbTask->addItem( m_tasklist[PDF_REVERSE] ); // 10 PDF_REVERSE if (m_encrypted) { m_cbTask->addItem( m_tasklist[PDF_DECRYPT] ); // 11 PDF_DECRYPT } m_cbTask->addCategoryItem(""); m_cbTask->addItem( m_tasklist[PDF_SELECT] ); // 12 PDF_SELECT m_cbTask->addItem( m_tasklist[PDF_DELETE] ); // 13 PDF_DELETE group = 2; } if (m_pdftk) { m_cbTask->addCategoryItem(""); m_cbTask->addItem( m_tasklist[PDF_PDFTK_BACKGROUND] ); // 14 PDF_PDFTK_BACKGROUND if ( ! m_pagesize.isNull() ) { m_cbTask->addItem( m_tasklist[PDF_PDFTK_BGCOLOR] ); // 15 PDF_PDFTK_BGCOLOR } m_cbTask->addItem( m_tasklist[PDF_PDFTK_STAMP] ); // 16 PDF_PDFTK_STAMP m_cbTask->addCategoryItem(""); m_cbTask->addItem( m_tasklist[PDF_PDFTK_FREE] ); // 17 PDF_PDFTK_FREE group = 3; } if (m_pdfpages && !m_encrypted) { if ( group < 3 ) { m_cbTask->addCategoryItem(""); } m_cbTask->addItem( m_tasklist[PDF_PDFPAGES_FREE] ); // 17 PDF_PDFPAGES_FREE } // choose one common task (need to calculate the combobox index) int index = m_cbTask->findText(lasttext); if ( lastindex==-1 || index==-1 ) { int lastTask = KileConfig::pdfWizardLastTask(); int task = ( lastTask < m_cbTask->count() ) ? lastTask : PDF_SELECT; index = m_cbTask->findText(m_tasklist[task]); if ( index == -1 ) { index = 0; } } m_cbTask->setCurrentIndex(index); slotTaskChanged(index); setFocusProxy(m_PdfDialog.m_edInfile); m_PdfDialog.m_edInfile->setFocus(); } QString PdfDialog::getOutfileName(const QString &infile) { return ( infile.isEmpty() ) ? QString() : infile.left(infile.length()-4) + "-out" + ".pdf"; } // calculate task index from comboxbox index int PdfDialog::taskIndex() { return m_tasklist.indexOf( m_cbTask->currentText() ); } void PdfDialog::setPermissions(bool print, bool other) { for (int i = 0; isetChecked(state); } } // read permissions QString PdfDialog::readPermissions() { QString permissions; for (int i = 0; i < m_pdfPermissionKeys.size(); ++i) { if ( m_pdfPermissionWidgets.at(i)->isChecked() ) { permissions += m_pdfPermissionPdftk.at(i) + " "; } } return permissions; } //-------------------- slots -------------------- void PdfDialog::slotTabwidgetChanged(int index) { m_rearrangeButton->setText(index == 0 ? i18n("Re&arrange") : i18n("&Update")); updateDialog(); } void PdfDialog::slotPrintingClicked() { if ( m_pdftk ) { setPermissions(true, false); } } void PdfDialog::slotAllClicked() { if ( m_pdftk ) { setPermissions(true, true); } } void PdfDialog::slotPermissionClicked(bool) { for (int i = 0; i < m_pdfPermissionKeys.size(); ++i) { QCheckBox *box = m_pdfPermissionWidgets.at(i); if ( box->isChecked() != m_pdfPermissionState[i] ) { box->setChecked( m_pdfPermissionState[i] ); } } } void PdfDialog::slotInputfileChanged(const QString &text) { clearDocumentInfo(); if ( QFile(text).exists() ) { m_PdfDialog.m_edOutfile->lineEdit()->setText( getOutfileName(text) ); pdfParser(text); } updateDialog(); } void PdfDialog::slotOverwriteChanged(int state) { bool checked = (state!=Qt::Checked); m_PdfDialog.m_lbOutfile->setEnabled(checked); m_PdfDialog.m_edOutfile->setEnabled(checked); updateDialog(); } void PdfDialog::slotOutputfileChanged(const QString &) { updateDialog(); } void PdfDialog::slotTaskChanged(int) { if ( m_PdfDialog.tabWidget->currentIndex() > 0 ) { return; } int taskindex = taskIndex(); if ( isParameterTask(taskindex) ) { QString s,labeltext; if ( taskindex==PDF_SELECT || taskindex==PDF_DELETE ) { labeltext = i18n("Pages:"); s = i18n("Comma separated page list: 1,4-7,9"); QRegExp re("((\\d+(-\\d+)?),)*\\d+(-\\d+)?"); m_PdfDialog.m_edParameter->setValidator(new QRegExpValidator(re, m_PdfDialog.m_edParameter)); } else if (taskindex==PDF_PDFTK_FREE) { labeltext = i18n("Parameter:"); s = i18n("All options for 'pdftk'"); m_PdfDialog.m_edParameter->setValidator(0); } else { //if (taskindex==PDF_PDFPAGES_FREE) { labeltext = i18n("Parameter:"); s = i18n("All options for 'pdfpages'"); m_PdfDialog.m_edParameter->setValidator(0); } m_PdfDialog.m_lbParamInfo->setText(" (" + s + ")"); m_PdfDialog.m_lbParameter->setText(labeltext); m_PdfDialog.m_lbParameter->show(); m_PdfDialog.m_edParameter->clear(); m_PdfDialog.m_edParameter->show(); m_PdfDialog.m_lbParamInfo->show(); } else { m_PdfDialog.m_lbParameter->hide(); m_PdfDialog.m_edParameter->hide(); m_PdfDialog.m_lbParamInfo->hide(); } if ( isOverlayTask(taskindex) ) { m_PdfDialog.m_lbStamp->show(); m_PdfDialog.m_edStamp->show(); if ( taskindex == PDF_PDFTK_BACKGROUND ) { m_PdfDialog.m_edStamp->setWhatsThis(i18n("Applies a PDF watermark to the background of a single input PDF. " "Pdftk uses only the first page from the background PDF and applies it to every page of the input PDF. " "This page is scaled and rotated as needed to fit the input page.") ); } else if ( taskindex == PDF_PDFTK_STAMP ) { m_PdfDialog.m_edStamp->setWhatsThis( i18n("Applies a foreground stamp on top of the input PDF document's pages. " "Pdftk uses only the first page from the stamp PDF and applies it to every page of the input PDF. " "This page is scaled and rotated as needed to fit the input page. " "This works best if the stamp PDF page has a transparent background.") ); } } else { m_PdfDialog.m_lbStamp->hide(); m_PdfDialog.m_edStamp->hide(); } if (isBackgroundColor(taskindex)) { m_PdfDialog.m_lbBackgroundColor->show(); m_PdfDialog.m_pbBackgroundColor->show(); } else { m_PdfDialog.m_lbBackgroundColor->hide(); m_PdfDialog.m_pbBackgroundColor->hide(); } if (isOverlayTask(taskindex) || isBackgroundColor(taskindex) || isFreeTask(taskindex)) { m_rearrangeButton->setText(i18n("&Apply")); } else { m_rearrangeButton->setText(i18n("Re&arrange")); } } // execute commands void PdfDialog::slotExecute() { int tabindex = m_PdfDialog.tabWidget->currentIndex(); switch (tabindex) { case 0: if (checkParameter()) { executeAction(); } break; case 1: if (checkProperties()) { executeProperties(); } break; case 2: if (checkPermissions()) { executePermissions(); } break; } } void PdfDialog::slotShowHelp() { QString message = i18n("
PDF-Wizard

" "This wizard uses 'pdftk' and the LaTeX package 'pdfpages' to" "
    " "
  • rearrange pages of an existing PDF document
  • " "
  • read and update documentinfo of a PDF document (only pdftk)
  • " "
  • read, set or change some permissions of a PDF document (only pdftk). " "A password is necessary to set or change this document settings. " "Additionally PDF encryption is done to lock the file's content behind this password.
  • " "
" "

The package 'pdfpages' will only work with non-encrypted documents. " "'pdftk' can handle both kind of documents, but a password is needed for encrypted files. " "If one of 'pdftk' or 'pdfpages' is not available, the possible rearrangements are reduced.

" "

Warning: Encryption and a password does not provide any real PDF security. The content " "is encrypted, but the key is known. You should see it more as a polite but firm request " "to respect the author's wishes.

"); #if !LIBPOPPLER_AVAILABLE message += i18n("

Information: This version of Kile was compiled without libpoppler library. " "Setting, changing and removing of properties and permissions is not possible.

"); #endif KMessageBox::information(this, message, i18n("PDF Tools")); } void PdfDialog::executeAction() { QString command = buildActionCommand(); if ( command.isEmpty() ) { return; } m_errorHandler->clearMessages(); QFileInfo from(m_inputfile); QFileInfo to(m_outputfile); // output for log window QString program = (m_execLatex) ? i18n("LaTeX with 'pdfpages' package") : i18n("pdftk"); QString msg = i18n("Rearranging PDF file: ") + from.fileName(); if (!to.fileName().isEmpty()) msg += " ---> " + to.fileName(); m_errorHandler->printMessage(KileTool::Info, msg, program); // some output logs m_output->clear(); QString s = QString("*****\n") + i18n("***** tool: ") + program + '\n' + i18n("***** input file: ") + from.fileName()+ '\n' + i18n("***** output file: ") + to.fileName()+ '\n' + i18n("***** param: ") + m_param + '\n' + i18n("***** command: ") + command + '\n' + i18n("***** viewer: ") + ((m_PdfDialog.m_cbView->isChecked()) ? i18n("yes") : i18n("no")) + '\n' + "*****\n"; emit( output(s) ); // run Process executeScript(command, m_tempdir->path(), PDF_SCRIPTMODE_ACTION); } void PdfDialog::executeProperties() { // create temporary file QTemporaryFile infotemp; //code was infotemp.setSuffix(".txt"); //Add to constructor and adapt if necessay: QDir::tempPath() + QLatin1String("/myapp_XXXXXX") + QLatin1String(".txt") infotemp.setAutoRemove(false); if(!infotemp.open()) { KILE_DEBUG_MAIN << "Could not create tempfile for key/value pairs in QString PdfDialog::executeProperties()" ; return; } QString infofile = infotemp.fileName(); // create a text file with key/value pairs for pdftk QTextStream infostream(&infotemp); for (QStringList::const_iterator it = m_pdfInfoKeys.constBegin(); it != m_pdfInfoKeys.constEnd(); ++it) { infostream << "InfoKey: " << (*it) << "\n"; infostream << "InfoValue: " << m_pdfInfoWidget[*it]->text().trimmed() << "\n"; } // add modification Date QString datetime = QDateTime::currentDateTimeUtc().toString("%Y%m%d%H%M%S%:z"); datetime = datetime.replace(":","'"); infostream << "InfoKey: " << "ModDate" << "\n"; infostream << "InfoValue: " << "D:" << datetime << "'\n"; infotemp.close(); // build command QString inputfile = m_PdfDialog.m_edInfile->lineEdit()->text().trimmed(); QString password = m_PdfDialog.m_edPassword->text().trimmed(); QString pdffile = m_tempdir->path() + QFileInfo(m_inputfile).baseName() + "-props.pdf"; // read permissions QString permissions = readPermissions(); // build param QString param = "\"" + inputfile + "\""; if ( m_encrypted ) { param += " input_pw " + password; } param += " update_info " + infofile + " output \"" + pdffile+ "\""; if ( m_encrypted ) { param += " encrypt_128bit"; if ( !permissions.isEmpty() ) param += " allow " + permissions; param += " owner_pw " + password; } QString command = "pdftk " + param; // move destination file m_move_filelist.clear(); m_move_filelist << pdffile << inputfile; // execute script showLogs("Updating properties", inputfile, param); executeScript(command, QString(), PDF_SCRIPTMODE_PROPERTIES); } void PdfDialog::executePermissions() { // read permissions QString permissions = readPermissions(); // build command QString inputfile = m_PdfDialog.m_edInfile->lineEdit()->text().trimmed(); QString password = m_PdfDialog.m_edPassword->text().trimmed(); QString pdffile = m_tempdir->path() + QFileInfo(m_inputfile).baseName() + "-perms.pdf"; QString param = "\"" + inputfile + "\""; if ( m_encrypted ) { param += " input_pw " + password; } param += " output \"" + pdffile + "\" encrypt_128bit"; if ( !permissions.isEmpty() ) { param += " allow " + permissions; } param += " owner_pw " + password; QString command = "pdftk " + param; // move destination file m_move_filelist.clear(); m_move_filelist << pdffile << inputfile; // execute script showLogs("Updating permissions", inputfile, param); executeScript(command, QString(), PDF_SCRIPTMODE_PERMISSIONS); } void PdfDialog::showLogs(const QString &title, const QString &inputfile, const QString ¶m) { // some info for log widget m_errorHandler->clearMessages(); m_errorHandler->printMessage(KileTool::Info, title, "pdftk" ); // some info for output widget QFileInfo input(inputfile); m_output->clear(); QString s = QString("*****\n") + i18n("***** tool: ") + "pdftk" + '\n' + i18n("***** input file: ") + input.fileName()+ '\n' + i18n("***** param: ") + param + '\n' + "*****\n"; emit( output(s) ); } void PdfDialog::executeScript(const QString &command, const QString &dir, int scriptmode) { // delete old KProcess if (m_proc) { delete m_proc; } m_scriptmode = scriptmode; m_outputtext = ""; m_proc = new KProcess(); if (!dir.isEmpty()) { m_proc->setWorkingDirectory(dir); } m_proc->setShellCommand(command); m_proc->setOutputChannelMode(KProcess::MergedChannels); m_proc->setReadChannel(QProcess::StandardOutput); connect(m_proc, SIGNAL(readyReadStandardOutput()), this, SLOT(slotProcessOutput())); connect(m_proc, SIGNAL(readyReadStandardError()), this, SLOT(slotProcessOutput())); connect(m_proc, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(slotProcessExited(int, QProcess::ExitStatus))); KILE_DEBUG_MAIN << "=== PdfDialog::runPdfutils() ===================="; KILE_DEBUG_MAIN << "execute '" << command << "'"; m_scriptrunning = true; m_rearrangeButton->setEnabled(false); m_buttonBox->button(QDialogButtonBox::Close)->setEnabled(false); m_proc->start(); } void PdfDialog::slotProcessOutput() { m_outputtext += m_proc->readAll(); } void PdfDialog::slotProcessExited(int exitCode, QProcess::ExitStatus exitStatus) { if ( exitStatus != QProcess::NormalExit) { if (m_scriptmode != PDF_SCRIPTMODE_TOOLS) showError(i18n("An error occurred while executing the task.")); } else { bool state = ( exitCode == 0 ); if ( m_scriptmode == PDF_SCRIPTMODE_TOOLS ) { initUtilities(); } #if !LIBPOPPLER_AVAILABLE else if ( m_scriptmode==PDF_SCRIPTMODE_NUMPAGES_PDFTK || m_scriptmode==PDF_SCRIPTMODE_NUMPAGES_IMAGEMAGICK || m_scriptmode==PDF_SCRIPTMODE_NUMPAGES_GHOSTSCRIPT ) { readNumberOfPages(m_scriptmode,m_outputtext); } #endif else { finishPdfAction(state); } } m_scriptrunning = false; m_buttonBox->button(QDialogButtonBox::Close)->setEnabled(true); updateDialog(); } void PdfDialog::finishPdfAction(bool state) { // output window emit( output(m_outputtext) ); // log window QString program = (m_scriptmode==PDF_SCRIPTMODE_ACTION && m_execLatex) ? "LaTeX with 'pdfpages' package" : "pdftk"; if ( state ) { m_errorHandler->printMessage(KileTool::Info, "finished", program); // should we move the temporary pdf file if ( ! m_move_filelist.isEmpty() ) { QFile::remove( m_move_filelist[1] ); QFile::rename( m_move_filelist[0], m_move_filelist[1] ); KILE_DEBUG_MAIN << "move file: " << m_move_filelist[0] << " ---> " << m_move_filelist[1]; } // run viewer if ( m_PdfDialog.m_cbView->isChecked() && m_scriptmode==PDF_SCRIPTMODE_ACTION ) { runViewer(); } - // file properties/permissions could be changed changed + // file properties/permissions could be changed if ( (m_scriptmode==PDF_SCRIPTMODE_ACTION && m_PdfDialog.m_cbOverwrite->isChecked()) || m_scriptmode==PDF_SCRIPTMODE_PROPERTIES || m_scriptmode==PDF_SCRIPTMODE_PERMISSIONS ) { slotInputfileChanged( m_PdfDialog.m_edInfile->lineEdit()->text().trimmed() ); } } else { QString msg; if (m_outputtext.indexOf("OWNER PASSWORD") >= 0 ) { msg = i18n("Finished with an error (wrong password)"); } else { msg = i18n("Finished with an error"); } m_errorHandler->printMessage(KileTool::Error, msg, program); } } void PdfDialog::runViewer() { m_errorHandler->printMessage(KileTool::Info, "Running viewer", "ViewPDF"); // call ViewPDF QString cfg = KileTool::configName("ViewPDF", m_manager->config()); KileTool::View *tool = dynamic_cast(m_manager->createTool("ViewPDF", cfg, false)); if(!tool) { m_errorHandler->printMessage(KileTool::Error, i18n("Could not create the ViewPDF tool"), i18n("ViewPDF")); return; } tool->setFlags(0); tool->setSource(m_outputfile); m_manager->run(tool); } QString PdfDialog::buildActionCommand() { // build action: parameter m_execLatex = true; // default m_inputfile = m_PdfDialog.m_edInfile->lineEdit()->text().trimmed(); m_outputfile = m_PdfDialog.m_edOutfile->lineEdit()->text().trimmed(); QColor bgcolor; QString bgfile; int taskindex = taskIndex(); switch (taskindex) { case PDF_PAGE_EMPTY: m_param = "nup=1x2,landscape,pages=" + buildPageRange(PDF_PAGE_EMPTY); break; case PDF_PAGE_DUPLICATE: m_param = "nup=1x2,landscape,pages=" + buildPageRange(PDF_PAGE_DUPLICATE); break; case PDF_2UP: m_param = "nup=1x2,landscape,pages=1-"; break; case PDF_2UP_LANDSCAPE: m_param = "nup=1x2,pages=1-"; break; case PDF_4UP: m_param = "nup=2x2,pages=1-"; break; case PDF_4UP_LANDSCAPE: m_param = "nup=2x2,landscape,pages=1-"; break; case PDF_EVEN: if ( m_pdftk ) { m_param = "cat 1-endeven"; m_execLatex = false; } else { m_param = buildPageList(true); } break; case PDF_ODD: if ( m_pdftk ) { m_param = "cat 1-endodd"; m_execLatex = false; } else { m_param = buildPageList(false); } break; case PDF_EVEN_REV: if ( m_pdftk ) { m_param = "cat end-1even"; m_execLatex = false; } else { m_param = buildReversPageList(true); } break; case PDF_ODD_REV: if ( m_pdftk ) { m_param = "cat end-1odd"; m_execLatex = false; } else { m_param = buildReversPageList(false); } break; case PDF_REVERSE: if ( m_pdftk ) { m_param = "cat end-1"; m_execLatex = false; } else { m_param = "last-1"; } break; case PDF_DECRYPT: m_param.clear(); m_execLatex = false; break; case PDF_SELECT: case PDF_DELETE: m_param = ( taskindex == PDF_SELECT ) ? buildSelectPageList() : buildDeletePageList(); if ( m_pdftk ) { m_param = "cat " + m_param.replace(","," "); m_execLatex = false; } else { m_param = "pages={" + m_param + "}"; } break; case PDF_PDFTK_BACKGROUND: m_param = "background \"" + m_PdfDialog.m_edStamp->text().trimmed() + "\""; m_execLatex = false; break; case PDF_PDFTK_BGCOLOR: bgcolor = m_PdfDialog.m_pbBackgroundColor->color(); bgfile = buildPdfBackgroundFile(&bgcolor); m_param = "background " + bgfile; m_execLatex = false; break; case PDF_PDFTK_STAMP: m_param = "stamp \"" + m_PdfDialog.m_edStamp->text().trimmed() + "\""; m_execLatex = false; break; case PDF_PDFTK_FREE: m_param = m_PdfDialog.m_edParameter->text().trimmed(); m_execLatex = false; break; case PDF_PDFPAGES_FREE: m_param = m_PdfDialog.m_edParameter->text().trimmed(); break; } // build action: command QString command,latexfile,pdffile; if ( m_execLatex ) { latexfile = buildLatexFile(m_param); pdffile = latexfile + ".pdf"; command = "pdflatex " + latexfile + ".tex"; } else { pdffile = m_tempdir->path() + QFileInfo(m_inputfile).baseName() + "-temp.pdf"; command = "pdftk \"" + m_inputfile + "\""; if ( m_encrypted ) { QString password = m_PdfDialog.m_edPassword->text().trimmed(); command += " input_pw " + password; } command += " " + m_param + " output \"" + pdffile+ "\""; } // additional actions bool viewer = m_PdfDialog.m_cbView->isChecked(); bool equalfiles = (m_PdfDialog.m_cbOverwrite->isChecked() || m_inputfile==m_outputfile); if (equalfiles) { m_outputfile = m_inputfile; } // move destination file m_move_filelist.clear(); if ( equalfiles ) { m_move_filelist << pdffile << m_inputfile; } else if ( !m_outputfile.isEmpty() ) { m_move_filelist << pdffile << m_outputfile; } // viewer if ( viewer && m_outputfile.isEmpty() ) { m_outputfile = pdffile; } return command; } // create a temporary file to run latex with package pdfpages.sty QString PdfDialog::buildLatexFile(const QString ¶m) { QTemporaryFile temp; //code was temp.setPrefix(m_tempdir->path()); //Add to constructor and adapt if necessay: m_tempdir->path()QLatin1String("/myapp_XXXXXX.txt") //code was temp.setSuffix(".tex"); //Add to constructor and adapt if necessay: QDir::tempPath() + QLatin1String("/myapp_XXXXXX") + QLatin1String(".tex") temp.setAutoRemove(false); if(!temp.open()) { KILE_DEBUG_MAIN << "Could not create tempfile in PdfDialog::buildLatexFile()" ; return QString(); } QString tempname = temp.fileName(); QTextStream stream(&temp); stream << "\\documentclass[a4paper,12pt]{article}"; stream << "\\usepackage[final]{pdfpages}"; stream << "\\begin{document}"; stream << "\\includepdf[" << param << "]{" << m_inputfile << "}"; stream << "\\end{document}"; // everything is prepared to do the job temp.close(); return(tempname.left(tempname.length() - 4)); } // create a temporary pdf file to set a background color QString PdfDialog::buildPdfBackgroundFile(QColor *color) { QTemporaryFile temp; //code was temp.setPrefix(m_tempdir->path()); //Add to constructor and adapt if necessay: m_tempdir->path()QLatin1String("/myapp_XXXXXX.txt") //code was temp.setSuffix(".pdf"); //Add to constructor and adapt if necessay: QDir::tempPath() + QLatin1String("/myapp_XXXXXX") + QLatin1String(".pdf") temp.setAutoRemove(false); if(!temp.open()) { KILE_DEBUG_MAIN << "Could not create tempfile in PdfDialog::buildPdfBackgroundFile()" ; return QString(); } QString tempname = temp.fileName(); QTextStream stream(&temp); stream << "%PDF-1.4\n"; stream << '%' << '\0' << '\0' << '\0' << '\0' << '\r'; stream << "5 0 obj \n" "<<\n" "/Type /ExtGState\n" "/OPM 1\n" ">>\n" "endobj \n" "4 0 obj \n" "<<\n" "/R7 5 0 R\n" ">>\n" "endobj \n" "6 0 obj \n" "<<\n" "/Length 83\n" ">>\n" "stream\n" "q 0.1 0 0 0.1 0 0 cm\n" "/R7 gs\n"; stream << color->redF() << " " << color->greenF() << " " << color->blueF() << " rg\n"; stream << "0 0 " << 10*m_pagesize.width() << " " << 10*m_pagesize.height() << " re\n"; stream << "f\n" "0 g\n" "Q\n" "\n" "endstream \n" "endobj \n" "3 0 obj \n" "<<\n" "/Parent 1 0 R\n"; stream << "/MediaBox [0 0 " << m_pagesize.width() << " " << m_pagesize.height() << "]\n"; stream << "/Resources \n" "<<\n" "/ExtGState 4 0 R\n" "/ProcSet [/PDF]\n" ">>\n" "/pdftk_PageNum 1\n" "/Type /Page\n" "/Contents 6 0 R\n" ">>\n" "endobj \n" "1 0 obj \n" "<<\n" "/Kids [3 0 R]\n" "/Count 1\n" "/Type /Pages\n" ">>\n" "endobj \n" "7 0 obj \n" "<<\n" "/Pages 1 0 R\n" "/Type /Catalog\n" ">>\n" "endobj \n" "8 0 obj \n" "<<\n" "/Creator ()\n" "/Producer ())\n" "/ModDate ()\n" "/CreationDate ()\n" ">>\n" "endobj xref\n" "0 9\n" "0000000000 65535 f \n" "0000000388 00000 n \n" "0000000000 65536 n \n" "0000000231 00000 n \n" "0000000062 00000 n \n" "0000000015 00000 n \n" "0000000095 00000 n \n" "0000000447 00000 n \n" "0000000498 00000 n \n" "trailer\n" "\n" "<<\n" "/Info 8 0 R\n" "/Root 7 0 R\n" "/Size 9\n" "/ID [<4a7c31ef3aeb884b18f59c2037a752f5><54079f85d95a11f3400fe5fc3cfc832b>]\n" ">>\n" "startxref\n" "721\n" "%%EOF\n"; // everything is prepared to do the job temp.close(); return tempname; } QString PdfDialog::buildPageRange(int type) { QString s; for (int i = 1; i <= m_numpages; ++i) { if (type == PDF_PAGE_EMPTY) { s += QString("%1,{},").arg(i); } else { s += QString("%1,%2,").arg(i).arg(i); } } return "{" + s.left(s.length()-1) + "}"; } QString PdfDialog::buildPageList(bool even) { QString s, number; int start = ( even ) ? 2 : 1; for (int i=start; i<=m_numpages; i+=2 ) { s += number.setNum(i) + ","; } if ( !s.isEmpty() ) { s.truncate(s.length()-1); } return "{" + s + "}"; } QString PdfDialog::buildReversPageList(bool even) { QString s,number; int last = m_numpages; if ( even ) { if ( (last & 1) == 1 ) { last--; } } else { if ( (last & 1) == 0 ) { last--; } } for (int i=last; i>=1; i-=2 ) { s += number.setNum(i) + ","; } if ( !s.isEmpty() ) { s.truncate(s.length()-1); } return "{" + s + "}"; } QString PdfDialog::buildSelectPageList() { return m_PdfDialog.m_edParameter->text().trimmed(); } QString PdfDialog::buildDeletePageList() { // m_numpages is known QString param = m_PdfDialog.m_edParameter->text().trimmed(); QRegExp re("(\\d+)-(\\d+)"); // analyze delete list bool ok; QBitArray arr(m_numpages + 1,false); QStringList pagelist = param.split(','); foreach (const QString &s, pagelist) { if ( s.contains('-') && re.indexIn(s) >= 0 ) { int from = re.cap(1).toInt(&ok); int to = re.cap(2).toInt(&ok); for (int i=from; i<=to; ++i) { arr.setBit(i); } } else { arr.setBit(s.toInt(&ok)); } } // build select list QString result; int page = 1; while ( page <= m_numpages ) { int from = searchPages(&arr,page,m_numpages,true); if ( from > m_numpages ) { break; } int to = searchPages(&arr,from+1,m_numpages,false) - 1; if ( !result.isEmpty() ) { result += ","; } if ( from < to ) { result += QString::number(from) + "-" + QString::number(to); } else { result += QString::number(from); } page = to + 1; } return result; } int PdfDialog::searchPages(QBitArray *arr, int page, int lastpage, bool value) { while ( page <= lastpage ) { if ( arr->at(page) != value ) { return page; } page++; } return lastpage + 1; } bool PdfDialog::checkParameter() { if ( !checkInputFile() ) { return false; } if ( m_encrypted ) { if ( !checkPassword() ) { return false; } } // check parameter int taskindex = taskIndex(); if ( isParameterTask(taskindex) && m_PdfDialog.m_edParameter->text().trimmed().isEmpty() ) { showError( i18n("The utility needs some parameters in this mode.") ); return false; } // check select/delete page list (m_numpages is known) if ( taskindex==PDF_SELECT || taskindex==PDF_DELETE ) { // m_numpages is known QString param = m_PdfDialog.m_edParameter->text().trimmed(); QRegExp re("(\\d+)-(\\d+)"); // analyze page list bool ok; QStringList pagelist = param.split(','); foreach (const QString &s, pagelist) { if ( s.contains('-') && re.indexIn(s)>=0 ) { int from = re.cap(1).toInt(&ok); int to = re.cap(2).toInt(&ok); if ( from > to ) { showError(i18n("Illegal page list 'from-to': %1 is bigger than %2.",from,to)); return false; } if ( to > m_numpages ) { showError(i18n("Illegal pagenumber: %1.",to)); return false; } } else { int page = s.toInt(&ok); if ( page > m_numpages ) { showError(i18n("Illegal pagenumber: %1.",page)); return false; } } } } // check background/stamp parameter if ( isOverlayTask(taskindex) ) { QString filename = m_PdfDialog.m_edStamp->text().trimmed(); if ( filename.isEmpty() ) { QString message = ( taskindex == PDF_PDFTK_STAMP ) ? i18n("You need to define a PDF file as foreground stamp.") : i18n("You need to define a PDF file as background watermark."); showError(message); return false; } QFileInfo fs(filename); if (fs.completeSuffix() != "pdf") { showError(i18n("Unknown file format: only '.pdf' is accepted as image file in this mode.")); return false; } if ( !QFile::exists(filename) ) { showError(i18n("The given file doesn't exist.")); return false; } } // overwrite mode: no output file is needed if ( m_PdfDialog.m_cbOverwrite->isChecked() ) { return true; } // create a different output file QString outfile = m_PdfDialog.m_edOutfile->lineEdit()->text().trimmed(); if ( outfile.isEmpty() ) { showError(i18n("You need to define an output file.")); return false; } // outfile file must have extension pdf QFileInfo fo(outfile); if (fo.completeSuffix() != "pdf") { showError(i18n("Unknown file format: only '.pdf' is accepted as output file.")); return false; } // check, if this output file already exists if ( fo.exists() ) { QString s = i18n("A file named \"%1\" already exists. Are you sure you want to overwrite it?", fo.fileName()); if (KMessageBox::questionYesNo(this, "
" + s + "
", i18n("PDF Tools")) == KMessageBox::No) { return false; } } return true; } bool PdfDialog::checkProperties() { if ( !checkInputFile() ) { return false; } return ( m_encrypted ) ? checkPassword() : true; } bool PdfDialog::checkPermissions() { if ( !checkInputFile() ) { return false; } return checkPassword(); } bool PdfDialog::checkInputFile() { QString infile = m_PdfDialog.m_edInfile->lineEdit()->text().trimmed(); if (infile.isEmpty()) { showError(i18n("No input file is given.")); return false; } QFileInfo fi(infile); QString suffix = fi.completeSuffix(); if (suffix != "pdf") { showError(i18n("Unknown file format: only '.pdf' are accepted for input files.")); return false; } if (!fi.exists()) { showError(i18n("This input file does not exist.")); return false; } return true; } bool PdfDialog::checkPassword() { // check password QString password = m_PdfDialog.m_edPassword->text().trimmed(); if (password.isEmpty()) { showError(i18n("No password is given.")); return false; } if (password.length() < 6) { showError(i18n("The password should be at least 6 characters long.")); return false; } return true; } void PdfDialog::showError(const QString &text) { KMessageBox::error(this, i18n("
") + text + i18n("
"), i18n("PDF Tools")); } // check tasks bool PdfDialog::isParameterTask(int task) { return ( task==PDF_SELECT || task==PDF_DELETE || task==PDF_PDFPAGES_FREE || task==PDF_PDFTK_FREE ); } bool PdfDialog::isOverlayTask(int task) { return ( task==PDF_PDFTK_BACKGROUND || task==PDF_PDFTK_STAMP ); } bool PdfDialog::isBackgroundColor(int task) { return ( task == PDF_PDFTK_BGCOLOR ) ? true : false; } bool PdfDialog::isFreeTask(int task) { return ( task==PDF_PDFPAGES_FREE || task==PDF_PDFTK_FREE ); } } diff --git a/src/editorextension.cpp b/src/editorextension.cpp index d4f7789d..27130aba 100644 --- a/src/editorextension.cpp +++ b/src/editorextension.cpp @@ -1,3389 +1,3389 @@ /*********************************************************************************************** Copyright (C) 2004-2012 by Holger Danielsson (holger.danielsson@versanet.de) 2008-2013 by Michel Ludwig (michel.ludwig@kdemail.net) ***********************************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "editorextension.h" #include #include #include #include #include #include #include #include #include #include "errorhandler.h" #include "codecompletion.h" #include "kile.h" #include "kileactions.h" #include "kileconfig.h" #include "kileextensions.h" #include "kileinfo.h" #include "kiletool_enums.h" #include "kileviewmanager.h" #include "quickpreview.h" #include "widgets/konsolewidget.h" /* * FIXME: The code in this file should be reworked completely. Once we've got a better parser * most of the code in here should also be superfluous. */ namespace KileDocument { EditorExtension::EditorExtension(KileInfo *info) : m_ki(info) { m_latexCommands = m_ki->latexCommands(); // init regexp m_reg.setPattern("(\\\\(begin|end)\\s*\\{([A-Za-z]+\\*?)\\})|(\\\\\\[|\\\\\\])"); // 1 2 3 4 m_regexpEnter.setPattern("^(.*)((\\\\begin\\s*\\{([^\\{\\}]*)\\})|(\\\\\\[))"); // 1 23 4 5 // init double quotes m_quoteListI18N // this is shown in the configuration dialog << i18n("English quotes: `` ''") << i18n("French quotes: "< ">") << i18n("German quotes: "` "'") << i18n("French quotes (long): \\flqq \\frqq") << i18n("German quotes (long): \\glqq \\grqq") << i18n("Icelandic quotes (v1): \\ilqq \\irqq") << i18n("Icelandic quotes (v2): \\iflqq \\ifrqq") << i18n("Czech quotes: \\uv{}") << i18n("csquotes package: \\enquote{}"); m_quoteList << QPair("``", "''") << QPair("\"<", "\">") << QPair("\"`", "\"'") << QPair("\\flqq", "\\frqq") << QPair("\\glqq", "\\grqq") << QPair("\\ilqq", "\\irqq") << QPair("\\iflqq", "\\ifrqq") << QPair("\\uv{", "}") << QPair("\\enquote{", "}"); readConfig(); } EditorExtension::~EditorExtension() { } //////////////////// read configuration //////////////////// void EditorExtension::readConfig(void) { // init insertion of double quotes initDoubleQuotes(); // allow special chars? m_specialCharacters = KileConfig::insertSpecialCharacters(); // calculate indent for autoindent of environments m_envAutoIndent.clear(); if(KileConfig::envIndentation()) { if(KileConfig::envIndentSpaces()) { int num = KileConfig::envIndentNumSpaces(); if(num < 1 || num > 9) { num = 1; } m_envAutoIndent.fill(' ', num); } else { m_envAutoIndent = "\t"; } } } void EditorExtension::insertTag(const KileAction::TagData& data, KTextEditor::View *view) { KTextEditor::Document *doc = view->document(); if(!doc) { return; } //whether or not to wrap tag around selection bool wrap = !data.tagEnd.isNull() && view->selection(); //%C before or after the selection bool before = data.tagBegin.count("%C"); bool after = data.tagEnd.count("%C"); //save current cursor position KTextEditor::Cursor cursor = view->cursorPosition(); int para = cursor.line(); int para_begin = para; int index = cursor.column(); int index_begin = index; int para_end = 0; int index_cursor = index; int para_cursor = index; // offset for autoindentation of environments int dxIndentEnv = 0; // environment tag bool envtag = data.tagBegin.count("%E") || data.tagEnd.count("%E"); QString whitespace = getWhiteSpace( doc->line(para).left(index) ); //if there is a selection act as if cursor is at the beginning of selection if (wrap) { KTextEditor::Range selectionRange = view->selectionRange(); index = selectionRange.start().column(); para = selectionRange.start().line(); para_end = selectionRange.end().line(); } QString ins = data.tagBegin; QString tagEnd = data.tagEnd; //start an atomic editing sequence KTextEditor::Document::EditingTransaction transaction(doc); //cut the selected text QString trailing; if(wrap) { QString sel = view->selectionText(); view->removeSelectionText(); // no autoindentation of environments, when text is selected if(envtag) { ins.remove("%E"); tagEnd.remove("%E\n"); } // strip one of two consecutive line ends int len = sel.length(); if(tagEnd.at(0)=='\n' && len > 0 && sel.indexOf('\n',-1) == len - 1) { sel.truncate( len-1 ); } // now add the selection ins += sel; // place the cursor behind this tag, if there is no other wish if(!before && !after) { trailing = "%C"; after = true; } } else if(envtag) { ins.replace("%E",whitespace+m_envAutoIndent); tagEnd.replace("%E",whitespace+m_envAutoIndent); if(data.dy > 0) { dxIndentEnv = whitespace.length() + m_envAutoIndent.length(); } } tagEnd.replace("\\end{",whitespace+"\\end{"); ins += tagEnd + trailing; //do some replacements QFileInfo fi( doc->url().toLocalFile()); ins.replace("%S", fi.completeBaseName()); ins.replace("%B", s_bullet); //insert first part of tag at cursor position doc->insertText(KTextEditor::Cursor(para, index), ins); //move cursor to the new position if(before || after) { int n = data.tagBegin.count("\n")+ data.tagEnd.count("\n"); if(wrap) { n += para_end > para ? para_end-para : para-para_end; } for (int line = para_begin; line <= para_begin+n; ++line) { if(doc->line(line).count("%C")) { int i=doc->line(line).indexOf("%C"); para_cursor = line; index_cursor = i; doc->removeText(KTextEditor::Range(line, i, line, i+2)); break; } index_cursor=index; para_cursor=line; } } else { int py = para_begin, px = index_begin; if(wrap) { //act as if cursor was at beginning of selected text (which is the point where the tagBegin is inserted) py = para; px = index; } para_cursor = py+data.dy; index_cursor = px+data.dx+dxIndentEnv; } //end the atomic editing sequence transaction.finish(); //set the cursor position (it is important that this is done outside of the atomic editing sequence) view->setCursorPosition(KTextEditor::Cursor(para_cursor, index_cursor)); view->removeSelection(); } //////////////////// goto environment tag (begin or end) //////////////////// // goto the next non-nested environment tag KTextEditor::View* EditorExtension::determineView(KTextEditor::View *view) { if (!view) { view = m_ki->viewManager()->currentTextView(); } m_overwritemode = (!view) ? false : (view->viewMode() == KTextEditor::View::NormalModeOverwrite); return view; } void EditorExtension::gotoEnvironment(bool backwards, KTextEditor::View *view) { view = determineView(view); if(!view) { return; } uint row,col; EnvData env; bool found; // get current position KTextEditor::Document *doc = view->document(); KTextEditor::Cursor cursor = view->cursorPosition(); row = cursor.line(); col = cursor.column(); // start searching if(backwards) { found = findBeginEnvironment(doc,row,col,env); //KILE_DEBUG_MAIN << " goto begin env: " << env.row << "/" << env.col; } else { found = findEndEnvironment(doc,row,col,env); env.col += env.len; } if(found) { view->setCursorPosition(KTextEditor::Cursor(env.row, env.col)); } } // match the opposite environment tag void EditorExtension::matchEnvironment(KTextEditor::View *view) { view = determineView(view); if(!view) { return; } uint row,col; EnvData env; // get current position KTextEditor::Document *doc = view->document(); KTextEditor::Cursor cursor = view->cursorPosition(); row = cursor.line(); col = cursor.column(); // we only start, when we are at an environment tag if(!isEnvironmentPosition(doc, row, col, env)) { return; } gotoEnvironment(env.tag != EnvBegin, view); } //////////////////// close opened environments //////////////////// // search for the last opened environment and close it void EditorExtension::closeEnvironment(KTextEditor::View *view) { view = determineView(view); if(!view) { return; } int row, col, currentRow, currentCol; QString name; KTextEditor::Cursor cursor = view->cursorPosition(); currentRow = cursor.line(); currentCol = cursor.column(); if(findOpenedEnvironment(row, col, name, view)) { if(name == "\\[") { view->document()->insertText(KTextEditor::Cursor(currentRow, currentCol), "\\]"); } else { view->document()->insertText(KTextEditor::Cursor(currentRow, currentCol), "\\end{" + name + '}'); } // view->setCursorPosition(KTextEditor::Cursor(row + 1, 0)); } } // close all opened environments void EditorExtension::closeAllEnvironments(KTextEditor::View *view) { view = determineView(view); if(!view) { return; } QStringList envlist = findOpenedEnvironmentList(view, true); if(envlist.count() == 0) { return; } int currentRow, currentCol, outputCol; KTextEditor::Document *doc = view->document(); KTextEditor::Cursor cursor = view->cursorPosition(); currentRow = cursor.line(); currentCol = cursor.column(); bool indent = !m_envAutoIndent.isEmpty(); if(indent && currentCol > 0) { doc->insertText(KTextEditor::Cursor(currentRow, currentCol),"\n"); currentRow++; currentCol = 0; } bool ok1,ok2; for(QStringList::Iterator it = envlist.begin(); it != envlist.end(); ++it) { QStringList entry = (*it).split(','); if(entry[0] == "document") { break; } int row = entry[1].toInt(&ok1); int col = entry[2].toInt(&ok2); if(!ok1 || !ok2) { continue; } outputCol = currentCol; if(indent) { QString whitespace = getWhiteSpace( doc->line(row).left(col) ); doc->insertText(KTextEditor::Cursor(currentRow, outputCol), whitespace); outputCol += whitespace.length(); } QString endtag = ( entry[0] == "\\[" ) ? "\\]\n" : "\\end{"+entry[0]+"}\n"; doc->insertText(KTextEditor::Cursor(currentRow, outputCol), endtag); ++currentRow; } } //////////////////// mathgroup //////////////////// void EditorExtension::selectMathgroup(KTextEditor::View *view) { view = determineView(view); if(!view) { return; } KTextEditor::Range range = mathgroupRange(view); if(range.isValid()) { view->setSelection(range); } } void EditorExtension::deleteMathgroup(KTextEditor::View *view) { view = determineView(view); if(!view) { return; } KTextEditor::Range range = mathgroupRange(view); if(range.isValid()) { deleteRange(range,view); } } bool EditorExtension::hasMathgroup(KTextEditor::View *view) { // view will be checked in mathgroupRange() KTextEditor::Range range = mathgroupRange(view); return (range.isValid()) ? true : false; } QString EditorExtension::getMathgroupText(KTextEditor::View *view) { view = determineView(view); if(!view) { return QString(); } KTextEditor::Range range = mathgroupRange(view); return (range.isValid()) ? view->document()->text(range) : QString(); } QString EditorExtension::getMathgroupText(uint &row, uint &col, KTextEditor::View *view) { int row1, col1, row2, col2; view = determineView(view); if(view && getMathgroup(view, row1, col1, row2, col2)) { row = row1; col = col1; return view->document()->text(KTextEditor::Range(row1, col1, row2, col2)); } else { return QString(); } } KTextEditor::Range EditorExtension::mathgroupRange(KTextEditor::View *view) { view = determineView(view); if(!view) { return KTextEditor::Range::invalid(); } int row1, col1, row2, col2; if(getMathgroup(view, row1, col1, row2, col2)) { return KTextEditor::Range(row1, col1, row2, col2); } else { return KTextEditor::Range::invalid(); } } bool EditorExtension::getMathgroup(KTextEditor::View *view, int &row1, int &col1, int &row2, int &col2) { int row, col, r, c; MathData begin, end; KTextEditor::Document *doc = view->document(); KTextEditor::Cursor cursor = view->cursorPosition(); row = cursor.line(); col = cursor.column(); QString textline = getTextLineReal(doc,row); // check for '\ensuremath{...}' QString word; int x1, x2; if(getCurrentWord(doc, row, col, smTex, word, x1, x2) && word == "\\ensuremath") { view->setCursorPosition(KTextEditor::Cursor(row, x2)); } BracketData open,close; if(getTexgroup(false, open, close, view)) { QString s = getTextLineReal(doc,open.row); if(open.col >= 11 && s.mid(open.col - 11, 11) == "\\ensuremath") { view->setCursorPosition(KTextEditor::Cursor(row, col)); row1 = open.row; col1 = open.col-11; row2 = close.row; col2 = close.col; return true; } } // do we need to restore the cursor position view->setCursorPosition(KTextEditor::Cursor(row, col)); // '$' is difficult, because it is used as opening and closing tag int mode = 0; if(textline[col] == '$') { mode = 1; } else if(col > 0 && textline[col - 1] == '$') { mode = 2; } if(mode > 0) { // first look, if this is a closing '$' r = row; c = (mode == 1) ? col : col - 1; if(decreaseCursorPosition(doc, r, c) && findOpenMathTag(doc, r, c, begin)) { if(begin.tag == mmMathDollar && (begin.numdollar & 1)) { row1 = begin.row; col1 = begin.col; row2 = row; col2 = (mode == 1) ? col + 1 : col; return true; } } // perhaps an opening '$' r = row; c = (mode == 1) ? col+1 : col; if(findCloseMathTag(doc, r, c, end)) { if(end.tag == mmMathDollar) { row1 = row; col1 = ( mode == 1 ) ? col : col-1; row2 = end.row; col2 = end.col + end.len; return true; } } // found no mathgroup with '$' return false; } // now let's search for all other math tags: // if a mathgroup tag starts in the current column, we save this // position and move the cursor one column to the right bool openingtag = isOpeningMathTagPosition(doc, row, col, begin); if(openingtag) { // try to find the corresponding closing tag at the right bool closetag = findCloseMathTag(doc, row, col + 1, end); if(closetag && checkMathtags(begin, end)) { row1 = begin.row; col1 = begin.col; row2 = end.row; col2 = end.col + end.len; return true; } } r = row; c = col; bool closingtag = isClosingMathTagPosition(doc, row, col, end); if(closingtag) { c = end.col; if(!decreaseCursorPosition(doc, r, c)) { return false; } } // now try to search to opening tag of the math group if(!findOpenMathTag(doc, r, c, begin)) { return false; } if(begin.tag == mmMathDollar && !(begin.numdollar & 1)) { //KILE_DEBUG_MAIN << "error: even number of '$' --> no math mode" ; return false; } // and now the closing tag if(!findCloseMathTag(doc, r, c, end)) { return false; } // both tags were found, but they must be of the same type if(checkMathtags(begin, end)) { row1 = begin.row; col1 = begin.col; row2 = end.row; col2 = end.col + end.len; return true; } else { return false; } } //////////////////// mathgroup tags //////////////////// bool EditorExtension::checkMathtags(const MathData &begin,const MathData &end) { // both tags were found, but they must be of the same type if(begin.tag != end.tag) { //KILE_DEBUG_MAIN << "error: opening and closing tag of mathmode don't match: " << begin.tag << " - " << end.tag; return false; } // and additionally: if it is a math env, both tags must have the same name if(begin.tag == mmDisplaymathEnv && begin.envname != end.envname) { //KILE_DEBUG_MAIN << "error: opening and closing env tags have different names: " << begin.envname << " - " << end.envname; return false; } return true; } bool EditorExtension::isOpeningMathTagPosition(KTextEditor::Document *doc, uint row, uint col, MathData &mathdata) { QString textline = getTextLineReal(doc,row); QRegExp reg("\\\\begin\\s*\\{([A-Za-z]+\\*?)\\}|\\\\\\[|\\\\\\("); if((int)col != reg.indexIn(textline, col)) { return false; } QChar id = reg.cap(0)[1]; QString envname = reg.cap(1); mathdata.row = row; mathdata.col = col; mathdata.len = reg.cap(0).length(); switch(id.unicode()) { case 'b': if(!(m_latexCommands->isMathEnv(envname) || envname=="math") || m_latexCommands->needsMathMode(envname)) { return false; } mathdata.tag = ( envname=="math" ) ? mmMathEnv : mmDisplaymathEnv; mathdata.envname = envname; break; case '[': mathdata.tag = mmDisplaymathParen; break; case '(': mathdata.tag = mmMathParen; break; } return true; } bool EditorExtension::isClosingMathTagPosition(KTextEditor::Document *doc, uint row, uint col,MathData &mathdata) { QString textline = doc->line(row); QRegExp reg("\\\\end\\s*\\{([A-Za-z]+\\*?)\\}|\\\\\\]|\\\\\\)"); int pos = reg.lastIndexIn(textline, col); if(pos < 0 || (int)col > pos + reg.matchedLength()) { return false; } QChar id = reg.cap(0)[1]; QString envname = reg.cap(1); mathdata.row = row; mathdata.col = pos; mathdata.len = reg.cap(0).length(); switch(id.unicode()) { case 'e': if(!(m_latexCommands->isMathEnv(envname) || envname=="math") || m_latexCommands->needsMathMode(envname)) { return false; } mathdata.tag = ( envname=="math" ) ? mmMathEnv : mmDisplaymathEnv; mathdata.envname = envname; break; case ']': mathdata.tag = mmDisplaymathParen; break; case ')': mathdata.tag = mmMathParen; break; } return true; } bool EditorExtension::findOpenMathTag(KTextEditor::Document *doc, int row, int col, MathData &mathdata) { const QString regExpString = "\\$" "|\\\\begin\\s*\\{([A-Za-z]+\\*?)\\}" "|\\\\end\\s*\\{([A-Za-z]+\\*?)\\}" "|\\\\\\[|\\\\\\]" "|\\\\\\(|\\\\\\)"; QRegExp reg(regExpString); int lastrow = -1, lastcol = -1; QString mathname; bool foundDollar = false; uint numDollar = 0; QString textline = getTextLineReal(doc, row); int column = col; bool continueSearch = true; while(continueSearch) { while((column = reg.lastIndexIn(textline, col)) != -1) { col = column; mathdata.row = row; mathdata.col = col; mathdata.len = reg.cap(0).length(); mathname = reg.cap(0).left(2); // should be better called 'isValidChar()', because it checks for comments // and escaped chars like backslash and dollar in '\\' and '\$' if(mathname == "$") { // count and continue search ++numDollar; // but remember the first dollar found backwards if(!foundDollar) { lastrow = row; lastcol = col; foundDollar = true; } } else if(mathname=="\\[" || mathname=="\\(") { // found start of mathmode if(numDollar == 0) { mathdata.tag = ( mathname == "\\[" ) ? mmDisplaymathParen : mmMathParen; mathdata.numdollar = 0; return true; } else { //KILE_DEBUG_MAIN << "error: dollar not allowed in \\[ or \\( mode"; return false; } } else if(mathname=="\\]" || mathname=="\\)") { continueSearch = false; break; } else if(mathname=="\\b") { // save name of environment QString envname = reg.cap(1); // if we found the opening tag of a math env if(m_latexCommands->isMathEnv(envname) || envname=="math") { if(numDollar > 0) { //KILE_DEBUG_MAIN << "error: dollar not allowed in math env numdollar=" << numDollar; return false; } // if this is a math env with its own mathmode, we have found the starting position if(envname == "math") { mathdata.tag = mmMathEnv; mathdata.envname = envname; return true; } if(!m_latexCommands->needsMathMode(envname)) { mathdata.tag = mmDisplaymathEnv; mathdata.envname = envname; return true; } } // no math env, we found the opening tag of a normal env else { continueSearch = false; break; } } else if(mathname == "\\e") { QString envname = reg.cap(2); // if we found the closing tag of a math env if(m_latexCommands->isMathEnv(envname) || envname == "math") { // if this is a math env with its own mathmode if(!m_latexCommands->needsMathMode(envname) || envname == "math") { continueSearch = false; break; } // if this is a math env which needs $..$ if(m_latexCommands->isMathModeEnv(envname)) { if(numDollar >= 1) { --numDollar; continueSearch = false; break; } // else continue search } } // if we found the closing tag of a normal env else { continueSearch = false; break; } } else { //KILE_DEBUG_MAIN << "error: unknown match"; return false; } // continue search one column left of the last match (if this is possible) if(col == 0) { break; } --col; } if(row > 0) { textline = getTextLineReal(doc,--row); col = textline.length(); } else if(column == -1) { continueSearch = false; break; } } // nothing else found, so math mode starts a the last dollar (the first one found backwards) mathdata.row = lastrow; mathdata.col = lastcol; mathdata.len = 1; mathdata.numdollar = numDollar; mathdata.tag = (numDollar > 0) ? mmMathDollar : mmNoMathMode; return true; } bool EditorExtension::findCloseMathTag(KTextEditor::Document *doc, int row, int col, MathData &mathdata) { const QString regExpString = "\\$" "|\\\\begin\\s*\\{([A-Za-z]+\\*?)\\}" "|\\\\end\\s*\\{([A-Za-z]+\\*?)\\}" "|\\\\\\[|\\\\\\]" "|\\\\\\(|\\\\\\)"; // + int rowFound, colFound; // + QRegExp reg(regExpString); // + reg.setCaseSensitivity(Qt::CaseInsensitive); // + int lastMatch = 0; int rowFound, colFound; QRegExp reg(regExpString); KTextEditor::Range searchRange = KTextEditor::Range(KTextEditor::Cursor(row, col), doc->documentEnd()); while(true) { QVector foundRanges = doc->searchText(searchRange, regExpString, KTextEditor::Regex | KTextEditor::CaseInsensitive); if(foundRanges.isEmpty() || (foundRanges.size() == 1 && !foundRanges.first().isValid())) { break; } //KILE_DEBUG_MAIN << "number of ranges " << foundRanges.count(); if(foundRanges.size() < 3) { break; } KTextEditor::Range range = foundRanges.first(); //KILE_DEBUG_MAIN << "found math tag: " << doc->text(range); if(!range.isValid()) { break; } rowFound = range.start().line(); colFound = range.start().column(); QString textFound = doc->text(range); // should be better called 'isValidChar()', because it checks for comments // and escaped chars like backslash and dollar in '\\' and '\$' if(isValidBackslash(doc, rowFound, colFound)) { QString mathname = textFound.left(2); // always remember behind the last match mathdata.row = rowFound; mathdata.col = colFound; mathdata.len = textFound.length(); if(mathname=="$") { mathdata.tag = mmMathDollar; return true; } else if(mathname=="\\]") { mathdata.tag = mmDisplaymathParen; return true; } else if(mathname=="\\)") { mathdata.tag = mmMathParen; return true; } else if(mathname=="\\[" || mathname=="\\(") { //KILE_DEBUG_MAIN << "error: current mathgroup was not closed"; return false; } else if(mathname=="\\b") { QString envname = doc->text(foundRanges[1]); if(!(m_latexCommands->isMathEnv(envname) || envname=="math")) { //KILE_DEBUG_MAIN << "error: only math env are allowed in mathmode (found begin tag)"; return false; } if(!m_latexCommands->needsMathMode(envname) || envname=="math") { //KILE_DEBUG_MAIN << "error: mathenv with its own mathmode are not allowed in mathmode "; return false; } // else continue search } else if(mathname == "\\e") { QString envname = doc->text(foundRanges[2]); if(!(m_latexCommands->isMathEnv(envname) || envname=="math")) { //KILE_DEBUG_MAIN << "error: only math env are allowed in mathmode (found end tag)"; return false; } if(envname == "math") { mathdata.tag = mmMathEnv; mathdata.envname = envname; return true; } if(!m_latexCommands->needsMathMode(envname)) { mathdata.tag = mmDisplaymathEnv; mathdata.envname = envname; return true; } // else continue search } } // go ahead searchRange = KTextEditor::Range(foundRanges.first().end(), doc->documentEnd()); } //KILE_DEBUG_MAIN << "not found anything"; return false; } //////////////////// insert newlines inside an environment //////////////////// // intelligent newlines: look for the last opened environment // and decide what to insert // or continue the comment void EditorExtension::insertIntelligentNewline(KTextEditor::View *view) { KILE_DEBUG_MAIN << view; view = determineView(view); if(!view) { return; } KTextEditor::Document* doc = view->document(); if(!doc) { return; } QString name; KTextEditor::Cursor cursor = view->cursorPosition(); int row = cursor.line(); int col = cursor.column(); QString newLineAndIndentationString = '\n' + extractIndentationString(view, row); if(isCommentPosition(doc, row, col)) { KILE_DEBUG_MAIN << "found comment"; view->insertText(newLineAndIndentationString + "% "); moveCursorToLastPositionInCurrentLine(view); return; } else if(findOpenedEnvironment(row, col, name, view)) { if(m_latexCommands->isListEnv(name)) { if ( name == "description" ) { view->insertText(newLineAndIndentationString + "\\item[]"); } else { view->insertText(newLineAndIndentationString + "\\item "); } moveCursorToLastPositionInCurrentLine(view); return; } else if(m_latexCommands->isTabularEnv(name) || m_latexCommands->isMathEnv(name)) { view->insertText(newLineAndIndentationString + "\\\\"); moveCursorToLastPositionInCurrentLine(view); return; } } // - no comment position // - found no opened environment // - unknown environment // - finish tabular or math environment view->insertText(newLineAndIndentationString); moveCursorToLastPositionInCurrentLine(view); } bool EditorExtension::findOpenedEnvironment(int &row, int &col, QString &envname, KTextEditor::View *view) { view = determineView(view); if(!view) { return false; } // get current cursor position KTextEditor::Document *doc = view->document(); KTextEditor::Cursor cursor = view->cursorPosition(); row = cursor.line(); col = cursor.column(); EnvData env; int startrow = row; int startcol = col; //KILE_DEBUG_MAIN << " close - start "; // accept a starting place outside an environment bool env_position = isEnvironmentPosition(doc, row, col, env); // We can also accept a column, if we are on the left side of an environment. // But we should decrease the current cursor position for the search. if(env_position && env.cpos != EnvInside) { if(env.cpos == EnvLeft && !decreaseCursorPosition(doc, startrow, startcol)) { return false; } env_position = false; } if(!env_position && findEnvironmentTag(doc, startrow, startcol, env, true)) { //KILE_DEBUG_MAIN << " close - found begin env at: " << env.row << "/" << env.col << " " << env.name; row = env.row; col = env.col; envname = env.name; return true; } else { return false; } } QStringList EditorExtension::findOpenedEnvironmentList(KTextEditor::View *view, bool position) { QStringList envlist; view = determineView(view); if(view) { int currentRow, currentCol; KTextEditor::Document *doc = view->document(); KTextEditor::Cursor cursor = view->cursorPosition(); currentRow = cursor.line(); currentCol = cursor.column(); int row = currentRow; int col = currentCol; EnvData env; // check the starting position bool env_position = isEnvironmentPosition(doc, row, col, env); if(env_position) { // we are inside an environment tag: bad to complete if(env.cpos == EnvInside) { return envlist; } // we are left of an environment tag: go one position to the left if(env.cpos == EnvLeft) { if (!decreaseCursorPosition(doc, row, col)) { return envlist; } } } while (findEnvironmentTag(doc, row, col, env, true)) { row = env.row; col = env.col; if(position) { envlist << env.name + QString(",%1,%2").arg(row).arg(col); } else { envlist << env.name; } if(col == 0) { if (!decreaseCursorPosition(doc, row, col)) { break; } } view->setCursorPosition(KTextEditor::Cursor(row, col)); } // reset cursor original position view->setCursorPosition(KTextEditor::Cursor(currentRow, currentCol)); } return envlist; } //////////////////// select an environment //////////////////// void EditorExtension::selectEnvironment(bool inside, KTextEditor::View *view) { view = determineView(view); if(!view) { return; } if (!view->selection() || !expandSelectionEnvironment(inside,view)) { KTextEditor::Range range = environmentRange(inside,view); if(range.isValid()) { view->setSelection(range); } } } void EditorExtension::deleteEnvironment(bool inside, KTextEditor::View *view) { view = determineView(view); if(!view) { return; } KTextEditor::Range range = environmentRange(inside,view); if(range.isValid()) { deleteRange(range,view); } } void EditorExtension::deleteRange(KTextEditor::Range &range, KTextEditor::View *view) { view->removeSelection(); view->document()->removeText(range); view->setCursorPosition(range.start()); } // calculate start and end of an environment bool EditorExtension::getEnvironment(bool inside, EnvData &envbegin, EnvData &envend, KTextEditor::View *view) { view = determineView(view); if(!view) { return false; } int row, col; KTextEditor::Document *doc = view->document(); KTextEditor::Cursor cursor = view->cursorPosition(); row = cursor.line(); col = cursor.column(); if(!findBeginEnvironment(doc, row, col, envbegin)) { return false; } if(!findEndEnvironment(doc, row, col, envend)) { return false; } if(inside) { envbegin.col += envbegin.len; } else { envend.col += envend.len; } return true; } KTextEditor::Range EditorExtension::environmentRange(bool inside, KTextEditor::View *view) { // view will be checked in getEnvironment() EnvData envbegin, envend; return (getEnvironment(inside, envbegin, envend, view)) ? KTextEditor::Range(envbegin.row, envbegin.col, envend.row, envend.col) : KTextEditor::Range::invalid(); } QString EditorExtension::environmentText(bool inside, KTextEditor::View *view) { view = determineView(view); if(!view) { return QString(); } KTextEditor::Range range = environmentRange(inside,view); return (range.isValid()) ? view->document()->text(range) : QString(); } QString EditorExtension::environmentName(KTextEditor::View *view) { // view will be checked in getEnvironment() EnvData envbegin, envend; return (getEnvironment(false, envbegin, envend, view)) ? envbegin.name : QString(); } // determine text, startrow and startcol of current environment QString EditorExtension::getEnvironmentText(int &row, int &col, QString &name, KTextEditor::View *view) { view = determineView(view); if(!view) { return QString(); } EnvData envbegin, envend; if(getEnvironment(false, envbegin, envend, view) && envbegin.name != "document") { row = envbegin.row; col = envbegin.col; name = envbegin.name; return view->document()->text(KTextEditor::Range(envbegin.row, envbegin.col, envend.row, envend.col)); } else { return QString(); } } bool EditorExtension::hasEnvironment(KTextEditor::View *view) { view = determineView(view); if(!view) { return false; } EnvData envbegin,envend; return (getEnvironment(false, envbegin, envend, view) && envbegin.name != "document"); } // when an environment is selected (inside or outside), // the selection is expanded to the surrounding environment bool EditorExtension::expandSelectionEnvironment(bool inside, KTextEditor::View *view) { KTextEditor::Document *doc = view->document(); if (!view->selection()) { return false; } // get current position int row, col; KTextEditor::Cursor cursor = view->cursorPosition(); row = cursor.line(); col = cursor.column(); // get current selection KTextEditor::Range selectionRange = view->selectionRange(); int row1 = selectionRange.start().line(); int col1 = selectionRange.start().column(); int row2 = selectionRange.end().line(); int col2 = selectionRange.end().column(); // determine current environment outside EnvData oenvbegin,oenvend; if(!getEnvironment(false, oenvbegin, oenvend, view)) { return false; } bool newselection = false; // first look, if this environment is selected outside if(row1 == oenvbegin.row && col1 == oenvbegin.col && row2 == oenvend.row && col2 == oenvend.col) { if(!decreaseCursorPosition(doc, oenvbegin.row, oenvbegin.col) ) { return newselection; } view->setCursorPosition(KTextEditor::Cursor(oenvbegin.row, oenvbegin.col)); // search the surrounding environment and select it if(getEnvironment(inside, oenvbegin, oenvend, view)) { view->setSelection(KTextEditor::Range(oenvbegin.row, oenvbegin.col, oenvend.row, oenvend.col)); newselection = true; } } else { // then determine current environment inside EnvData ienvbegin, ienvend; getEnvironment(true, ienvbegin, ienvend, view); // and look, if this environment is selected inside if(row1 == ienvbegin.row && col1 == ienvbegin.col && row2 == ienvend.row && col2 == ienvend.col) { if(!decreaseCursorPosition(doc, oenvbegin.row, oenvbegin.col) ) { return newselection; } view->setCursorPosition(KTextEditor::Cursor(oenvbegin.row, oenvbegin.col)); // search the surrounding environment and select it if(getEnvironment(inside, ienvbegin, ienvend, view)) { view->setSelection(KTextEditor::Range(ienvbegin.row, ienvbegin.col, ienvend.row, ienvend.col)); newselection = true; } } } // restore old cursor position view->setCursorPosition(KTextEditor::Cursor(row, col)); return newselection; } //////////////////// search for \begin{env} //////////////////// // Find the last \begin{env} tag. If the current cursor is over // - \begin{env} tag: we will stop immediately // - \end{env} tag: we will start before this tag bool EditorExtension::findBeginEnvironment(KTextEditor::Document *doc, int row, int col, EnvData &env) { // KILE_DEBUG_MAIN << " find begin: "; if(isEnvironmentPosition(doc, row, col, env)) { // already found position? //KILE_DEBUG_MAIN << " found env at: " << env.row << "/" << env.col << " " << env.name; if(env.tag == EnvBegin) { //KILE_DEBUG_MAIN << " is begin env at: " << env.row << "/" << env.col << " " << env.name; return true; } // go one position back //KILE_DEBUG_MAIN << " is end env at: " << env.row << "/" << env.col << " " << env.name; row = env.row; col = env.col; if(!decreaseCursorPosition(doc, row, col)) { return false; } } // looking back for last environment //KILE_DEBUG_MAIN << " looking back from pos: " << row << "/" << col << " " << env.name; return findEnvironmentTag(doc, row, col, env, true); } //////////////////// search for \end{env} //////////////////// // Find the last \end{env} tag. If the current cursor is over // - \end{env} tag: we will stop immediately // - \begin{env} tag: we will start behind this tag bool EditorExtension::findEndEnvironment(KTextEditor::Document *doc, int row, int col, EnvData &env) { if(isEnvironmentPosition(doc, row, col, env)) { // already found position? if(env.tag == EnvEnd ) { return true; } // go one position forward row = env.row; col = env.col + 1; } // looking forward for the next environment return findEnvironmentTag(doc, row, col, env, false); } //////////////////// search for an environment tag //////////////////// // find the last/next non-nested environment tag bool EditorExtension::findEnvironmentTag(KTextEditor::Document *doc, int row, int col, EnvData &env, bool backwards) { unsigned int envcount = 0; KTextEditor::Range searchRange; if(backwards) { searchRange = KTextEditor::Range(KTextEditor::Cursor(0, 0), KTextEditor::Cursor(row, col)); } else { searchRange = KTextEditor::Range(KTextEditor::Cursor(row, col), doc->documentEnd()); } KTextEditor::SearchOptions searchOptions = (backwards) ? KTextEditor::Regex | KTextEditor::Backwards : KTextEditor::Regex; while(true) { QVector foundRanges = doc->searchText(searchRange, m_reg.pattern(), searchOptions); if(foundRanges.isEmpty() || (foundRanges.size() == 1 && !foundRanges.first().isValid())) { break; } //KILE_DEBUG_MAIN << "number of ranges " << foundRanges.count(); EnvTag wrong_env = (backwards) ? EnvEnd : EnvBegin; if(foundRanges.size() < 5) { break; } KTextEditor::Range range = foundRanges.first(); if(!range.isValid()) { //KILE_DEBUG_MAIN << "invalid range found"; break; } env.row = range.start().line(); env.col = range.start().column(); env.len = doc->text(range).length(); if(isValidBackslash(doc, env.row, env.col)) { // index 0 is the fullmatch, 1 first cap and so on QString cap2 = (foundRanges[2].isValid() ? doc->text(foundRanges[2]) : ""); QString cap3 = (foundRanges[3].isValid() ? doc->text(foundRanges[3]) : ""); QString cap4 = (foundRanges[4].isValid() ? doc->text(foundRanges[4]) : ""); EnvTag found_env = (cap2 == "begin" || cap4 == "\\[") ? EnvBegin : EnvEnd; if(found_env == wrong_env) { ++envcount; } else { if(envcount > 0) { --envcount; } else { if(found_env == EnvBegin) { env.name = (cap2 == "begin") ? cap3 : "\\["; } else { env.name = (cap2 == "end") ? cap3 : "\\]"; } env.tag = found_env; //KILE_DEBUG_MAIN << "found " << env.name; return true; } } } // finally, prepare the range for the next search if(backwards) { searchRange = KTextEditor::Range(KTextEditor::Cursor(0, 0), foundRanges.first().start()); } else { searchRange = KTextEditor::Range(foundRanges.first().end(), doc->documentEnd()); } } //KILE_DEBUG_MAIN << "not found anything"; return false; } //////////////////// check for an environment position //////////////////// // Check if the current position belongs to an environment. The result is set // to the beginning backslash of the environment tag. The same algorithms as // matching brackets is used. // // insert mode: if there is a full tag on the left, always take it // if not, look to the right // overwrite mode: always take the tag, which begins at the cursor position // // test it with {a}{{b}}{c} bool EditorExtension::isEnvironmentPosition(KTextEditor::Document *doc, int row, int col, EnvData &env) { // get real textline without comments, quoted characters and pairs of backslashes QString textline = getTextLineReal(doc, row); if(col > textline.length()) { return false; } bool left = false; //KILE_DEBUG_MAIN << "col=" << col; // check if there is a match in this line from the current position to the left int startcol = (textline[col] == '\\') ? col - 1 : col; if(startcol >= 1) { //KILE_DEBUG_MAIN << "search to the left "; int pos = textline.lastIndexOf(m_reg, startcol); env.len = m_reg.matchedLength(); if(pos != -1 && pos < col && col <= pos + env.len) { //KILE_DEBUG_MAIN << "search to the left: found"; env.row = row; env.col = pos; QChar ch = textline.at(pos + 1); if(ch=='b' || ch=='e') { env.tag = (ch == 'b') ? EnvBegin : EnvEnd; env.name = m_reg.cap(3); } else { env.tag = (ch == '[') ? EnvBegin : EnvEnd; env.name = m_reg.cap(4); } if ( !m_overwritemode || (m_overwritemode && colline(row); bool backslash = false; for(int i = 0; i < col; ++i) { if(textline[i] == '%') { if(!backslash) { // found a comment sign return true; } else { backslash = false; } } else if(textline[i] == '\\') { // count number of backslashes backslash = !backslash; } else { backslash = false; // no backslash } } return false; } // check if the character at text[col] is a valid backslash: // - there is no comment sign in this line before // - there is not a odd number of backslashes directly before bool EditorExtension::isValidBackslash(KTextEditor::Document *doc, int row, int col) { QString textline = doc->line(row); bool backslash = false; for(int i = 0; i < col; ++i) { if(textline[i] == '%') { if(!backslash) { return false; // found a comment sign } else { backslash = false; } } else if(textline[i] == '\\') { // count number of backslashes backslash = !backslash; } else { backslash = false; // no backslash } } return !backslash; } //////////////////// goto next bullet //////////////////// void EditorExtension::gotoBullet(bool backwards, KTextEditor::View *view) { view = determineView(view); if(!view) { return; } // get current position KTextEditor::Document *doc = view->document(); KTextEditor::Cursor cursor = view->cursorPosition(); KTextEditor::SearchOptions searchOptions = (backwards) ? KTextEditor::Backwards : KTextEditor::Default; KTextEditor::Range searchRange; if(backwards) { searchRange = KTextEditor::Range(KTextEditor::Cursor(0, 0), cursor); } else { const KTextEditor::Cursor nextCursorPosition(cursor.line(), cursor.column() + 1); if((doc->characterAt(cursor) == s_bullet_char) // we are already at a bullet && view->selection() && view->selectionRange() == KTextEditor::Range(cursor, nextCursorPosition)) { // which has been 'highlighted' cursor = nextCursorPosition; // search for the next bullet } searchRange = KTextEditor::Range(cursor, doc->documentEnd()); } QVector foundRanges = doc->searchText(searchRange, s_bullet, searchOptions); if(foundRanges.size() >= 1) { KTextEditor::Range range = foundRanges.first(); if(range.isValid()) { int line = range.start().line(); int column = range.start().column(); view->setCursorPosition(KTextEditor::Cursor(line, column)); view->setSelection(KTextEditor::Range(line, column, line, column + 1)); } } } //////////////////// increase/decrease cursor position //////////////////// bool EditorExtension::moveCursorRight(KTextEditor::View *view) { return moveCursor(view, MoveCursorRight); } bool EditorExtension::moveCursorLeft(KTextEditor::View *view) { return moveCursor(view, MoveCursorLeft); } bool EditorExtension::moveCursorUp(KTextEditor::View *view) { return moveCursor(view, MoveCursorUp); } bool EditorExtension::moveCursorDown(KTextEditor::View *view) { return moveCursor(view, MoveCursorDown); } bool EditorExtension::moveCursor(KTextEditor::View *view, CursorMove direction) { view = determineView(view); if(!view) { return false; } KTextEditor::Document *doc = view->document(); KTextEditor::Cursor cursor = view->cursorPosition(); int row = cursor.line(); int col = cursor.column(); bool ok = false; switch (direction) { case MoveCursorLeft: ok = decreaseCursorPosition(doc,row,col); break; case MoveCursorRight: ok = increaseCursorPosition(doc,row,col); break; case MoveCursorUp: if(row > 0) { row--; ok = true; } break; case MoveCursorDown: if(row < doc->lines() - 1) { row++; ok = true; } break; } if(ok) { return view->setCursorPosition(KTextEditor::Cursor(row,col)); } else { return false; } } bool EditorExtension::increaseCursorPosition(KTextEditor::Document *doc, int &row, int &col) { bool ok = true; if(col < doc->lineLength(row) - 1) { ++col; } else if(row < doc->lines() - 1) { ++row; col = 0; } else { ok = false; } return ok; } bool EditorExtension::decreaseCursorPosition(KTextEditor::Document *doc, int &row, int &col) { bool ok = true; if(col > 0) { --col; } else if(row > 0) { --row; col = doc->lineLength(row); } else { ok = false; } return ok; } //////////////////// texgroups //////////////////// // goto the next non-nested bracket void EditorExtension::gotoTexgroup(bool backwards, KTextEditor::View *view) { view = determineView(view); if(!view) return; uint row,col; bool found; BracketData bracket; // get current position KTextEditor::Document *doc = view->document(); KTextEditor::Cursor cursor = view->cursorPosition(); row = cursor.line(); col = cursor.column(); m_overwritemode = (view->viewMode() == KTextEditor::View::NormalModeOverwrite); // start searching if(backwards) { found = findOpenBracket(doc, row, col, bracket); } else { found = findCloseBracket(doc, row, col, bracket); // go behind the bracket if(!m_overwritemode) { ++bracket.col; } } if(found) { view->setCursorPosition(KTextEditor::Cursor(bracket.row, bracket.col)); } } // match the opposite bracket void EditorExtension::matchTexgroup(KTextEditor::View *view) { view = determineView(view); if(!view) { return; } int row, col; BracketData bracket; // get current position KTextEditor::Document *doc = view->document(); KTextEditor::Cursor cursor = view->cursorPosition(); row = cursor.line(); col = cursor.column(); m_overwritemode = (view->viewMode() == KTextEditor::View::NormalModeOverwrite); // this operation is only allowed at a bracket position if(!isBracketPosition(doc, row, col, bracket)) { return; } // start searching bool found = false; if(bracket.open) { found = findCloseBracketTag(doc, bracket.row, bracket.col + 1, bracket); // go behind the bracket if(!m_overwritemode) { ++bracket.col; } } else { if(!decreaseCursorPosition(doc, bracket.row, bracket.col)) { return; } found = findOpenBracketTag(doc, bracket.row, bracket.col, bracket); } if(found) { view->setCursorPosition(KTextEditor::Cursor(bracket.row, bracket.col)); } } //////////////////// close an open texgroup //////////////////// // search for the last opened texgroup and close it void EditorExtension::closeTexgroup(KTextEditor::View *view) { view = determineView(view); if(!view) { return; } int row, col; BracketData bracket; KTextEditor::Document *doc = view->document(); KTextEditor::Cursor cursor = view->cursorPosition(); row = cursor.line(); col = cursor.column(); int rowtemp = row; int coltemp = col; if(!decreaseCursorPosition(doc, rowtemp, coltemp)) { return; } if(findOpenBracketTag(doc, rowtemp, coltemp, bracket)) { doc->insertText(KTextEditor::Cursor(row, col), "}"); view->setCursorPosition(KTextEditor::Cursor(row, col + 1)); } } //////////////////// select a texgroup //////////////////// void EditorExtension::selectTexgroup(bool inside, KTextEditor::View *view) { view = determineView(view); if(!view) { return; } KTextEditor::Range range = texgroupRange(inside,view); if(range.isValid()) { view->setSelection(range); } } void EditorExtension::deleteTexgroup(bool inside, KTextEditor::View *view) { view = determineView(view); if(!view) { return; } KTextEditor::Range range =texgroupRange(inside,view); if(range.isValid()) { deleteRange(range, view); } } // calculate start and end of a Texgroup KTextEditor::Range EditorExtension::texgroupRange(bool inside, KTextEditor::View *view) { view = determineView(view); if(!view) { return KTextEditor::Range::invalid(); } BracketData open, close; if(getTexgroup(inside, open, close, view)) { return KTextEditor::Range(open.row, open.col, close.row, close.col); } else { return KTextEditor::Range::invalid(); } } bool EditorExtension::hasTexgroup(KTextEditor::View *view) { // view will be checked in texgroupRange() KTextEditor::Range range = texgroupRange(true, view); return (range.isValid()) ? true : false; } QString EditorExtension::getTexgroupText(bool inside, KTextEditor::View *view) { view = determineView(view); if(!view) { return QString(); } KTextEditor::Range range = texgroupRange(inside,view); return (range.isValid()) ? view->document()->text(range) : QString(); } bool EditorExtension::getTexgroup(bool inside, BracketData &open, BracketData &close, KTextEditor::View *view) { view = determineView(view); if(!view) { return false; } int row, col; KTextEditor::Document *doc = view->document(); KTextEditor::Cursor cursor = view->cursorPosition(); row = cursor.line(); col = cursor.column(); if(!findOpenBracket(doc, row, col, open)) { //KILE_DEBUG_MAIN << "no open bracket"; return false; } if(!findCloseBracket(doc, row, col, close)) { //KILE_DEBUG_MAIN << "no close bracket"; return false; } if(inside) { ++open.col; } else { ++close.col; } return true; } //////////////////// search for a bracket position //////////////////// // Find the last opening bracket. If the current cursor is over // - '{': we will stop immediately // - '}': we will start before this character bool EditorExtension::findOpenBracket(KTextEditor::Document *doc, int row, int col, BracketData &bracket) { if(isBracketPosition(doc, row, col, bracket)) { // already found position? if(bracket.open) { return true; } // go one position back row = bracket.row; col = bracket.col; if(!decreaseCursorPosition(doc, row, col)) { return false; } } // looking back for last bracket return findOpenBracketTag(doc, row, col, bracket); } // Find the last closing bracket. If the current cursor is over // - '}': we will stop immediately // - '{': we will start behind this character bool EditorExtension::findCloseBracket(KTextEditor::Document *doc, int row, int col, BracketData &bracket) { if (isBracketPosition(doc, row, col, bracket)) { // already found position? if(!bracket.open) { return true; } // go one position forward row = bracket.row; col = bracket.col + 1; } // looking forward for next bracket return findCloseBracketTag(doc, row, col, bracket); } /* Bracket matching uses the following algorithm (taken from Kate): 1) If in overwrite mode, match the bracket currently underneath the cursor. 2) Otherwise, if the character to the left of the cursor is an ending bracket, match it. 3) Otherwise if the character to the right of the cursor is a starting bracket, match it. 4) Otherwise, if the character to the left of the cursor is a starting bracket, match it. 5) Otherwise, if the character to the right of the cursor is an ending bracket, match it. 6) Otherwise, don't match anything. */ bool EditorExtension::isBracketPosition(KTextEditor::Document *doc, int row, int col, BracketData &bracket) { // default results bracket.row = row; bracket.col = col; QString textline = getTextLineReal(doc, row); QChar right = textline[col]; QChar left = (col > 0) ? textline[col-1] : QChar(' '); if (m_overwritemode) { if(right == '{') { bracket.open = true; } else if(left == '}') { bracket.open = false; } else { return false; } } else if(left == '}') { bracket.open = false; --bracket.col; } else if(right == '{') { bracket.open = true; } else if(left == '{') { bracket.open = true; --bracket.col; } else if(right == '}') { bracket.open = false; } else { return false; } return true; } // find next non-nested closing bracket bool EditorExtension::findCloseBracketTag(KTextEditor::Document *doc, int row, int col, BracketData &bracket) { uint brackets = 0; for(int line = row; line < doc->lines(); ++line) { uint start = (line == row) ? col : 0; QString textline = getTextLineReal(doc,line); for(int i = start; i < textline.length(); ++i) { if(textline[i] == '{') { ++brackets; } else if(textline[i] == '}') { if(brackets > 0) { --brackets; } else { bracket.row = line; bracket.col = i; bracket.open = false; return true; } } } } return false; } // find next non-nested opening bracket bool EditorExtension::findOpenBracketTag(KTextEditor::Document *doc, int row, int col, BracketData &bracket) { uint brackets = 0; for(int line = row; line >= 0; --line) { QString textline = getTextLineReal(doc, line); int start = (line == row) ? col : textline.length() - 1; for (int i = start; i >= 0; --i) { //KILE_DEBUG_MAIN << "findOpenBracketTag: (" << line << "," << i << ") = " << textline[i].toLatin1(); if(textline[i] == '{') { if(brackets > 0) { --brackets; } else { bracket.row = line; bracket.col = i; bracket.open = true; return true; } } else if(textline[i] == '}') { ++brackets; } } } //KILE_DEBUG_MAIN << "nothting found"; return false; } //////////////////// get real text //////////////////// // get current textline and remove // - all pairs of backslashes: '\\' // - all quoted comment signs: '\%' // - all quoted brackets: '\{' and '\}' // - all comments -// replace these characters one one, which never will be looked for +// replace these characters with one, which never will be looked for QString EditorExtension::getTextLineReal(KTextEditor::Document *doc, int row) { QString textline = doc->line(row); int len = textline.length(); if(len == 0) { return QString(); } bool backslash = false; for(int i = 0; i < len; ++i) { if (textline[i]=='{' || textline[i]=='}' || textline[i]=='$') { if(backslash) { textline[i-1] = '&'; textline[i] = '&'; } backslash = false; } else if(textline[i] == '\\') { if(backslash) { textline[i-1] = '&'; textline[i] = '&'; backslash = false; } else { backslash = true; } } else if(textline[i]=='%') { if (backslash) { textline[i-1] = '&'; textline[i] = '&'; } else { len = i; break; } backslash = false; } else { backslash = false; } } // return real text return textline.left(len); } //////////////////// capture the current word //////////////////// // Capture the current word from the cursor position to the left and right. // The result depens on the given search mode; // - smTex only letters, except backslash as first and star as last character // - smLetter: only letters // - smWord: letters and digits // - smNospace: everything except white space bool EditorExtension::getCurrentWord(KTextEditor::Document *doc, int row, int col, EditorExtension::SelectMode mode, QString &word, int &x1, int &x2) { // get real textline without comments, quoted characters and pairs of backslashes QString textline = getTextLineReal(doc, row); if (col > textline.length()) { return false; } QRegExp reg; QString pattern1, pattern2; switch(mode) { case smLetter: pattern1 = "[^a-zA-Z]+"; pattern2 = "[a-zA-Z]+"; break; case smWord: pattern1 = "[^a-zA-Z0-9]"; pattern2 = "[a-zA-Z0-9]+"; break; case smNospace: pattern1 = "\\s"; pattern2 = "\\S+"; break; default: pattern1 = "[^a-zA-Z]"; pattern2 = "\\\\?[a-zA-Z]+\\*?"; break; } x1 = x2 = col; int pos; // search to the left side if(col > 0) { reg.setPattern(pattern1); pos = textline.lastIndexOf(reg, col - 1); if(pos != -1) { // found an illegal character x1 = pos + 1; if(mode == smTex) { if(textline[pos] == '\\') { x1 = pos; } col = x1; } } else { x1 = 0; // pattern matches from beginning of line } } // search at the current position reg.setPattern(pattern2); pos = textline.indexOf(reg, col); if(pos != -1 && pos == col) { x2 = pos + reg.matchedLength(); } // get all characters if(x1 != x2) { word = textline.mid(x1, x2 - x1); return true; } else { return false; } } KTextEditor::Range EditorExtension::wordRange(const KTextEditor::Cursor &cursor, bool latexCommand, KTextEditor::View *view) { view = determineView(view); if(!view) { return KTextEditor::Range::invalid(); } int col1, col2; QString word; EditorExtension::SelectMode mode = ( latexCommand ) ? EditorExtension::smTex : EditorExtension::smLetter; int line = cursor.line(); return (getCurrentWord(view->document(), line, cursor.column(), mode, word, col1, col2)) ? KTextEditor::Range(line,col1,line,col2) : KTextEditor::Range::invalid(); } QString EditorExtension::word(const KTextEditor::Cursor &cursor, bool latexCommand, KTextEditor::View *view) { KTextEditor::Range range = EditorExtension::wordRange(cursor,latexCommand,view); return ( range.isValid() ) ? view->document()->text(range) : QString(); } //////////////////// paragraph //////////////////// void EditorExtension::selectParagraph(KTextEditor::View* view, bool wholeLines) { view = determineView(view); if(!view) { return; } KTextEditor::Range range = findCurrentParagraphRange(view, wholeLines); if ( range.isValid() ) { view->setSelection(range); } } void EditorExtension::deleteParagraph(KTextEditor::View *view) { view = determineView(view); if(!view) { return; } int startline, endline; if(findCurrentTexParagraph(startline, endline, view)) { KTextEditor::Document *doc = view->document(); view->removeSelection(); if(startline > 0) { --startline; } else if(endline < doc->lines() - 1) { ++endline; } doc->removeText(KTextEditor::Range(startline, 0, endline+1, 0)); view->setCursorPosition(KTextEditor::Cursor(startline, 0)); } } // get the range of the current paragraph KTextEditor::Range EditorExtension::findCurrentParagraphRange(KTextEditor::View* view, bool wholeLines) { view = determineView(view); if(!view) { return KTextEditor::Range::invalid(); } int startline, endline, startcolumn, endcolumn; if (findCurrentTexParagraph(startline, startcolumn, endline, endcolumn, view)) { return wholeLines ? KTextEditor::Range(startline, 0, endline + 1, 0) : KTextEditor::Range(startline, startcolumn, endline, endcolumn); } else { return KTextEditor::Range::invalid(); } } QString EditorExtension::getParagraphText(KTextEditor::View *view) { view = determineView(view); if(!view) { return QString(); } KTextEditor::Range range = findCurrentParagraphRange(view); return (range.isValid()) ? view->document()->text(range) : QString(); } bool EditorExtension::findCurrentTexParagraph(int& startline, int& endline, KTextEditor::View* view) { int dummy; return findCurrentTexParagraph(startline, dummy, endline, dummy, view); } bool EditorExtension::findCurrentTexParagraph(int& startline, int& startcolumn, int& endline, int& endcolumn, KTextEditor::View* view) { view = determineView(view); if(!view) { return false; } int row; // get current position KTextEditor::Document *doc = view->document(); KTextEditor::Cursor cursor = view->cursorPosition(); row = cursor.line(); // don't accept an empty line as part of a paragraph if(doc->line(row).trimmed().isEmpty()) { return false; } // settings default results startline = row; endline = row; // find the previous empty line for(int line = row - 1; line >= 0; --line) { if(doc->line(line).trimmed().isEmpty()) { break; } startline = line; } // it is guaranteed that 'startline.trimmed()' won't be empty startcolumn = 0; QString line = doc->line(startline); for(int i = 0; i < line.size(); ++i) { if(!line[i].isSpace()) { startcolumn = i; break; } } // find the next empty line for(int line = row + 1; line < doc->lines(); ++line) { if(doc->line(line).trimmed().isEmpty()) { break; } endline = line; } // it is guaranteed that 'endline.trimmed()' won't be empty line = doc->line(endline); endcolumn = line.size(); for(int i = line.size() - 1; i >= 0; --i) { if(!line[i].isSpace()) { endcolumn = i+1; break; } } // settings result return true; } void EditorExtension::gotoNextParagraph(KTextEditor::View *view) { view = determineView(view); if(!view) { return; } bool found; int startline, endline; KTextEditor::Document *doc = view->document(); endline = view->cursorPosition().line(); if(doc->line(endline).trimmed().isEmpty()) { found = true; } else { found = findCurrentTexParagraph(startline, endline, view); } // we are in an empty line or in the last line of a paragraph if (found) { // find the next non empty line for(int line = endline + 1; line < doc->lines(); ++line) { if(!doc->line(line).trimmed().isEmpty()) { view->setCursorPosition(KTextEditor::Cursor(line, 0)); return; } } } } void EditorExtension::gotoPrevParagraph(KTextEditor::View *view) { view = determineView(view); if(!view) { return; } bool found; int startline,endline; KTextEditor::Document *doc = view->document(); startline = view->cursorPosition().line(); if(doc->line(startline).trimmed().isEmpty()) { startline++; found = true; } else { found = findCurrentTexParagraph(startline,endline,view); } // we are in an empty line or in the first line of a paragraph if(found) { // find the last line of the previous paragraph int foundline = -1; for (int line = startline - 1; line >= 0; --line) { if(!doc->line(line).trimmed().isEmpty()) { break; } foundline = line; } if(foundline < 0) { return; } // and finally the first line of this paragraph int prevstartline = -1; for(int line = foundline - 1; line >= 0; --line) { if(doc->line(line).trimmed().isEmpty()) { break; } prevstartline = line; } if(prevstartline >= 0) { view->setCursorPosition(KTextEditor::Cursor(prevstartline, 0)); } } } int EditorExtension::prevNonEmptyLine(int line, KTextEditor::View *view) { view = determineView(view); if(!view) { return -1; } KTextEditor::Document *doc = view->document(); for(int i = line - 1; i >= 0; --i) { if(!doc->line(i).trimmed().isEmpty()) { return i; } } return -1; } int EditorExtension::nextNonEmptyLine(int line, KTextEditor::View *view) { view = determineView(view); if(!view) { return -1; } KTextEditor::Document *doc = view->document(); int lines = doc->lines(); for(int i = line + 1; i < lines; ++i) { if(!doc->line(i).trimmed().isEmpty()) { return i; } } return -1; } //////////////////// one line of text//////////////////// void EditorExtension::selectLine(KTextEditor::View *view) { view = determineView(view); if(!view) { return; } // get current position int row; QString word; KTextEditor::Document *doc = view->document(); KTextEditor::Cursor cursor = view->cursorPosition(); row = cursor.line(); if(doc->lineLength(row) > 0) { view->setSelection(KTextEditor::Range(row, 0, row + 1, 0)); } } void EditorExtension::selectLine(int line, KTextEditor::View *view) { view = determineView(view); if(!view) { return; } if(view->document()->lineLength(line) > 0) { view->setSelection(KTextEditor::Range(line, 0, line + 1, 0)); } } void EditorExtension::selectLines(int from, int to, KTextEditor::View *view) { view = determineView(view); if(view && from <= to) { view->setSelection(KTextEditor::Range(from, 0, to + 1, 0)); } } bool EditorExtension::replaceLine(int line, const QString &s, KTextEditor::View *view) { view = determineView(view); if(!view) { return false; } KTextEditor::Document *doc = view->document(); KTextEditor::Document::EditingTransaction transaction(doc); doc->removeLine(line); bool result = doc->insertLine(line, s); return result; } void EditorExtension::deleteEndOfLine(KTextEditor::View *view) { view = determineView(view); if(!view) { return; } int row, col; KTextEditor::Cursor cursor = view->cursorPosition(); row = cursor.line(); col = cursor.column(); KTextEditor::Document *doc = view->document(); view->removeSelection(); doc->removeText(KTextEditor::Range(row, col, row, doc->lineLength(row))); } //////////////////// LaTeX command //////////////////// void EditorExtension::selectWord(EditorExtension::SelectMode mode, KTextEditor::View *view) { view = determineView(view); if(!view) { return; } KTextEditor::Range range = wordRange(view->cursorPosition(),mode,view); if ( range.isValid() ) { view->setSelection(range); } } void EditorExtension::deleteWord(EditorExtension::SelectMode mode, KTextEditor::View *view) { view = determineView(view); if(!view) { return; } KTextEditor::Range range = wordRange(view->cursorPosition(),mode,view); if(range.isValid()) { deleteRange(range,view); } } void EditorExtension::nextBullet(KTextEditor::View* view) { gotoBullet(false, view); } void EditorExtension::prevBullet(KTextEditor::View* view) { gotoBullet(true, view); } void EditorExtension::insertBullet(KTextEditor::View* view) { view = determineView(view); if(!view) { return; } view->document()->insertText(view->cursorPosition(), s_bullet); } ///////////////////// Special Functions /////////////// /* void EditorExtension::insertNewLine(KTextEditor::View *view) { view = determineView(view); if(!view) { return; } int newLineNumber = view->cursorPosition().line() + 1; view->document()->insertLine(newLineNumber, QString()); } */ void EditorExtension::moveCursorToLastPositionInCurrentLine(KTextEditor::View *view) { view = determineView(view); if(!view) { return; } const KTextEditor::Cursor currentPosition = view->cursorPosition(); view->setCursorPosition(KTextEditor::Cursor(currentPosition.line(), view->document()->lineLength(currentPosition.line()))); } void EditorExtension::keyReturn(KTextEditor::View *view) { view = determineView(view); if(!view) { return; } int newLineNumber = view->cursorPosition().line() + 1; view->document()->insertLine(newLineNumber, QString()); view->setCursorPosition(KTextEditor::Cursor(newLineNumber, 0)); } void EditorExtension::commentLaTeX(KTextEditor::Document* document, const KTextEditor::Range& range) { int startLine = range.start().line(), endLine = range.end().line(); for(int i = startLine; i <= endLine; ++i) { document->insertText(KTextEditor::Cursor(i, 0), "% "); } } void EditorExtension::goToLine(int line, KTextEditor::View *view) { view = determineView(view); if(!view) { return; } KTextEditor::Cursor cursor(line, 0); view->setCursorPosition(cursor); } //////////////////// double quotes //////////////////// void EditorExtension::initDoubleQuotes() { m_dblQuotes = KileConfig::insertDoubleQuotes(); int index = KileConfig::doubleQuotes(); if(index < 0 || index >= m_quoteList.count()) { index = 0; } m_leftDblQuote = m_quoteList[index].first; m_rightDblQuote = m_quoteList[index].second; KILE_DEBUG_MAIN << "new quotes: " << m_dblQuotes << " left=" << m_leftDblQuote << " right=" << m_rightDblQuote<< endl; } bool EditorExtension::insertDoubleQuotes(KTextEditor::View *view) { // don't insert double quotes, if konsole has focus // return false, because if this is called from an event // handler, because this event has to be passed on if(m_ki->texKonsole()->hasFocus()) { return false; } // insert double quotes, normal mode or autocompletion mode // always return true for event handler view = determineView(view); if(!view) { return true; } KTextEditor::Document *doc = view->document(); if(!doc) { return false; } view->removeSelectionText(); int row, col; KTextEditor::Cursor cursor = view->cursorPosition(); row = cursor.line(); col = cursor.column(); // simply insert, if we are inside a verb command if(insideVerb(view) || insideVerbatim(view)) { return false; } // simply insert, if autoinsert mode is not active or the char bevor is \ (typically for \"a useful) if (!m_dblQuotes || (col > 0 && doc->text(KTextEditor::Range(row, col - 1, row, col)) == "\\")) { return false; } // insert with auto mode QString pattern1 = QRegExp::escape(m_leftDblQuote); if(m_leftDblQuote.at(m_leftDblQuote.length()-1).isLetter()) { pattern1 += "(\\b|(\\{\\}))"; } QString pattern2 = QRegExp::escape(m_rightDblQuote); if(m_rightDblQuote.at(m_rightDblQuote.length()-1).isLetter()) { pattern2 += "(\\b|(\\{\\}))"; } bool openFound = false; KTextEditor::Range searchRange = KTextEditor::Range(KTextEditor::Cursor(0, 0), KTextEditor::Cursor(row, col)); QVector foundRanges = doc->searchText(searchRange, '(' + pattern1 + ")|(" + pattern2 + ')', KTextEditor::Regex | KTextEditor::Backwards); // KTextEditor::Document#searchText always returns at least one range, even // if no occurrences have been found. Thus, we have to check if the range is valid. KTextEditor::Range range = foundRanges.first(); if(range.isValid()) { int lineFound = range.start().line(); int columnFound = range.start().column(); openFound = (doc->line(lineFound).indexOf(m_leftDblQuote, columnFound) == columnFound); } QString textline = doc->line(row); //KILE_DEBUG_MAIN << "text=" << textline << " open=" << openfound; if(openFound) { // If we last inserted a language specific doublequote open, // we have to change it to a normal doublequote. If not we // insert a language specific doublequote close int startcol = col - m_leftDblQuote.length(); //KILE_DEBUG_MAIN << "startcol=" << startcol << " col=" << col ; if (startcol>=0 && textline.indexOf(m_leftDblQuote, startcol) == startcol) { doc->removeText(KTextEditor::Range(row, startcol, row, startcol + m_leftDblQuote.length())); doc->insertText(KTextEditor::Cursor(row, startcol), "\""); } else { doc->insertText(KTextEditor::Cursor(row, col), m_rightDblQuote); } } else { // If we last inserted a language specific doublequote close, // we have to change it to a normal doublequote. If not we // insert a language specific doublequote open int startcol = col - m_rightDblQuote.length(); //KILE_DEBUG_MAIN << "startcol=" << startcol << " col=" << col ; if (startcol >= 0 && textline.indexOf(m_rightDblQuote, startcol) == startcol) { doc->removeText(KTextEditor::Range(row, startcol, row, startcol + m_rightDblQuote.length())); doc->insertText(KTextEditor::Cursor(row,startcol), "\""); } else { doc->insertText(KTextEditor::Cursor(row, col), m_leftDblQuote); } } return true; } // Takes an unicode unsigned short and calls insertSpecialCharacter to // insert the proper LaTeX sequence and warn user of any dependencies. //FIXME: there should be one central place to convert unicode chars to LaTeX; // also see 'LaTeXEventFilter::eventFilter'. bool EditorExtension::insertLatexFromUnicode(unsigned short rep, KTextEditor::View *view) { switch(rep) { // Find the unicode decimal representation case 160: return insertSpecialCharacter("~", view); case 161: return insertSpecialCharacter("!`", view); case 162: return insertSpecialCharacter("\\textcent", view, "textcomp"); case 163: return insertSpecialCharacter("\\pounds", view); case 164: return insertSpecialCharacter("\\textcurrency", view, "textcomp"); case 165: return insertSpecialCharacter("\\textyen", view, "textcomp"); case 166: return insertSpecialCharacter("\\textbrokenbar", view, "textcomp"); case 167: return insertSpecialCharacter("\\S", view); case 168: return insertSpecialCharacter("\"", view); case 169: return insertSpecialCharacter("\\copyright", view); case 170: return insertSpecialCharacter("\\textordfeminine", view, "textcomp"); case 171: return insertSpecialCharacter("\\guillemotleft", view); case 172: return insertSpecialCharacter("\\neg", view); // TODO: Check for math case 173: return insertSpecialCharacter("-", view); // TODO: Check for math case 174: return insertSpecialCharacter("\\textregistered", view, "textcomp"); case 176: return insertSpecialCharacter("^\\circ", view); // TODO: Check for math case 177: return insertSpecialCharacter("\\pm", view); // TODO: Check for math case 178: return insertSpecialCharacter("^2", view); // TODO: Check for math case 179: return insertSpecialCharacter("^3", view); // TODO: Check for math case 180: return insertSpecialCharacter("'", view); case 181: return insertSpecialCharacter("\\mu", view); // TODO: Check for math case 182: return insertSpecialCharacter("\\P", view); case 185: return insertSpecialCharacter("^1", view); // TODO: Check for math case 186: return insertSpecialCharacter("\\textordmasculine", view, "textcomp"); case 187: return insertSpecialCharacter("\\guillemotright", view); case 191: return insertSpecialCharacter("?`", view); case 192: return insertSpecialCharacter("\\`A", view); case 193: return insertSpecialCharacter("\\'A", view); case 194: return insertSpecialCharacter("\\^A", view); case 195: return insertSpecialCharacter("\\~A", view); case 196: return insertSpecialCharacter("\\\"A", view); case 197: return insertSpecialCharacter("\\AA", view); case 198: return insertSpecialCharacter("\\AE", view); case 199: return insertSpecialCharacter("\\c{C}", view); case 200: return insertSpecialCharacter("\\`E", view); case 201: return insertSpecialCharacter("\\'E", view); case 202: return insertSpecialCharacter("\\^E", view); case 203: return insertSpecialCharacter("\\\"E", view); case 204: return insertSpecialCharacter("\\`I", view); case 205: return insertSpecialCharacter("\\'I", view); case 206: return insertSpecialCharacter("\\^I", view); case 207: return insertSpecialCharacter("\\\"I", view); case 209: return insertSpecialCharacter("\\~N", view); case 210: return insertSpecialCharacter("\\`O", view); case 211: return insertSpecialCharacter("\\'O", view); case 212: return insertSpecialCharacter("\\^O", view); case 213: return insertSpecialCharacter("\\~O", view); case 214: return insertSpecialCharacter("\\\"O", view); case 215: return insertSpecialCharacter("\\times", view); //TODO: Check for math case 216: return insertSpecialCharacter("\\Oslash", view); case 217: return insertSpecialCharacter("\\`U", view); case 218: return insertSpecialCharacter("\\'U", view); case 219: return insertSpecialCharacter("\\^U", view); case 220: return insertSpecialCharacter("\\\"U", view); case 221: return insertSpecialCharacter("\\'Y", view); case 223: return insertSpecialCharacter("\\ss{}", view); case 224: return insertSpecialCharacter("\\`a", view); case 225: return insertSpecialCharacter("\\'a", view); case 226: return insertSpecialCharacter("\\^a", view); case 227: return insertSpecialCharacter("\\~a", view); case 228: return insertSpecialCharacter("\\\"a", view); case 229: return insertSpecialCharacter("\\aa", view); case 230: return insertSpecialCharacter("\\ae", view); case 231: return insertSpecialCharacter("\\c{c}", view); case 232: return insertSpecialCharacter("\\`e", view); case 233: return insertSpecialCharacter("\\'e", view); case 234: return insertSpecialCharacter("\\^e", view); case 235: return insertSpecialCharacter("\\\"e", view); case 236: return insertSpecialCharacter("\\`i", view); case 237: return insertSpecialCharacter("\\'i", view); case 238: return insertSpecialCharacter("\\^i", view); case 239: return insertSpecialCharacter("\\\"i", view); case 240: return insertSpecialCharacter("\\~o", view); case 241: return insertSpecialCharacter("\\~n", view); case 242: return insertSpecialCharacter("\\`o", view); case 243: return insertSpecialCharacter("\\'o", view); case 244: return insertSpecialCharacter("\\^o", view); case 245: return insertSpecialCharacter("\\~o", view); case 246: return insertSpecialCharacter("\\\"o", view); case 247: return insertSpecialCharacter("\\div", view); case 248: return insertSpecialCharacter("\\oslash", view); case 249: return insertSpecialCharacter("\\`u", view); case 250: return insertSpecialCharacter("\\'u", view); case 251: return insertSpecialCharacter("\\^u", view); case 252: return insertSpecialCharacter("\\\"u", view); case 253: return insertSpecialCharacter("\\'y", view); case 255: return insertSpecialCharacter("\\\"y", view); case 256: return insertSpecialCharacter("\\=A", view); case 257: return insertSpecialCharacter("\\=a", view); case 258: return insertSpecialCharacter("\\uA", view); case 259: return insertSpecialCharacter("\\ua", view); case 262: return insertSpecialCharacter("\\'C", view); case 263: return insertSpecialCharacter("\\'c", view); case 264: return insertSpecialCharacter("\\^C", view); case 265: return insertSpecialCharacter("\\^c", view); case 266: return insertSpecialCharacter("\\.C", view); case 267: return insertSpecialCharacter("\\.c", view); case 268: return insertSpecialCharacter("\\vC", view); case 269: return insertSpecialCharacter("\\vc", view); case 270: return insertSpecialCharacter("\\vD", view); case 271: return insertSpecialCharacter("\\vd", view); case 272: return insertSpecialCharacter("\\=D", view); case 273: return insertSpecialCharacter("\\=d", view); case 274: return insertSpecialCharacter("\\=E", view); case 275: return insertSpecialCharacter("\\=e", view); case 276: return insertSpecialCharacter("\\uE", view); case 277: return insertSpecialCharacter("\\ue", view); case 278: return insertSpecialCharacter("\\.E", view); case 279: return insertSpecialCharacter("\\.e", view); case 282: return insertSpecialCharacter("\\vE", view); case 283: return insertSpecialCharacter("\\ve", view); case 284: return insertSpecialCharacter("\\^G", view); case 285: return insertSpecialCharacter("\\^g", view); case 286: return insertSpecialCharacter("\\uG", view); case 287: return insertSpecialCharacter("\\ug", view); case 288: return insertSpecialCharacter("\\.G", view); case 289: return insertSpecialCharacter("\\.g", view); case 290: return insertSpecialCharacter("\\cG", view); case 291: return insertSpecialCharacter("\\'g", view); case 292: return insertSpecialCharacter("\\^H", view); case 293: return insertSpecialCharacter("\\^h", view); case 294: return insertSpecialCharacter("\\=H", view); case 295: return insertSpecialCharacter("\\=h", view); case 296: return insertSpecialCharacter("\\~I", view); case 297: return insertSpecialCharacter("\\~i", view); case 298: return insertSpecialCharacter("\\=I", view); case 299: return insertSpecialCharacter("\\=i", view); case 300: return insertSpecialCharacter("\\uI", view); case 301: return insertSpecialCharacter("\\ui", view); case 304: return insertSpecialCharacter("\\.I", view); case 305: return insertSpecialCharacter("\\i", view); case 308: return insertSpecialCharacter("\\^J", view); case 309: return insertSpecialCharacter("\\^j", view); case 310: return insertSpecialCharacter("\\cK", view); case 311: return insertSpecialCharacter("\\ck", view); case 313: return insertSpecialCharacter("\\'L", view); case 314: return insertSpecialCharacter("\\'l", view); case 315: return insertSpecialCharacter("\\cL", view); case 316: return insertSpecialCharacter("\\cl", view); case 317: return insertSpecialCharacter("\\vL", view); case 318: return insertSpecialCharacter("\\vl", view); case 323: return insertSpecialCharacter("\\'N", view); case 324: return insertSpecialCharacter("\\'n", view); case 325: return insertSpecialCharacter("\\cN", view); case 326: return insertSpecialCharacter("\\cn", view); case 327: return insertSpecialCharacter("\\vN", view); case 328: return insertSpecialCharacter("\\vn", view); case 332: return insertSpecialCharacter("\\=O", view); case 333: return insertSpecialCharacter("\\=o", view); case 334: return insertSpecialCharacter("\\uO", view); case 335: return insertSpecialCharacter("\\uo", view); case 336: return insertSpecialCharacter("\\HO", view); case 337: return insertSpecialCharacter("\\Ho", view); case 338: return insertSpecialCharacter("\\OE", view); case 339: return insertSpecialCharacter("\\oe", view); case 340: return insertSpecialCharacter("\\'R", view); case 341: return insertSpecialCharacter("\\'r", view); case 342: return insertSpecialCharacter("\\cR", view); case 343: return insertSpecialCharacter("\\cr", view); case 344: return insertSpecialCharacter("\\vR", view); case 345: return insertSpecialCharacter("\\vr", view); case 346: return insertSpecialCharacter("\\'S", view); case 347: return insertSpecialCharacter("\\'s", view); case 348: return insertSpecialCharacter("\\^S", view); case 349: return insertSpecialCharacter("\\^s", view); case 350: return insertSpecialCharacter("\\cS", view); case 351: return insertSpecialCharacter("\\cs", view); case 352: return insertSpecialCharacter("\\vS", view); case 353: return insertSpecialCharacter("\\vs", view); case 354: return insertSpecialCharacter("\\cT", view); case 355: return insertSpecialCharacter("\\ct", view); case 356: return insertSpecialCharacter("\\vT", view); case 357: return insertSpecialCharacter("\\vt", view); case 358: return insertSpecialCharacter("\\=T", view); case 359: return insertSpecialCharacter("\\=t", view); case 360: return insertSpecialCharacter("\\~U", view); case 361: return insertSpecialCharacter("\\~u", view); case 362: return insertSpecialCharacter("\\=U", view); case 363: return insertSpecialCharacter("\\=u", view); case 364: return insertSpecialCharacter("\\uU", view); case 365: return insertSpecialCharacter("\\uu", view); case 366: return insertSpecialCharacter("\\AU", view); case 367: return insertSpecialCharacter("\\Au", view); case 368: return insertSpecialCharacter("\\HU", view); case 369: return insertSpecialCharacter("\\Hu", view); case 370: return insertSpecialCharacter("\\cU", view); case 371: return insertSpecialCharacter("\\cu", view); case 372: return insertSpecialCharacter("\\^W", view); case 373: return insertSpecialCharacter("\\^w", view); case 374: return insertSpecialCharacter("\\^Y", view); case 375: return insertSpecialCharacter("\\^y", view); case 376: return insertSpecialCharacter("\\\"Y", view); case 377: return insertSpecialCharacter("\\'Z", view); case 378: return insertSpecialCharacter("\\'z", view); case 379: return insertSpecialCharacter("\\.Z", view); case 380: return insertSpecialCharacter("\\.z", view); case 381: return insertSpecialCharacter("\\vZ", view); case 382: return insertSpecialCharacter("\\vz", view); default: return false; } } // If allowed, inserts texString at current cursor postition. Startlingly similar to insertDoubleQuotes. bool EditorExtension::insertSpecialCharacter(const QString& texString, KTextEditor::View *view, const QString& dep) { // stop if special character replacement is disabled if (!m_specialCharacters) { return false; } // return false if konsole has focus if(m_ki->texKonsole()->hasFocus()) { return false; } // always return true for event handler view = determineView(view); if(!view) { return true; } KTextEditor::Document *doc = view->document(); // Only change if we have a tex document if(!doc || !m_ki->extensions()->isTexFile(doc->url())) { return false; } // In case of replace view->removeSelectionText(); int row, col; KTextEditor::Cursor cursor = view->cursorPosition(); row = cursor.line(); col = cursor.column(); // insert texString doc->insertText(KTextEditor::Cursor(row, col), texString); KILE_DEBUG_MAIN << "Replacing with "<allPackages(); if(!packagelist.contains(dep)) { m_ki->errorHandler()->printMessage(KileTool::Error, i18n("You have to include the package %1 to use %2.", dep, texString), i18n("Missing Package")); KILE_DEBUG_MAIN << "Need package "<< dep; } } return true; } //////////////////// insert tabulator //////////////////// void EditorExtension::insertIntelligentTabulator(KTextEditor::View *view) { view = determineView(view); if(!view) { return; } int row, col, currentRow, currentCol; QString envname,tab; QString prefix = " "; KTextEditor::Cursor cursor = view->cursorPosition(); currentRow = cursor.line(); currentCol = cursor.column(); if(findOpenedEnvironment(row, col, envname, view)) { // look if this is an environment with tabs tab = m_latexCommands->getTabulator(envname); // try to align tabulator with textline above if(currentRow >= 1) { int tabpos = view->document()->line(currentRow - 1).indexOf('&', currentCol); if(tabpos >= 0) { currentCol = tabpos; prefix.clear(); } } } if(tab.isEmpty()) { tab = '&'; } tab = prefix + tab + ' '; view->document()->insertText(KTextEditor::Cursor(currentRow, currentCol), tab); view->setCursorPosition(KTextEditor::Cursor(currentRow, currentCol + tab.length())); } //////////////////// autocomplete environment //////////////////// // should we complete the current environment (call from LaTeXEventFilter) bool EditorExtension::eventInsertEnvironment(KTextEditor::View *view) { if(!view) { return false; } // don't complete environment, if we are // still working inside the completion box KTextEditor::CodeCompletionInterface *codeCompletionInterface = qobject_cast(view); if(codeCompletionInterface && codeCompletionInterface->isCompletionActive()) { return false; } int row = view->cursorPosition().line(); int col = view->cursorPositionVirtual().column(); QString line = view->document()->line(row).left(col); int pos = m_regexpEnter.indexIn(line); if (pos != -1) { line = m_regexpEnter.cap(1); for(int i = 0; i < line.length(); ++i) { if(!line[i].isSpace()) { line[i] = ' '; } } QString envname, endenv; if(m_regexpEnter.cap(2) == "\\[") { envname = m_regexpEnter.cap(2); endenv = "\\]\n"; } else { envname = m_regexpEnter.cap(4); endenv = m_regexpEnter.cap(2).replace("\\begin","\\end") + '\n'; } if(shouldCompleteEnv(envname, view)) { QString item = m_latexCommands->isListEnv(envname) ? "\\item " : QString(); view->document()->insertText(KTextEditor::Cursor(row, col), '\n' + line + m_envAutoIndent + item + '\n' + line + endenv); view->setCursorPosition(KTextEditor::Cursor(row + 1, line.length() + m_envAutoIndent.length() + item.length())); return true; } } return false; } bool EditorExtension::shouldCompleteEnv(const QString &env, KTextEditor::View *view) { KILE_DEBUG_MAIN << "===EditorExtension::shouldCompleteEnv( " << env << " )==="; QRegExp reTestBegin,reTestEnd; if(env == "\\[") { KILE_DEBUG_MAIN << "display style"; reTestBegin.setPattern("(?:[^\\\\]|^)\\\\\\["); // the first part is a non-capturing bracket (?:...) and we check if we don't have a backslash in front, // or that we are at the begin of the line reTestEnd.setPattern("(?:[^\\\\]|^)\\\\\\]"); } else { reTestBegin.setPattern("(?:[^\\\\]|^)\\\\begin\\s*\\{" + QRegExp::escape(env) + "\\}"); reTestEnd.setPattern("(?:[^\\\\]|^)\\\\end\\s*\\{" + QRegExp::escape(env) + "\\}"); } int num = view->document()->lines(); int numBeginsFound = 0; int numEndsFound = 0; KTextEditor::Cursor cursor = view->cursorPosition(); int realLine = cursor.line(); for(int i = realLine; i < num; ++i) { numBeginsFound += view->document()->line(i).count(reTestBegin); numEndsFound += view->document()->line(i).count(reTestEnd); KILE_DEBUG_MAIN << "line is " << i << " numBeginsFound = " << numBeginsFound << " , " << "numEndsFound = " << numEndsFound; if(numEndsFound >= numBeginsFound) { return false; } else if(numEndsFound == 0 && numBeginsFound > 1) { return true; } else if(numBeginsFound > 2 || numEndsFound > 1) { return true; // terminate the search } } return true; } QString EditorExtension::getWhiteSpace(const QString &s) { QString whitespace = s; for(int i = 0; i < whitespace.length(); ++i) { if(!whitespace[i].isSpace()) { whitespace[i] = ' '; } } return whitespace; } //////////////////// inside verbatim commands //////////////////// bool EditorExtension::insideVerbatim(KTextEditor::View *view) { int rowEnv, colEnv; QString nameEnv; if(findOpenedEnvironment(rowEnv, colEnv, nameEnv, view)) { if(m_latexCommands->isVerbatimEnv(nameEnv)) { return true; } } return false; } bool EditorExtension::insideVerb(KTextEditor::View *view) { view = determineView(view); if(!view) { return false; } // get current position int row, col; KTextEditor::Cursor cursor = view->cursorPosition(); row = cursor.line(); col = cursor.column(); int startpos = 0; QString textline = getTextLineReal(view->document(),row); QRegExp reg("\\\\verb(\\*?)(.)"); while(true) { int pos = textline.indexOf(reg,startpos); if(pos < 0 || col < pos + 6 + reg.cap(1).length()) { return false; } pos = textline.indexOf(reg.cap(2), pos + 6 + reg.cap(1).length()); if(pos < 0 || col <= pos) { return true; } startpos = pos + 1; } } //////////////////// goto sectioning command //////////////////// void EditorExtension::gotoNextSectioning() { gotoSectioning(false); } void EditorExtension::gotoPrevSectioning() { gotoSectioning(true); } void EditorExtension::gotoSectioning(bool backwards, KTextEditor::View *view) { view = determineView(view); if(!view) { return; } int rowFound, colFound; if( view && view->document()->isModified() ){ // after saving, the document structure is the current one, so in this case we don't need to update it m_ki->viewManager()->updateStructure(true); } if(m_ki->structureWidget()->findSectioning(Q_NULLPTR,view->document(), view->cursorPosition().line(), view->cursorPosition().column(), backwards, false, rowFound, colFound)) { view->setCursorPosition(KTextEditor::Cursor(rowFound, colFound)); } } //////////////////// sectioning popup //////////////////// void EditorExtension::sectioningCommand(KileWidget::StructureViewItem *item, int id) { KTextEditor::View *view = determineView(Q_NULLPTR); if(!view) { return; } if(!item) { return; } KTextEditor::Document *doc = view->document(); // try to determine the whole secting // get the start auf the selected sectioning int row, col, row1, col1, row2, col2; row = row1 = item->startline() - 1; col = col1 = item->startcol() - 1; // FIXME tbraun make this more clever, introdoce in kiledocinfo a flag which can be easily queried for that, so that we don' // check, if the document was changed in the meantime QRegExp reg( "\\\\(part|chapter|section|subsection|subsubsection|paragraph|subparagraph)\\*?\\s*(\\{|\\[)" ); QString textline = getTextLineReal(doc,row1); if(reg.indexIn(textline, col1) != col1) { m_ki->errorHandler()->clearMessages(); m_ki->errorHandler()->printMessage(KileTool::Error, i18n("The document was modified and the structure view should be updated, before starting such an operation."), i18n("Structure View Error") ); return; } // increase cursor position and find the following sectioning command if(!increaseCursorPosition(doc, row, col)) { return; } if (!m_ki->structureWidget()->findSectioning(item, doc, row, col, false, true, row2, col2)){ // or the end of the document // if there is a '\end{document} command, we have to exclude it if (!findEndOfDocument(doc, row, col, row2, col2)) { row2 = doc->lines() - 1; col2 = 0; } } // clear selection and make cursor position visible view->removeSelection(); view->setCursorPosition(KTextEditor::Cursor(row1, col1)); QString text; KTextEditor::Document::EditingTransaction transaction(doc); switch (id) { case KileWidget::StructureWidget::SectioningCut: QApplication::clipboard()->setText(doc->text(KTextEditor::Range(row1, col1, row2, col2))); // copy -> clipboard doc->removeText(KTextEditor::Range(row1, col1, row2, col2)); // delete break; case KileWidget::StructureWidget::SectioningCopy: QApplication::clipboard()->setText(doc->text(KTextEditor::Range(row1, col1, row2, col2))); // copy -> clipboard break; case KileWidget::StructureWidget::SectioningPaste: text = QApplication::clipboard()->text(); // clipboard -> text if(!text.isEmpty()) { view->setCursorPosition(KTextEditor::Cursor(row2, col2)); // insert view->insertText(text + '\n'); } break; case KileWidget::StructureWidget::SectioningSelect: view->setSelection(KTextEditor::Range(row1, col1, row2, col2)); // select break; case KileWidget::StructureWidget::SectioningDelete: doc->removeText(KTextEditor::Range(row1, col1, row2, col2)); // delete break; case KileWidget::StructureWidget::SectioningComment: commentLaTeX(doc, KTextEditor::Range(row1, col1, row2, col2)); break; case KileWidget::StructureWidget::SectioningPreview: view->setSelection(KTextEditor::Range(row1, col1, row2, col2)); // quick preview m_ki->quickPreview()->previewSelection(view, false); view->removeSelection(); break; } transaction.finish(); // update structure view, because it has changed if(id == KileWidget::StructureWidget::SectioningDelete || id == KileWidget::StructureWidget::SectioningComment) { m_ki->viewManager()->updateStructure(true); } } bool EditorExtension::findEndOfDocument(KTextEditor::Document *doc, int row, int col, int &rowFound, int &colFound) { KTextEditor::Range documentRange(KTextEditor::Cursor(row, col), doc->documentEnd()); QVector foundRanges = doc->searchText(documentRange, "\\end{document}"); if(foundRanges.size() >= 1) { KTextEditor::Range range = foundRanges.first(); if(range.isValid()) { rowFound = range.start().line(); colFound = range.start().column(); return true; } } return false; } QString EditorExtension::extractIndentationString(KTextEditor::View *view, int line) { KTextEditor::Document* doc = view->document(); if(!doc) { return QString(); } const QString lineString = doc->line(line); int lastWhiteSpaceCharIndex = -1; for(int i = 0; i < lineString.length(); ++i) { if(!lineString[i].isSpace()) { break; } ++lastWhiteSpaceCharIndex; } return lineString.left(lastWhiteSpaceCharIndex + 1); } } diff --git a/src/kiledocmanager.h b/src/kiledocmanager.h index a6a76d9d..c731eae8 100644 --- a/src/kiledocmanager.h +++ b/src/kiledocmanager.h @@ -1,298 +1,298 @@ /************************************************************************** * Copyright (C) 2004 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) * * (C) 2006-2013 by Michel Ludwig (michel.ludwig@kdemail.net) * ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #ifndef KILEDOCUMENTKILEDOCMANAGER_H #define KILEDOCUMENTKILEDOCMANAGER_H #include #include #include #include #include #include #include "kileconstants.h" #include "kileproject.h" #include "widgets/progressdialog.h" class QUrl; class KFileItem; class QProgressDialog; namespace KTextEditor {class Document; class View;} class TemplateItem; class KileInfo; class KileProjectItem; namespace KileParser { class ParserOutput; } namespace KileDocument { class Info; class TextInfo; /** * The design of the document manager is based on the following invariants: * - Several projects can be open simultaneously * - For every URL there can only be at most one associated KileDocument::Info* object, but * there can be several KileProject* items (each one belonging to a different project) * - It is guaranteed that every project item that represents textual data contains a TextInfo* object **/ class Manager : public QObject { Q_OBJECT public: explicit Manager(KileInfo *info, QObject *parent = Q_NULLPTR, const char *name = Q_NULLPTR); ~Manager(); void readConfig(); void writeConfig(); public Q_SLOTS: KTextEditor::View* createNewJScript(); KTextEditor::View* createNewLaTeXDocument(); //files void newDocumentStatus(KTextEditor::Document *doc); /** * Creates a new file on disk. **/ void fileNew(const QUrl&); void fileNewScript(); void fileNew(KileDocument::Type type = LaTeX); void fileSelected(const QUrl&); void fileSelected(const KileProjectItem *item); void fileSelected(const KFileItem& file); void fileOpen(); inline TextInfo* fileOpen(const QString& localFile, const QString& encoding = QString(), int index = -1) { return fileOpen(QUrl::fromLocalFile(localFile), encoding, index); } TextInfo* fileOpen(const QUrl &url, const QString& encoding = QString(), int index = -1); bool fileSave(KTextEditor::View* = Q_NULLPTR); bool fileSaveAs(KTextEditor::View* = Q_NULLPTR); void fileSaveCopyAs(); void saveURL(const QUrl&); bool fileSaveAll(bool disUntitled = false); bool fileCloseAllOthers(KTextEditor::View *view = Q_NULLPTR); bool fileCloseAll(); bool fileClose(const QUrl &url); bool fileClose(KTextEditor::View *view = Q_NULLPTR); bool fileClose(KTextEditor::Document *doc, bool closingproject = false); //templates KTextEditor::View* loadTemplate(TemplateItem*); void createTemplate(); void removeTemplate(); void replaceTemplateVariables(QString &line); //projects void projectNew(); void projectOpen(); /** * @param openProjectItemViews Opens project files in the editor iff openProjectItemViews is set to 'true'. **/ void projectOpen(const QUrl&, int step = 0, int max = 1, bool openProjectItemViews = true); /** * Saves the state of the project, if @param project is zero, the active project is saved. **/ void projectSave(KileProject* project = Q_NULLPTR); void projectAddFiles(const QUrl&); void projectAddFiles(KileProject* project = Q_NULLPTR,const QUrl &url = QUrl()); void toggleArchive(KileProjectItem *); void buildProjectTree(KileProject *project = Q_NULLPTR); void buildProjectTree(const QUrl&); void projectOptions(const QUrl&); void projectOptions(KileProject *project = Q_NULLPTR); bool projectClose(const QUrl &url = QUrl()); bool projectCloseAll(); void projectShow(); void projectRemoveFiles(); void projectShowFiles(); void projectAddFile(QString filename, bool graphics=false); void projectOpenAllFiles(); void projectOpenAllFiles(const QUrl&); KileProject* selectProject(const QString&); void addProject(KileProject *project); void addToProject(const QUrl&); void addToProject(KileProject*, const QUrl&); void removeFromProject(KileProjectItem *item); void storeProjectItem(KileProjectItem *item, KTextEditor::Document *doc); void cleanUpTempFiles(const QUrl &url, bool silent = false); void openDroppedURLs(QDropEvent *e); void reloadXMLOnAllDocumentsAndViews(); void handleParsingComplete(const QUrl &url, KileParser::ParserOutput* output); Q_SIGNALS: void projectTreeChanged(const KileProject*); void closingDocument(KileDocument::Info*); void documentInfoCreated(KileDocument::Info*); void updateStructure(bool needToParse, KileDocument::Info*); void updateModeStatus(); void updateReferences(KileDocument::Info*); void documentModificationStatusChanged(KTextEditor::Document*, bool, KTextEditor::ModificationInterface::ModifiedOnDiskReason); void documentUrlChanged(KTextEditor::Document*); void documentNameChanged(KTextEditor::Document*); void documentReadWriteStateChanged(KTextEditor::Document*); void addToRecentFiles(const QUrl&); void addToRecentProjects(const QUrl&); void removeFromRecentProjects(const QUrl&); void startWizard(); void removeFromProjectView(const QUrl&); void removeFromProjectView(const KileProject*); void removeItemFromProjectView(const KileProjectItem*, bool); void addToProjectView(const QUrl&); void addToProjectView(KileProjectItem *item); void addToProjectView(const KileProject*); void documentSavedAs(KTextEditor::View*, KileDocument::TextInfo*); void projectOpened(KileProject *project); void documentOpened(KileDocument::TextInfo *textInfo); public: bool isOpeningFile(); KTextEditor::Editor* getEditor(); QList projects() { return m_projects; } QList textDocumentInfos() { return m_textInfoList; } KTextEditor::Document* docFor(const QUrl &url); TextInfo* getInfo() const; inline TextInfo* textInfoFor(const QString& localFile) { return textInfoFor(QUrl::fromLocalFile(localFile)); } TextInfo* textInfoFor(const QUrl &url); TextInfo* textInfoFor(KTextEditor::Document* doc) const; QUrl urlFor(TextInfo* textInfo); void updateInfos(); KileProject* projectForMember(const QUrl &memberUrl); KileProject* projectFor(const QUrl &projecturl); KileProject* projectFor(const QString & name); KileProject* activeProject(); bool isProjectOpen(); void updateProjectReferences(KileProject *project); QStringList getProjectFiles(); KileProjectItem* activeProjectItem(); /** * Finds the project item for the file with URL @param url. * @returns a pointer to the project item, 0 if this file does not belong to a project **/ KileProjectItem* itemFor(const QUrl &url, KileProject *project = Q_NULLPTR) const; KileProjectItem* itemFor(TextInfo *docinfo, KileProject *project = Q_NULLPTR) const; KileProjectItem* selectProjectFileItem(const QString &label); QList selectProjectFileItems(const QString &label); /** * The next method returns a list as several projects can be open simultaneously, i.e. * one URL can be associated with several project item belonging to different projects. **/ QList itemsFor(Info *docinfo) const; QList itemsFor(const QUrl &url) const; static const QUrl symlinkFreeURL(const QUrl &url); protected: /** * @param openProjectItemViews Opens project files in the editor iff openProjectItemViews is set to 'true'. **/ void projectOpenItem(KileProjectItem *item, bool openProjectItemViews = true); void createTextInfoForProjectItem(KileProjectItem *item); void trashDoc(TextInfo *docinfo, KTextEditor::Document *doc = Q_NULLPTR); TextInfo* createTextDocumentInfo(KileDocument::Type type, const QUrl &url, const QUrl& baseDirectory = QUrl()); void recreateTextDocumentInfo(TextInfo *oldinfo); /** * Tries to remove and delete a TextInfo object. The TextInfo object will only be deleted if it isn't referenced - * by any project item or if is is only referenced by a project that should be closed. + * by any project item or if it is only referenced by a project that should be closed. * @param closingproject Indicates whether the TextInfo object should be removed as part of a project close * operation. * @warning This method does not close or delete any Kate documents that are associated with the TextInfo object ! **/ bool removeTextDocumentInfo(TextInfo *docinfo, bool closingproject = false); KTextEditor::Document* createDocument(const QUrl &url, TextInfo *docinfo, const QString& encoding, const QString& mode, const QString& highlight); /** * Creates a document with the specified text. * * @param extension The extension of the file that should be created without leading "." **/ KTextEditor::View* createDocumentWithText(const QString& text, KileDocument::Type type = KileDocument::Text, const QString& extension = QString(), const QUrl &baseDirectory = QUrl()); KTextEditor::View* loadText(KileDocument::Type type, const QUrl &url, const QString& encoding = QString(), bool create = true, const QString& mode = QString(), const QString& highlight = QString(), const QString &text = QString(), int index = -1, const QUrl& baseDirectory = QUrl()); KTextEditor::View* loadItem(KileDocument::Type type, KileProjectItem *item, const QString& text = QString(), bool openProjectItemViews = true); QStringList loadTextURLContents(const QUrl &url, const QString& encoding); private: KTextEditor::Editor *m_editor; QList m_textInfoList; KileInfo *m_ki; QList m_projects; QPointer m_progressDialog; unsigned int m_autoSaveLock; bool m_currentlySavingAll, m_currentlyOpeningFile; void dontOpenWarning(KileProjectItem *item, const QString &action, const QString &filetype); void cleanupDocumentInfoForProjectItems(KileDocument::Info *info); void createProgressDialog(); QStringList autosaveWarnings; void loadDocumentAndViewSettings(KileDocument::TextInfo *textInfo); void saveDocumentAndViewSettings(KileDocument::TextInfo *textInfo); KConfigGroup configGroupForDocumentSettings(KTextEditor::Document *doc) const; QString configGroupNameForDocumentSettings(const QUrl &url) const; KConfigGroup configGroupForViewSettings(KTextEditor::Document *doc, int viewIndex) const; QString configGroupNameForViewSettings(const QUrl &url, int viewIndex) const; void deleteDocumentAndViewSettingsGroups(const QUrl &url); }; } #endif