repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
MaxHalford/prince
prince/mca.py
MCA.transform
python
def transform(self, X): utils.validation.check_is_fitted(self, 's_') if self.check_input: utils.check_array(X, dtype=[str, np.number]) return self.row_coordinates(X)
Computes the row principal coordinates of a dataset.
train
https://github.com/MaxHalford/prince/blob/714c9cdfc4d9f8823eabf550a23ad01fe87c50d7/prince/mca.py#L42-L47
null
class MCA(ca.CA): def fit(self, X, y=None): if self.check_input: utils.check_array(X, dtype=[str, np.number]) if not isinstance(X, pd.DataFrame): X = pd.DataFrame(X) n_initial_columns = X.shape[1] # One-hot encode the data self.one_hot_ = one_hot.OneHotEncoder().fit(X) # Apply CA to the indicator matrix super().fit(self.one_hot_.transform(X)) # Compute the total inertia n_new_columns = len(self.one_hot_.column_names_) self.total_inertia_ = (n_new_columns - n_initial_columns) / n_initial_columns return self def row_coordinates(self, X): return super().row_coordinates(self.one_hot_.transform(X)) def column_coordinates(self, X): return super().column_coordinates(self.one_hot_.transform(X)) def plot_coordinates(self, X, ax=None, figsize=(6, 6), x_component=0, y_component=1, show_row_points=True, row_points_size=10, show_row_labels=False, show_column_points=True, column_points_size=30, show_column_labels=False, legend_n_cols=1): """Plot row and column principal coordinates. Args: ax (matplotlib.Axis): A fresh one will be created and returned if not provided. figsize ((float, float)): The desired figure size if `ax` is not provided. x_component (int): Number of the component used for the x-axis. y_component (int): Number of the component used for the y-axis. show_row_points (bool): Whether to show row principal components or not. row_points_size (float): Row principal components point size. show_row_labels (bool): Whether to show row labels or not. show_column_points (bool): Whether to show column principal components or not. column_points_size (float): Column principal components point size. show_column_labels (bool): Whether to show column labels or not. legend_n_cols (int): Number of columns used for the legend. Returns: matplotlib.Axis """ utils.validation.check_is_fitted(self, 'total_inertia_') if ax is None: fig, ax = plt.subplots(figsize=figsize) # Add style ax = plot.stylize_axis(ax) # Plot row principal coordinates if show_row_points or show_row_labels: row_coords = self.row_coordinates(X) if show_row_points: ax.scatter( row_coords.iloc[:, x_component], row_coords.iloc[:, y_component], s=row_points_size, label=None, color=plot.GRAY['dark'], alpha=0.6 ) if show_row_labels: for _, row in row_coords.iterrows(): ax.annotate(row.name, (row[x_component], row[y_component])) # Plot column principal coordinates if show_column_points or show_column_labels: col_coords = self.column_coordinates(X) x = col_coords[x_component] y = col_coords[y_component] prefixes = col_coords.index.str.split('_').map(lambda x: x[0]) for prefix in prefixes.unique(): mask = prefixes == prefix if show_column_points: ax.scatter(x[mask], y[mask], s=column_points_size, label=prefix) if show_column_labels: for i, label in enumerate(col_coords[mask].index): ax.annotate(label, (x[mask][i], y[mask][i])) ax.legend(ncol=legend_n_cols) # Text ax.set_title('Row and column principal coordinates') ei = self.explained_inertia_ ax.set_xlabel('Component {} ({:.2f}% inertia)'.format(x_component, 100 * ei[x_component])) ax.set_ylabel('Component {} ({:.2f}% inertia)'.format(y_component, 100 * ei[y_component])) return ax
MaxHalford/prince
prince/mca.py
MCA.plot_coordinates
python
def plot_coordinates(self, X, ax=None, figsize=(6, 6), x_component=0, y_component=1, show_row_points=True, row_points_size=10, show_row_labels=False, show_column_points=True, column_points_size=30, show_column_labels=False, legend_n_cols=1): utils.validation.check_is_fitted(self, 'total_inertia_') if ax is None: fig, ax = plt.subplots(figsize=figsize) # Add style ax = plot.stylize_axis(ax) # Plot row principal coordinates if show_row_points or show_row_labels: row_coords = self.row_coordinates(X) if show_row_points: ax.scatter( row_coords.iloc[:, x_component], row_coords.iloc[:, y_component], s=row_points_size, label=None, color=plot.GRAY['dark'], alpha=0.6 ) if show_row_labels: for _, row in row_coords.iterrows(): ax.annotate(row.name, (row[x_component], row[y_component])) # Plot column principal coordinates if show_column_points or show_column_labels: col_coords = self.column_coordinates(X) x = col_coords[x_component] y = col_coords[y_component] prefixes = col_coords.index.str.split('_').map(lambda x: x[0]) for prefix in prefixes.unique(): mask = prefixes == prefix if show_column_points: ax.scatter(x[mask], y[mask], s=column_points_size, label=prefix) if show_column_labels: for i, label in enumerate(col_coords[mask].index): ax.annotate(label, (x[mask][i], y[mask][i])) ax.legend(ncol=legend_n_cols) # Text ax.set_title('Row and column principal coordinates') ei = self.explained_inertia_ ax.set_xlabel('Component {} ({:.2f}% inertia)'.format(x_component, 100 * ei[x_component])) ax.set_ylabel('Component {} ({:.2f}% inertia)'.format(y_component, 100 * ei[y_component])) return ax
Plot row and column principal coordinates. Args: ax (matplotlib.Axis): A fresh one will be created and returned if not provided. figsize ((float, float)): The desired figure size if `ax` is not provided. x_component (int): Number of the component used for the x-axis. y_component (int): Number of the component used for the y-axis. show_row_points (bool): Whether to show row principal components or not. row_points_size (float): Row principal components point size. show_row_labels (bool): Whether to show row labels or not. show_column_points (bool): Whether to show column principal components or not. column_points_size (float): Column principal components point size. show_column_labels (bool): Whether to show column labels or not. legend_n_cols (int): Number of columns used for the legend. Returns: matplotlib.Axis
train
https://github.com/MaxHalford/prince/blob/714c9cdfc4d9f8823eabf550a23ad01fe87c50d7/prince/mca.py#L49-L126
[ "def stylize_axis(ax, grid=True):\n\n if grid:\n ax.grid()\n\n ax.xaxis.set_ticks_position('none')\n ax.yaxis.set_ticks_position('none')\n\n ax.axhline(y=0, linestyle='-', linewidth=1.2, color=GRAY['dark'], alpha=0.6)\n ax.axvline(x=0, linestyle='-', linewidth=1.2, color=GRAY['dark'], alpha=0.6)\n\n return ax\n" ]
class MCA(ca.CA): def fit(self, X, y=None): if self.check_input: utils.check_array(X, dtype=[str, np.number]) if not isinstance(X, pd.DataFrame): X = pd.DataFrame(X) n_initial_columns = X.shape[1] # One-hot encode the data self.one_hot_ = one_hot.OneHotEncoder().fit(X) # Apply CA to the indicator matrix super().fit(self.one_hot_.transform(X)) # Compute the total inertia n_new_columns = len(self.one_hot_.column_names_) self.total_inertia_ = (n_new_columns - n_initial_columns) / n_initial_columns return self def row_coordinates(self, X): return super().row_coordinates(self.one_hot_.transform(X)) def column_coordinates(self, X): return super().column_coordinates(self.one_hot_.transform(X)) def transform(self, X): """Computes the row principal coordinates of a dataset.""" utils.validation.check_is_fitted(self, 's_') if self.check_input: utils.check_array(X, dtype=[str, np.number]) return self.row_coordinates(X)
MaxHalford/prince
prince/svd.py
compute_svd
python
def compute_svd(X, n_components, n_iter, random_state, engine): # Determine what SVD engine to use if engine == 'auto': engine = 'sklearn' # Compute the SVD if engine == 'fbpca': if FBPCA_INSTALLED: U, s, V = fbpca.pca(X, k=n_components, n_iter=n_iter) else: raise ValueError('fbpca is not installed; please install it if you want to use it') elif engine == 'sklearn': U, s, V = extmath.randomized_svd( X, n_components=n_components, n_iter=n_iter, random_state=random_state ) else: raise ValueError("engine has to be one of ('auto', 'fbpca', 'sklearn')") U, V = extmath.svd_flip(U, V) return U, s, V
Computes an SVD with k components.
train
https://github.com/MaxHalford/prince/blob/714c9cdfc4d9f8823eabf550a23ad01fe87c50d7/prince/svd.py#L10-L35
null
"""Singular Value Decomposition (SVD)""" try: import fbpca FBPCA_INSTALLED = True except ImportError: FBPCA_INSTALLED = False from sklearn.utils import extmath
MaxHalford/prince
prince/pca.py
PCA.row_coordinates
python
def row_coordinates(self, X): utils.validation.check_is_fitted(self, 's_') # Extract index index = X.index if isinstance(X, pd.DataFrame) else None # Copy data if self.copy: X = np.copy(X) # Scale data if hasattr(self, 'scaler_'): X = self.scaler_.transform(X) return pd.DataFrame(data=X.dot(self.V_.T), index=index)
Returns the row principal coordinates. The row principal coordinates are obtained by projecting `X` on the right eigenvectors.
train
https://github.com/MaxHalford/prince/blob/714c9cdfc4d9f8823eabf550a23ad01fe87c50d7/prince/pca.py#L86-L104
null
class PCA(base.BaseEstimator, base.TransformerMixin): """ Args: rescale_with_mean (bool): Whether to substract each column's mean or not. rescale_with_std (bool): Whether to divide each column by it's standard deviation or not. n_components (int): The number of principal components to compute. n_iter (int): The number of iterations used for computing the SVD. copy (bool): Whether to perform the computations inplace or not. check_input (bool): Whether to check the consistency of the inputs or not. """ def __init__(self, rescale_with_mean=True, rescale_with_std=True, n_components=2, n_iter=3, copy=True, check_input=True, random_state=None, engine='auto'): self.n_components = n_components self.n_iter = n_iter self.rescale_with_mean = rescale_with_mean self.rescale_with_std = rescale_with_std self.copy = copy self.check_input = check_input self.random_state = random_state self.engine = engine def fit(self, X, y=None): # Check input if self.check_input: utils.check_array(X) # Convert pandas DataFrame to numpy array if isinstance(X, pd.DataFrame): X = X.to_numpy(dtype=np.float64) # Copy data if self.copy: X = np.copy(X) # Scale data if self.rescale_with_mean or self.rescale_with_std: self.scaler_ = preprocessing.StandardScaler( copy=False, with_mean=self.rescale_with_mean, with_std=self.rescale_with_std ).fit(X) X = self.scaler_.transform(X) # Compute SVD self.U_, self.s_, self.V_ = svd.compute_svd( X=X, n_components=self.n_components, n_iter=self.n_iter, random_state=self.random_state, engine=self.engine ) # Compute total inertia self.total_inertia_ = np.sum(np.square(X)) return self def transform(self, X): """Computes the row principal coordinates of a dataset. Same as calling `row_coordinates`. In most cases you should be using the same dataset as you did when calling the `fit` method. You might however also want to included supplementary data. """ utils.validation.check_is_fitted(self, 's_') if self.check_input: utils.check_array(X) return self.row_coordinates(X) def row_standard_coordinates(self, X): """Returns the row standard coordinates. The row standard coordinates are obtained by dividing each row principal coordinate by it's associated eigenvalue. """ utils.validation.check_is_fitted(self, 's_') return self.row_coordinates(X).div(self.eigenvalues_, axis='columns') def row_contributions(self, X): """Returns the row contributions towards each principal component. Each row contribution towards each principal component is equivalent to the amount of inertia it contributes. This is calculated by dividing the squared row coordinates by the eigenvalue associated to each principal component. """ utils.validation.check_is_fitted(self, 's_') return np.square(self.row_coordinates(X)).div(self.eigenvalues_, axis='columns') def row_cosine_similarities(self, X): """Returns the cosine similarities between the rows and their principal components. The row cosine similarities are obtained by calculating the cosine of the angle shaped by the row principal coordinates and the row principal components. This is calculated by squaring each row projection coordinate and dividing each squared coordinate by the sum of the squared coordinates, which results in a ratio comprised between 0 and 1 representing the squared cosine. """ utils.validation.check_is_fitted(self, 's_') squared_coordinates = np.square(self.row_coordinates(X)) total_squares = squared_coordinates.sum(axis='columns') return squared_coordinates.div(total_squares, axis='rows') def column_correlations(self, X): """Returns the column correlations with each principal component.""" utils.validation.check_is_fitted(self, 's_') # Convert numpy array to pandas DataFrame if isinstance(X, np.ndarray): X = pd.DataFrame(X) row_pc = self.row_coordinates(X) return pd.DataFrame({ component: { feature: row_pc[component].corr(X[feature]) for feature in X.columns } for component in row_pc.columns }) @property def eigenvalues_(self): """Returns the eigenvalues associated with each principal component.""" utils.validation.check_is_fitted(self, 's_') return np.square(self.s_).tolist() @property def explained_inertia_(self): """Returns the percentage of explained inertia per principal component.""" utils.validation.check_is_fitted(self, 's_') return [eig / self.total_inertia_ for eig in self.eigenvalues_] def plot_row_coordinates(self, X, ax=None, figsize=(6, 6), x_component=0, y_component=1, labels=None, color_labels=None, ellipse_outline=False, ellipse_fill=True, show_points=True, **kwargs): """Plot the row principal coordinates.""" utils.validation.check_is_fitted(self, 's_') if ax is None: fig, ax = plt.subplots(figsize=figsize) # Add style ax = plot.stylize_axis(ax) # Make sure X is a DataFrame if not isinstance(X, pd.DataFrame): X = pd.DataFrame(X) # Retrieve principal coordinates coordinates = self.row_coordinates(X) x = coordinates[x_component].astype(np.float) y = coordinates[y_component].astype(np.float) # Plot if color_labels is None: ax.scatter(x, y, **kwargs) else: for color_label in sorted(list(set(color_labels))): mask = np.array(color_labels) == color_label color = ax._get_lines.get_next_color() # Plot points if show_points: ax.scatter(x[mask], y[mask], color=color, **kwargs, label=color_label) # Plot ellipse if (ellipse_outline or ellipse_fill): x_mean, y_mean, width, height, angle = plot.build_ellipse(x[mask], y[mask]) ax.add_patch(mpl.patches.Ellipse( (x_mean, y_mean), width, height, angle=angle, linewidth=2 if ellipse_outline else 0, color=color, fill=ellipse_fill, alpha=0.2 + (0.3 if not show_points else 0) if ellipse_fill else 1 )) # Add labels if labels is not None: for i, label in enumerate(labels): ax.annotate(label, (x[i], y[i])) # Legend ax.legend() # Text ax.set_title('Row principal coordinates') ei = self.explained_inertia_ ax.set_xlabel('Component {} ({:.2f}% inertia)'.format(x_component, 100 * ei[x_component])) ax.set_ylabel('Component {} ({:.2f}% inertia)'.format(y_component, 100 * ei[y_component])) return ax
MaxHalford/prince
prince/pca.py
PCA.row_standard_coordinates
python
def row_standard_coordinates(self, X): utils.validation.check_is_fitted(self, 's_') return self.row_coordinates(X).div(self.eigenvalues_, axis='columns')
Returns the row standard coordinates. The row standard coordinates are obtained by dividing each row principal coordinate by it's associated eigenvalue.
train
https://github.com/MaxHalford/prince/blob/714c9cdfc4d9f8823eabf550a23ad01fe87c50d7/prince/pca.py#L106-L113
null
class PCA(base.BaseEstimator, base.TransformerMixin): """ Args: rescale_with_mean (bool): Whether to substract each column's mean or not. rescale_with_std (bool): Whether to divide each column by it's standard deviation or not. n_components (int): The number of principal components to compute. n_iter (int): The number of iterations used for computing the SVD. copy (bool): Whether to perform the computations inplace or not. check_input (bool): Whether to check the consistency of the inputs or not. """ def __init__(self, rescale_with_mean=True, rescale_with_std=True, n_components=2, n_iter=3, copy=True, check_input=True, random_state=None, engine='auto'): self.n_components = n_components self.n_iter = n_iter self.rescale_with_mean = rescale_with_mean self.rescale_with_std = rescale_with_std self.copy = copy self.check_input = check_input self.random_state = random_state self.engine = engine def fit(self, X, y=None): # Check input if self.check_input: utils.check_array(X) # Convert pandas DataFrame to numpy array if isinstance(X, pd.DataFrame): X = X.to_numpy(dtype=np.float64) # Copy data if self.copy: X = np.copy(X) # Scale data if self.rescale_with_mean or self.rescale_with_std: self.scaler_ = preprocessing.StandardScaler( copy=False, with_mean=self.rescale_with_mean, with_std=self.rescale_with_std ).fit(X) X = self.scaler_.transform(X) # Compute SVD self.U_, self.s_, self.V_ = svd.compute_svd( X=X, n_components=self.n_components, n_iter=self.n_iter, random_state=self.random_state, engine=self.engine ) # Compute total inertia self.total_inertia_ = np.sum(np.square(X)) return self def transform(self, X): """Computes the row principal coordinates of a dataset. Same as calling `row_coordinates`. In most cases you should be using the same dataset as you did when calling the `fit` method. You might however also want to included supplementary data. """ utils.validation.check_is_fitted(self, 's_') if self.check_input: utils.check_array(X) return self.row_coordinates(X) def row_coordinates(self, X): """Returns the row principal coordinates. The row principal coordinates are obtained by projecting `X` on the right eigenvectors. """ utils.validation.check_is_fitted(self, 's_') # Extract index index = X.index if isinstance(X, pd.DataFrame) else None # Copy data if self.copy: X = np.copy(X) # Scale data if hasattr(self, 'scaler_'): X = self.scaler_.transform(X) return pd.DataFrame(data=X.dot(self.V_.T), index=index) def row_contributions(self, X): """Returns the row contributions towards each principal component. Each row contribution towards each principal component is equivalent to the amount of inertia it contributes. This is calculated by dividing the squared row coordinates by the eigenvalue associated to each principal component. """ utils.validation.check_is_fitted(self, 's_') return np.square(self.row_coordinates(X)).div(self.eigenvalues_, axis='columns') def row_cosine_similarities(self, X): """Returns the cosine similarities between the rows and their principal components. The row cosine similarities are obtained by calculating the cosine of the angle shaped by the row principal coordinates and the row principal components. This is calculated by squaring each row projection coordinate and dividing each squared coordinate by the sum of the squared coordinates, which results in a ratio comprised between 0 and 1 representing the squared cosine. """ utils.validation.check_is_fitted(self, 's_') squared_coordinates = np.square(self.row_coordinates(X)) total_squares = squared_coordinates.sum(axis='columns') return squared_coordinates.div(total_squares, axis='rows') def column_correlations(self, X): """Returns the column correlations with each principal component.""" utils.validation.check_is_fitted(self, 's_') # Convert numpy array to pandas DataFrame if isinstance(X, np.ndarray): X = pd.DataFrame(X) row_pc = self.row_coordinates(X) return pd.DataFrame({ component: { feature: row_pc[component].corr(X[feature]) for feature in X.columns } for component in row_pc.columns }) @property def eigenvalues_(self): """Returns the eigenvalues associated with each principal component.""" utils.validation.check_is_fitted(self, 's_') return np.square(self.s_).tolist() @property def explained_inertia_(self): """Returns the percentage of explained inertia per principal component.""" utils.validation.check_is_fitted(self, 's_') return [eig / self.total_inertia_ for eig in self.eigenvalues_] def plot_row_coordinates(self, X, ax=None, figsize=(6, 6), x_component=0, y_component=1, labels=None, color_labels=None, ellipse_outline=False, ellipse_fill=True, show_points=True, **kwargs): """Plot the row principal coordinates.""" utils.validation.check_is_fitted(self, 's_') if ax is None: fig, ax = plt.subplots(figsize=figsize) # Add style ax = plot.stylize_axis(ax) # Make sure X is a DataFrame if not isinstance(X, pd.DataFrame): X = pd.DataFrame(X) # Retrieve principal coordinates coordinates = self.row_coordinates(X) x = coordinates[x_component].astype(np.float) y = coordinates[y_component].astype(np.float) # Plot if color_labels is None: ax.scatter(x, y, **kwargs) else: for color_label in sorted(list(set(color_labels))): mask = np.array(color_labels) == color_label color = ax._get_lines.get_next_color() # Plot points if show_points: ax.scatter(x[mask], y[mask], color=color, **kwargs, label=color_label) # Plot ellipse if (ellipse_outline or ellipse_fill): x_mean, y_mean, width, height, angle = plot.build_ellipse(x[mask], y[mask]) ax.add_patch(mpl.patches.Ellipse( (x_mean, y_mean), width, height, angle=angle, linewidth=2 if ellipse_outline else 0, color=color, fill=ellipse_fill, alpha=0.2 + (0.3 if not show_points else 0) if ellipse_fill else 1 )) # Add labels if labels is not None: for i, label in enumerate(labels): ax.annotate(label, (x[i], y[i])) # Legend ax.legend() # Text ax.set_title('Row principal coordinates') ei = self.explained_inertia_ ax.set_xlabel('Component {} ({:.2f}% inertia)'.format(x_component, 100 * ei[x_component])) ax.set_ylabel('Component {} ({:.2f}% inertia)'.format(y_component, 100 * ei[y_component])) return ax
MaxHalford/prince
prince/pca.py
PCA.row_contributions
python
def row_contributions(self, X): utils.validation.check_is_fitted(self, 's_') return np.square(self.row_coordinates(X)).div(self.eigenvalues_, axis='columns')
Returns the row contributions towards each principal component. Each row contribution towards each principal component is equivalent to the amount of inertia it contributes. This is calculated by dividing the squared row coordinates by the eigenvalue associated to each principal component.
train
https://github.com/MaxHalford/prince/blob/714c9cdfc4d9f8823eabf550a23ad01fe87c50d7/prince/pca.py#L115-L123
null
class PCA(base.BaseEstimator, base.TransformerMixin): """ Args: rescale_with_mean (bool): Whether to substract each column's mean or not. rescale_with_std (bool): Whether to divide each column by it's standard deviation or not. n_components (int): The number of principal components to compute. n_iter (int): The number of iterations used for computing the SVD. copy (bool): Whether to perform the computations inplace or not. check_input (bool): Whether to check the consistency of the inputs or not. """ def __init__(self, rescale_with_mean=True, rescale_with_std=True, n_components=2, n_iter=3, copy=True, check_input=True, random_state=None, engine='auto'): self.n_components = n_components self.n_iter = n_iter self.rescale_with_mean = rescale_with_mean self.rescale_with_std = rescale_with_std self.copy = copy self.check_input = check_input self.random_state = random_state self.engine = engine def fit(self, X, y=None): # Check input if self.check_input: utils.check_array(X) # Convert pandas DataFrame to numpy array if isinstance(X, pd.DataFrame): X = X.to_numpy(dtype=np.float64) # Copy data if self.copy: X = np.copy(X) # Scale data if self.rescale_with_mean or self.rescale_with_std: self.scaler_ = preprocessing.StandardScaler( copy=False, with_mean=self.rescale_with_mean, with_std=self.rescale_with_std ).fit(X) X = self.scaler_.transform(X) # Compute SVD self.U_, self.s_, self.V_ = svd.compute_svd( X=X, n_components=self.n_components, n_iter=self.n_iter, random_state=self.random_state, engine=self.engine ) # Compute total inertia self.total_inertia_ = np.sum(np.square(X)) return self def transform(self, X): """Computes the row principal coordinates of a dataset. Same as calling `row_coordinates`. In most cases you should be using the same dataset as you did when calling the `fit` method. You might however also want to included supplementary data. """ utils.validation.check_is_fitted(self, 's_') if self.check_input: utils.check_array(X) return self.row_coordinates(X) def row_coordinates(self, X): """Returns the row principal coordinates. The row principal coordinates are obtained by projecting `X` on the right eigenvectors. """ utils.validation.check_is_fitted(self, 's_') # Extract index index = X.index if isinstance(X, pd.DataFrame) else None # Copy data if self.copy: X = np.copy(X) # Scale data if hasattr(self, 'scaler_'): X = self.scaler_.transform(X) return pd.DataFrame(data=X.dot(self.V_.T), index=index) def row_standard_coordinates(self, X): """Returns the row standard coordinates. The row standard coordinates are obtained by dividing each row principal coordinate by it's associated eigenvalue. """ utils.validation.check_is_fitted(self, 's_') return self.row_coordinates(X).div(self.eigenvalues_, axis='columns') def row_cosine_similarities(self, X): """Returns the cosine similarities between the rows and their principal components. The row cosine similarities are obtained by calculating the cosine of the angle shaped by the row principal coordinates and the row principal components. This is calculated by squaring each row projection coordinate and dividing each squared coordinate by the sum of the squared coordinates, which results in a ratio comprised between 0 and 1 representing the squared cosine. """ utils.validation.check_is_fitted(self, 's_') squared_coordinates = np.square(self.row_coordinates(X)) total_squares = squared_coordinates.sum(axis='columns') return squared_coordinates.div(total_squares, axis='rows') def column_correlations(self, X): """Returns the column correlations with each principal component.""" utils.validation.check_is_fitted(self, 's_') # Convert numpy array to pandas DataFrame if isinstance(X, np.ndarray): X = pd.DataFrame(X) row_pc = self.row_coordinates(X) return pd.DataFrame({ component: { feature: row_pc[component].corr(X[feature]) for feature in X.columns } for component in row_pc.columns }) @property def eigenvalues_(self): """Returns the eigenvalues associated with each principal component.""" utils.validation.check_is_fitted(self, 's_') return np.square(self.s_).tolist() @property def explained_inertia_(self): """Returns the percentage of explained inertia per principal component.""" utils.validation.check_is_fitted(self, 's_') return [eig / self.total_inertia_ for eig in self.eigenvalues_] def plot_row_coordinates(self, X, ax=None, figsize=(6, 6), x_component=0, y_component=1, labels=None, color_labels=None, ellipse_outline=False, ellipse_fill=True, show_points=True, **kwargs): """Plot the row principal coordinates.""" utils.validation.check_is_fitted(self, 's_') if ax is None: fig, ax = plt.subplots(figsize=figsize) # Add style ax = plot.stylize_axis(ax) # Make sure X is a DataFrame if not isinstance(X, pd.DataFrame): X = pd.DataFrame(X) # Retrieve principal coordinates coordinates = self.row_coordinates(X) x = coordinates[x_component].astype(np.float) y = coordinates[y_component].astype(np.float) # Plot if color_labels is None: ax.scatter(x, y, **kwargs) else: for color_label in sorted(list(set(color_labels))): mask = np.array(color_labels) == color_label color = ax._get_lines.get_next_color() # Plot points if show_points: ax.scatter(x[mask], y[mask], color=color, **kwargs, label=color_label) # Plot ellipse if (ellipse_outline or ellipse_fill): x_mean, y_mean, width, height, angle = plot.build_ellipse(x[mask], y[mask]) ax.add_patch(mpl.patches.Ellipse( (x_mean, y_mean), width, height, angle=angle, linewidth=2 if ellipse_outline else 0, color=color, fill=ellipse_fill, alpha=0.2 + (0.3 if not show_points else 0) if ellipse_fill else 1 )) # Add labels if labels is not None: for i, label in enumerate(labels): ax.annotate(label, (x[i], y[i])) # Legend ax.legend() # Text ax.set_title('Row principal coordinates') ei = self.explained_inertia_ ax.set_xlabel('Component {} ({:.2f}% inertia)'.format(x_component, 100 * ei[x_component])) ax.set_ylabel('Component {} ({:.2f}% inertia)'.format(y_component, 100 * ei[y_component])) return ax
MaxHalford/prince
prince/pca.py
PCA.row_cosine_similarities
python
def row_cosine_similarities(self, X): utils.validation.check_is_fitted(self, 's_') squared_coordinates = np.square(self.row_coordinates(X)) total_squares = squared_coordinates.sum(axis='columns') return squared_coordinates.div(total_squares, axis='rows')
Returns the cosine similarities between the rows and their principal components. The row cosine similarities are obtained by calculating the cosine of the angle shaped by the row principal coordinates and the row principal components. This is calculated by squaring each row projection coordinate and dividing each squared coordinate by the sum of the squared coordinates, which results in a ratio comprised between 0 and 1 representing the squared cosine.
train
https://github.com/MaxHalford/prince/blob/714c9cdfc4d9f8823eabf550a23ad01fe87c50d7/prince/pca.py#L125-L137
null
class PCA(base.BaseEstimator, base.TransformerMixin): """ Args: rescale_with_mean (bool): Whether to substract each column's mean or not. rescale_with_std (bool): Whether to divide each column by it's standard deviation or not. n_components (int): The number of principal components to compute. n_iter (int): The number of iterations used for computing the SVD. copy (bool): Whether to perform the computations inplace or not. check_input (bool): Whether to check the consistency of the inputs or not. """ def __init__(self, rescale_with_mean=True, rescale_with_std=True, n_components=2, n_iter=3, copy=True, check_input=True, random_state=None, engine='auto'): self.n_components = n_components self.n_iter = n_iter self.rescale_with_mean = rescale_with_mean self.rescale_with_std = rescale_with_std self.copy = copy self.check_input = check_input self.random_state = random_state self.engine = engine def fit(self, X, y=None): # Check input if self.check_input: utils.check_array(X) # Convert pandas DataFrame to numpy array if isinstance(X, pd.DataFrame): X = X.to_numpy(dtype=np.float64) # Copy data if self.copy: X = np.copy(X) # Scale data if self.rescale_with_mean or self.rescale_with_std: self.scaler_ = preprocessing.StandardScaler( copy=False, with_mean=self.rescale_with_mean, with_std=self.rescale_with_std ).fit(X) X = self.scaler_.transform(X) # Compute SVD self.U_, self.s_, self.V_ = svd.compute_svd( X=X, n_components=self.n_components, n_iter=self.n_iter, random_state=self.random_state, engine=self.engine ) # Compute total inertia self.total_inertia_ = np.sum(np.square(X)) return self def transform(self, X): """Computes the row principal coordinates of a dataset. Same as calling `row_coordinates`. In most cases you should be using the same dataset as you did when calling the `fit` method. You might however also want to included supplementary data. """ utils.validation.check_is_fitted(self, 's_') if self.check_input: utils.check_array(X) return self.row_coordinates(X) def row_coordinates(self, X): """Returns the row principal coordinates. The row principal coordinates are obtained by projecting `X` on the right eigenvectors. """ utils.validation.check_is_fitted(self, 's_') # Extract index index = X.index if isinstance(X, pd.DataFrame) else None # Copy data if self.copy: X = np.copy(X) # Scale data if hasattr(self, 'scaler_'): X = self.scaler_.transform(X) return pd.DataFrame(data=X.dot(self.V_.T), index=index) def row_standard_coordinates(self, X): """Returns the row standard coordinates. The row standard coordinates are obtained by dividing each row principal coordinate by it's associated eigenvalue. """ utils.validation.check_is_fitted(self, 's_') return self.row_coordinates(X).div(self.eigenvalues_, axis='columns') def row_contributions(self, X): """Returns the row contributions towards each principal component. Each row contribution towards each principal component is equivalent to the amount of inertia it contributes. This is calculated by dividing the squared row coordinates by the eigenvalue associated to each principal component. """ utils.validation.check_is_fitted(self, 's_') return np.square(self.row_coordinates(X)).div(self.eigenvalues_, axis='columns') def column_correlations(self, X): """Returns the column correlations with each principal component.""" utils.validation.check_is_fitted(self, 's_') # Convert numpy array to pandas DataFrame if isinstance(X, np.ndarray): X = pd.DataFrame(X) row_pc = self.row_coordinates(X) return pd.DataFrame({ component: { feature: row_pc[component].corr(X[feature]) for feature in X.columns } for component in row_pc.columns }) @property def eigenvalues_(self): """Returns the eigenvalues associated with each principal component.""" utils.validation.check_is_fitted(self, 's_') return np.square(self.s_).tolist() @property def explained_inertia_(self): """Returns the percentage of explained inertia per principal component.""" utils.validation.check_is_fitted(self, 's_') return [eig / self.total_inertia_ for eig in self.eigenvalues_] def plot_row_coordinates(self, X, ax=None, figsize=(6, 6), x_component=0, y_component=1, labels=None, color_labels=None, ellipse_outline=False, ellipse_fill=True, show_points=True, **kwargs): """Plot the row principal coordinates.""" utils.validation.check_is_fitted(self, 's_') if ax is None: fig, ax = plt.subplots(figsize=figsize) # Add style ax = plot.stylize_axis(ax) # Make sure X is a DataFrame if not isinstance(X, pd.DataFrame): X = pd.DataFrame(X) # Retrieve principal coordinates coordinates = self.row_coordinates(X) x = coordinates[x_component].astype(np.float) y = coordinates[y_component].astype(np.float) # Plot if color_labels is None: ax.scatter(x, y, **kwargs) else: for color_label in sorted(list(set(color_labels))): mask = np.array(color_labels) == color_label color = ax._get_lines.get_next_color() # Plot points if show_points: ax.scatter(x[mask], y[mask], color=color, **kwargs, label=color_label) # Plot ellipse if (ellipse_outline or ellipse_fill): x_mean, y_mean, width, height, angle = plot.build_ellipse(x[mask], y[mask]) ax.add_patch(mpl.patches.Ellipse( (x_mean, y_mean), width, height, angle=angle, linewidth=2 if ellipse_outline else 0, color=color, fill=ellipse_fill, alpha=0.2 + (0.3 if not show_points else 0) if ellipse_fill else 1 )) # Add labels if labels is not None: for i, label in enumerate(labels): ax.annotate(label, (x[i], y[i])) # Legend ax.legend() # Text ax.set_title('Row principal coordinates') ei = self.explained_inertia_ ax.set_xlabel('Component {} ({:.2f}% inertia)'.format(x_component, 100 * ei[x_component])) ax.set_ylabel('Component {} ({:.2f}% inertia)'.format(y_component, 100 * ei[y_component])) return ax
MaxHalford/prince
prince/pca.py
PCA.column_correlations
python
def column_correlations(self, X): utils.validation.check_is_fitted(self, 's_') # Convert numpy array to pandas DataFrame if isinstance(X, np.ndarray): X = pd.DataFrame(X) row_pc = self.row_coordinates(X) return pd.DataFrame({ component: { feature: row_pc[component].corr(X[feature]) for feature in X.columns } for component in row_pc.columns })
Returns the column correlations with each principal component.
train
https://github.com/MaxHalford/prince/blob/714c9cdfc4d9f8823eabf550a23ad01fe87c50d7/prince/pca.py#L139-L155
null
class PCA(base.BaseEstimator, base.TransformerMixin): """ Args: rescale_with_mean (bool): Whether to substract each column's mean or not. rescale_with_std (bool): Whether to divide each column by it's standard deviation or not. n_components (int): The number of principal components to compute. n_iter (int): The number of iterations used for computing the SVD. copy (bool): Whether to perform the computations inplace or not. check_input (bool): Whether to check the consistency of the inputs or not. """ def __init__(self, rescale_with_mean=True, rescale_with_std=True, n_components=2, n_iter=3, copy=True, check_input=True, random_state=None, engine='auto'): self.n_components = n_components self.n_iter = n_iter self.rescale_with_mean = rescale_with_mean self.rescale_with_std = rescale_with_std self.copy = copy self.check_input = check_input self.random_state = random_state self.engine = engine def fit(self, X, y=None): # Check input if self.check_input: utils.check_array(X) # Convert pandas DataFrame to numpy array if isinstance(X, pd.DataFrame): X = X.to_numpy(dtype=np.float64) # Copy data if self.copy: X = np.copy(X) # Scale data if self.rescale_with_mean or self.rescale_with_std: self.scaler_ = preprocessing.StandardScaler( copy=False, with_mean=self.rescale_with_mean, with_std=self.rescale_with_std ).fit(X) X = self.scaler_.transform(X) # Compute SVD self.U_, self.s_, self.V_ = svd.compute_svd( X=X, n_components=self.n_components, n_iter=self.n_iter, random_state=self.random_state, engine=self.engine ) # Compute total inertia self.total_inertia_ = np.sum(np.square(X)) return self def transform(self, X): """Computes the row principal coordinates of a dataset. Same as calling `row_coordinates`. In most cases you should be using the same dataset as you did when calling the `fit` method. You might however also want to included supplementary data. """ utils.validation.check_is_fitted(self, 's_') if self.check_input: utils.check_array(X) return self.row_coordinates(X) def row_coordinates(self, X): """Returns the row principal coordinates. The row principal coordinates are obtained by projecting `X` on the right eigenvectors. """ utils.validation.check_is_fitted(self, 's_') # Extract index index = X.index if isinstance(X, pd.DataFrame) else None # Copy data if self.copy: X = np.copy(X) # Scale data if hasattr(self, 'scaler_'): X = self.scaler_.transform(X) return pd.DataFrame(data=X.dot(self.V_.T), index=index) def row_standard_coordinates(self, X): """Returns the row standard coordinates. The row standard coordinates are obtained by dividing each row principal coordinate by it's associated eigenvalue. """ utils.validation.check_is_fitted(self, 's_') return self.row_coordinates(X).div(self.eigenvalues_, axis='columns') def row_contributions(self, X): """Returns the row contributions towards each principal component. Each row contribution towards each principal component is equivalent to the amount of inertia it contributes. This is calculated by dividing the squared row coordinates by the eigenvalue associated to each principal component. """ utils.validation.check_is_fitted(self, 's_') return np.square(self.row_coordinates(X)).div(self.eigenvalues_, axis='columns') def row_cosine_similarities(self, X): """Returns the cosine similarities between the rows and their principal components. The row cosine similarities are obtained by calculating the cosine of the angle shaped by the row principal coordinates and the row principal components. This is calculated by squaring each row projection coordinate and dividing each squared coordinate by the sum of the squared coordinates, which results in a ratio comprised between 0 and 1 representing the squared cosine. """ utils.validation.check_is_fitted(self, 's_') squared_coordinates = np.square(self.row_coordinates(X)) total_squares = squared_coordinates.sum(axis='columns') return squared_coordinates.div(total_squares, axis='rows') @property def eigenvalues_(self): """Returns the eigenvalues associated with each principal component.""" utils.validation.check_is_fitted(self, 's_') return np.square(self.s_).tolist() @property def explained_inertia_(self): """Returns the percentage of explained inertia per principal component.""" utils.validation.check_is_fitted(self, 's_') return [eig / self.total_inertia_ for eig in self.eigenvalues_] def plot_row_coordinates(self, X, ax=None, figsize=(6, 6), x_component=0, y_component=1, labels=None, color_labels=None, ellipse_outline=False, ellipse_fill=True, show_points=True, **kwargs): """Plot the row principal coordinates.""" utils.validation.check_is_fitted(self, 's_') if ax is None: fig, ax = plt.subplots(figsize=figsize) # Add style ax = plot.stylize_axis(ax) # Make sure X is a DataFrame if not isinstance(X, pd.DataFrame): X = pd.DataFrame(X) # Retrieve principal coordinates coordinates = self.row_coordinates(X) x = coordinates[x_component].astype(np.float) y = coordinates[y_component].astype(np.float) # Plot if color_labels is None: ax.scatter(x, y, **kwargs) else: for color_label in sorted(list(set(color_labels))): mask = np.array(color_labels) == color_label color = ax._get_lines.get_next_color() # Plot points if show_points: ax.scatter(x[mask], y[mask], color=color, **kwargs, label=color_label) # Plot ellipse if (ellipse_outline or ellipse_fill): x_mean, y_mean, width, height, angle = plot.build_ellipse(x[mask], y[mask]) ax.add_patch(mpl.patches.Ellipse( (x_mean, y_mean), width, height, angle=angle, linewidth=2 if ellipse_outline else 0, color=color, fill=ellipse_fill, alpha=0.2 + (0.3 if not show_points else 0) if ellipse_fill else 1 )) # Add labels if labels is not None: for i, label in enumerate(labels): ax.annotate(label, (x[i], y[i])) # Legend ax.legend() # Text ax.set_title('Row principal coordinates') ei = self.explained_inertia_ ax.set_xlabel('Component {} ({:.2f}% inertia)'.format(x_component, 100 * ei[x_component])) ax.set_ylabel('Component {} ({:.2f}% inertia)'.format(y_component, 100 * ei[y_component])) return ax
MaxHalford/prince
prince/pca.py
PCA.plot_row_coordinates
python
def plot_row_coordinates(self, X, ax=None, figsize=(6, 6), x_component=0, y_component=1, labels=None, color_labels=None, ellipse_outline=False, ellipse_fill=True, show_points=True, **kwargs): utils.validation.check_is_fitted(self, 's_') if ax is None: fig, ax = plt.subplots(figsize=figsize) # Add style ax = plot.stylize_axis(ax) # Make sure X is a DataFrame if not isinstance(X, pd.DataFrame): X = pd.DataFrame(X) # Retrieve principal coordinates coordinates = self.row_coordinates(X) x = coordinates[x_component].astype(np.float) y = coordinates[y_component].astype(np.float) # Plot if color_labels is None: ax.scatter(x, y, **kwargs) else: for color_label in sorted(list(set(color_labels))): mask = np.array(color_labels) == color_label color = ax._get_lines.get_next_color() # Plot points if show_points: ax.scatter(x[mask], y[mask], color=color, **kwargs, label=color_label) # Plot ellipse if (ellipse_outline or ellipse_fill): x_mean, y_mean, width, height, angle = plot.build_ellipse(x[mask], y[mask]) ax.add_patch(mpl.patches.Ellipse( (x_mean, y_mean), width, height, angle=angle, linewidth=2 if ellipse_outline else 0, color=color, fill=ellipse_fill, alpha=0.2 + (0.3 if not show_points else 0) if ellipse_fill else 1 )) # Add labels if labels is not None: for i, label in enumerate(labels): ax.annotate(label, (x[i], y[i])) # Legend ax.legend() # Text ax.set_title('Row principal coordinates') ei = self.explained_inertia_ ax.set_xlabel('Component {} ({:.2f}% inertia)'.format(x_component, 100 * ei[x_component])) ax.set_ylabel('Component {} ({:.2f}% inertia)'.format(y_component, 100 * ei[y_component])) return ax
Plot the row principal coordinates.
train
https://github.com/MaxHalford/prince/blob/714c9cdfc4d9f8823eabf550a23ad01fe87c50d7/prince/pca.py#L169-L228
[ "def stylize_axis(ax, grid=True):\n\n if grid:\n ax.grid()\n\n ax.xaxis.set_ticks_position('none')\n ax.yaxis.set_ticks_position('none')\n\n ax.axhline(y=0, linestyle='-', linewidth=1.2, color=GRAY['dark'], alpha=0.6)\n ax.axvline(x=0, linestyle='-', linewidth=1.2, color=GRAY['dark'], alpha=0.6)\n\n return ax\n", "def build_ellipse(X, Y):\n \"\"\"Construct ellipse coordinates from two arrays of numbers.\n\n Args:\n X (1D array_like)\n Y (1D array_like)\n\n Returns:\n float: The mean of `X`.\n float: The mean of `Y`.\n float: The width of the ellipse.\n float: The height of the ellipse.\n float: The angle of orientation of the ellipse.\n\n \"\"\"\n x_mean = np.mean(X)\n y_mean = np.mean(Y)\n\n cov_matrix = np.cov(np.vstack((X, Y)))\n U, s, V = linalg.svd(cov_matrix, full_matrices=False)\n\n chi_95 = np.sqrt(4.61) # 90% quantile of the chi-square distribution\n width = np.sqrt(cov_matrix[0][0]) * chi_95 * 2\n height = np.sqrt(cov_matrix[1][1]) * chi_95 * 2\n\n eigenvector = V.T[0]\n angle = np.arctan(eigenvector[1] / eigenvector[0])\n\n return x_mean, y_mean, width, height, angle\n" ]
class PCA(base.BaseEstimator, base.TransformerMixin): """ Args: rescale_with_mean (bool): Whether to substract each column's mean or not. rescale_with_std (bool): Whether to divide each column by it's standard deviation or not. n_components (int): The number of principal components to compute. n_iter (int): The number of iterations used for computing the SVD. copy (bool): Whether to perform the computations inplace or not. check_input (bool): Whether to check the consistency of the inputs or not. """ def __init__(self, rescale_with_mean=True, rescale_with_std=True, n_components=2, n_iter=3, copy=True, check_input=True, random_state=None, engine='auto'): self.n_components = n_components self.n_iter = n_iter self.rescale_with_mean = rescale_with_mean self.rescale_with_std = rescale_with_std self.copy = copy self.check_input = check_input self.random_state = random_state self.engine = engine def fit(self, X, y=None): # Check input if self.check_input: utils.check_array(X) # Convert pandas DataFrame to numpy array if isinstance(X, pd.DataFrame): X = X.to_numpy(dtype=np.float64) # Copy data if self.copy: X = np.copy(X) # Scale data if self.rescale_with_mean or self.rescale_with_std: self.scaler_ = preprocessing.StandardScaler( copy=False, with_mean=self.rescale_with_mean, with_std=self.rescale_with_std ).fit(X) X = self.scaler_.transform(X) # Compute SVD self.U_, self.s_, self.V_ = svd.compute_svd( X=X, n_components=self.n_components, n_iter=self.n_iter, random_state=self.random_state, engine=self.engine ) # Compute total inertia self.total_inertia_ = np.sum(np.square(X)) return self def transform(self, X): """Computes the row principal coordinates of a dataset. Same as calling `row_coordinates`. In most cases you should be using the same dataset as you did when calling the `fit` method. You might however also want to included supplementary data. """ utils.validation.check_is_fitted(self, 's_') if self.check_input: utils.check_array(X) return self.row_coordinates(X) def row_coordinates(self, X): """Returns the row principal coordinates. The row principal coordinates are obtained by projecting `X` on the right eigenvectors. """ utils.validation.check_is_fitted(self, 's_') # Extract index index = X.index if isinstance(X, pd.DataFrame) else None # Copy data if self.copy: X = np.copy(X) # Scale data if hasattr(self, 'scaler_'): X = self.scaler_.transform(X) return pd.DataFrame(data=X.dot(self.V_.T), index=index) def row_standard_coordinates(self, X): """Returns the row standard coordinates. The row standard coordinates are obtained by dividing each row principal coordinate by it's associated eigenvalue. """ utils.validation.check_is_fitted(self, 's_') return self.row_coordinates(X).div(self.eigenvalues_, axis='columns') def row_contributions(self, X): """Returns the row contributions towards each principal component. Each row contribution towards each principal component is equivalent to the amount of inertia it contributes. This is calculated by dividing the squared row coordinates by the eigenvalue associated to each principal component. """ utils.validation.check_is_fitted(self, 's_') return np.square(self.row_coordinates(X)).div(self.eigenvalues_, axis='columns') def row_cosine_similarities(self, X): """Returns the cosine similarities between the rows and their principal components. The row cosine similarities are obtained by calculating the cosine of the angle shaped by the row principal coordinates and the row principal components. This is calculated by squaring each row projection coordinate and dividing each squared coordinate by the sum of the squared coordinates, which results in a ratio comprised between 0 and 1 representing the squared cosine. """ utils.validation.check_is_fitted(self, 's_') squared_coordinates = np.square(self.row_coordinates(X)) total_squares = squared_coordinates.sum(axis='columns') return squared_coordinates.div(total_squares, axis='rows') def column_correlations(self, X): """Returns the column correlations with each principal component.""" utils.validation.check_is_fitted(self, 's_') # Convert numpy array to pandas DataFrame if isinstance(X, np.ndarray): X = pd.DataFrame(X) row_pc = self.row_coordinates(X) return pd.DataFrame({ component: { feature: row_pc[component].corr(X[feature]) for feature in X.columns } for component in row_pc.columns }) @property def eigenvalues_(self): """Returns the eigenvalues associated with each principal component.""" utils.validation.check_is_fitted(self, 's_') return np.square(self.s_).tolist() @property def explained_inertia_(self): """Returns the percentage of explained inertia per principal component.""" utils.validation.check_is_fitted(self, 's_') return [eig / self.total_inertia_ for eig in self.eigenvalues_]
MaxHalford/prince
prince/plot.py
build_ellipse
python
def build_ellipse(X, Y): x_mean = np.mean(X) y_mean = np.mean(Y) cov_matrix = np.cov(np.vstack((X, Y))) U, s, V = linalg.svd(cov_matrix, full_matrices=False) chi_95 = np.sqrt(4.61) # 90% quantile of the chi-square distribution width = np.sqrt(cov_matrix[0][0]) * chi_95 * 2 height = np.sqrt(cov_matrix[1][1]) * chi_95 * 2 eigenvector = V.T[0] angle = np.arctan(eigenvector[1] / eigenvector[0]) return x_mean, y_mean, width, height, angle
Construct ellipse coordinates from two arrays of numbers. Args: X (1D array_like) Y (1D array_like) Returns: float: The mean of `X`. float: The mean of `Y`. float: The width of the ellipse. float: The height of the ellipse. float: The angle of orientation of the ellipse.
train
https://github.com/MaxHalford/prince/blob/714c9cdfc4d9f8823eabf550a23ad01fe87c50d7/prince/plot.py#L27-L55
null
from collections import OrderedDict import numpy as np from scipy import linalg GRAY = OrderedDict([ ('light', '#bababa'), ('dark', '#404040') ]) def stylize_axis(ax, grid=True): if grid: ax.grid() ax.xaxis.set_ticks_position('none') ax.yaxis.set_ticks_position('none') ax.axhline(y=0, linestyle='-', linewidth=1.2, color=GRAY['dark'], alpha=0.6) ax.axvline(x=0, linestyle='-', linewidth=1.2, color=GRAY['dark'], alpha=0.6) return ax
westonplatter/fast_arrow
fast_arrow/resources/option.py
Option.fetch_list
python
def fetch_list(cls, client, ids): results = [] request_url = "https://api.robinhood.com/options/instruments/" for _ids in chunked_list(ids, 50): params = {"ids": ",".join(_ids)} data = client.get(request_url, params=params) partial_results = data["results"] while data["next"]: data = client.get(data["next"]) partial_results.extend(data["results"]) results.extend(partial_results) return results
fetch instruments by ids
train
https://github.com/westonplatter/fast_arrow/blob/514cbca4994f52a97222058167830a302e313d04/fast_arrow/resources/option.py#L44-L62
[ "def chunked_list(_list, _chunk_size=50):\n \"\"\"\n Break lists into small lists for processing:w\n \"\"\"\n for i in range(0, len(_list), _chunk_size):\n yield _list[i:i + _chunk_size]\n" ]
class Option(object): @classmethod def fetch_by_url(cls, client, url): return cls.instrument_by_urls(client, [url]) @classmethod def fetch_by_urls(cls, client, urls): raise NotImplementedError("Option.instrument_by_url") @classmethod def fetch_by_ids(cls, client, ids): results = [] params = {"ids": ",".join(ids)} request_url = "https://api.robinhood.com/options/instruments/" data = client.get(request_url, params=params) results = data["results"] while data["next"]: data = client.get(data["next"]) results.extend(data["results"]) return results @classmethod def fetch_by_id(cls, bearer, _id): return cls.fetch_by_ids(bearer, [_id]) # deprecate me @classmethod def fetch(cls, client, _id): """ fetch by instrument id """ return cls.fetch_list(client, [_id])[0] # # @TODO depricate me # @classmethod @classmethod def in_chain(cls, client, chain_id, expiration_dates=[]): """ fetch all option instruments in an options chain - expiration_dates = optionally scope """ request_url = "https://api.robinhood.com/options/instruments/" params = { "chain_id": chain_id, "expiration_dates": ",".join(expiration_dates) } data = client.get(request_url, params=params) results = data['results'] while data['next']: data = client.get(data['next']) results.extend(data['results']) return results @classmethod def mergein_marketdata_list(cls, client, options): ids = [x["id"] for x in options] mds = OptionMarketdata.quotes_by_instrument_ids(client, ids) mds = [x for x in mds if x] results = [] for o in options: # @TODO optimize this so it's better than O(n^2) md = [md for md in mds if md['instrument'] == o['url']] if len(md) > 0: md = md[0] # there is no overlap in keys, so it's fine to do a merge merged_dict = dict(list(o.items()) + list(md.items())) else: merged_dict = dict(list(o.items())) results.append(merged_dict) return results
westonplatter/fast_arrow
fast_arrow/resources/option.py
Option.in_chain
python
def in_chain(cls, client, chain_id, expiration_dates=[]): request_url = "https://api.robinhood.com/options/instruments/" params = { "chain_id": chain_id, "expiration_dates": ",".join(expiration_dates) } data = client.get(request_url, params=params) results = data['results'] while data['next']: data = client.get(data['next']) results.extend(data['results']) return results
fetch all option instruments in an options chain - expiration_dates = optionally scope
train
https://github.com/westonplatter/fast_arrow/blob/514cbca4994f52a97222058167830a302e313d04/fast_arrow/resources/option.py#L65-L83
[ "def get(self, url=None, params=None, retry=True):\n '''\n Execute HTTP GET\n '''\n headers = self._gen_headers(self.access_token, url)\n attempts = 1\n while attempts <= HTTP_ATTEMPTS_MAX:\n try:\n res = requests.get(url,\n headers=headers,\n params=params,\n timeout=15,\n verify=self.certs)\n res.raise_for_status()\n return res.json()\n except requests.exceptions.RequestException as e:\n attempts += 1\n if res.status_code in [400]:\n raise e\n elif retry and res.status_code in [403]:\n self.relogin_oauth2()\n" ]
class Option(object): @classmethod def fetch_by_url(cls, client, url): return cls.instrument_by_urls(client, [url]) @classmethod def fetch_by_urls(cls, client, urls): raise NotImplementedError("Option.instrument_by_url") @classmethod def fetch_by_ids(cls, client, ids): results = [] params = {"ids": ",".join(ids)} request_url = "https://api.robinhood.com/options/instruments/" data = client.get(request_url, params=params) results = data["results"] while data["next"]: data = client.get(data["next"]) results.extend(data["results"]) return results @classmethod def fetch_by_id(cls, bearer, _id): return cls.fetch_by_ids(bearer, [_id]) # deprecate me @classmethod def fetch(cls, client, _id): """ fetch by instrument id """ return cls.fetch_list(client, [_id])[0] # # @TODO depricate me # @classmethod def fetch_list(cls, client, ids): """ fetch instruments by ids """ results = [] request_url = "https://api.robinhood.com/options/instruments/" for _ids in chunked_list(ids, 50): params = {"ids": ",".join(_ids)} data = client.get(request_url, params=params) partial_results = data["results"] while data["next"]: data = client.get(data["next"]) partial_results.extend(data["results"]) results.extend(partial_results) return results @classmethod @classmethod def mergein_marketdata_list(cls, client, options): ids = [x["id"] for x in options] mds = OptionMarketdata.quotes_by_instrument_ids(client, ids) mds = [x for x in mds if x] results = [] for o in options: # @TODO optimize this so it's better than O(n^2) md = [md for md in mds if md['instrument'] == o['url']] if len(md) > 0: md = md[0] # there is no overlap in keys, so it's fine to do a merge merged_dict = dict(list(o.items()) + list(md.items())) else: merged_dict = dict(list(o.items())) results.append(merged_dict) return results
westonplatter/fast_arrow
fast_arrow/resources/option_order.py
OptionOrder.unroll_option_legs
python
def unroll_option_legs(cls, client, option_orders): ''' unroll option orders like this, https://github.com/joshfraser/robinhood-to-csv/blob/master/csv-options-export.py ''' # # @TODO write this with python threats to make concurrent HTTP requests # results = [] for oo in option_orders: for index, leg in enumerate(oo['legs']): for execution in leg['executions']: order = dict() keys_in_question = ['legs', 'price', 'type', 'premium', 'processed_premium', 'response_category', 'cancel_url'] for k, v in oo.items(): if k not in keys_in_question: order[k] = oo[k] order['order_type'] = oo['type'] contract = client.get(leg['option']) order['leg'] = index+1 order['symbol'] = contract['chain_symbol'] order['strike_price'] = contract['strike_price'] order['expiration_date'] = contract['expiration_date'] order['contract_type'] = contract['type'] for k, v in leg.items(): if k not in ['id', 'executions']: order[k] = leg[k] coef = (-1.0 if leg['side'] == 'buy' else 1.0) order['price'] = float(execution['price']) * 100.0 * coef order['execution_id'] = execution['id'] results.append(order) return results
unroll option orders like this, https://github.com/joshfraser/robinhood-to-csv/blob/master/csv-options-export.py
train
https://github.com/westonplatter/fast_arrow/blob/514cbca4994f52a97222058167830a302e313d04/fast_arrow/resources/option_order.py#L53-L95
[ "def get(self, url=None, params=None, retry=True):\n '''\n Execute HTTP GET\n '''\n headers = self._gen_headers(self.access_token, url)\n attempts = 1\n while attempts <= HTTP_ATTEMPTS_MAX:\n try:\n res = requests.get(url,\n headers=headers,\n params=params,\n timeout=15,\n verify=self.certs)\n res.raise_for_status()\n return res.json()\n except requests.exceptions.RequestException as e:\n attempts += 1\n if res.status_code in [400]:\n raise e\n elif retry and res.status_code in [403]:\n self.relogin_oauth2()\n" ]
class OptionOrder(object): @classmethod def all(cls, client, **kwargs): """ fetch all option positions """ max_date = kwargs['max_date'] if 'max_date' in kwargs else None max_fetches = \ kwargs['max_fetches'] if 'max_fetches' in kwargs else None url = 'https://api.robinhood.com/options/orders/' data = client.get(url) results = data["results"] if is_max_date_gt(max_date, results[-1]['updated_at'][0:10]): return results if max_fetches == 1: return results fetches = 1 while data["next"]: fetches = fetches + 1 data = client.get(data["next"]) results.extend(data["results"]) if is_max_date_gt(max_date, results[-1]['updated_at'][0:10]): return results if max_fetches and (fetches >= max_fetches): return results return results @classmethod def humanize_numbers(cls, option_orders): results = [] for oo in option_orders: keys_to_humanize = ["processed_premium"] coef = (1.0 if oo["direction"] == "credit" else -1.0) for k in keys_to_humanize: if oo[k] is None: continue oo[k] = float(oo[k]) * coef results.append(oo) return results @classmethod @classmethod def submit(cls, client, direction, legs, price, quantity, time_in_force, trigger, order_type, run_validations=True): ''' params: - client - direction - legs - price - quantity - time_in_force - trigger - order_type - run_validations. default = True ''' if run_validations: assert(direction in ["debit", "credit"]) assert(type(price) is str) assert(type(quantity) is int) assert(time_in_force in ["gfd", "gtc"]) assert(trigger in ["immediate"]) assert(order_type in ["limit", "market"]) assert(cls._validate_legs(legs) is True) payload = json.dumps({ "account": client.account_url, "direction": direction, "legs": legs, "price": price, "quantity": quantity, "time_in_force": time_in_force, "trigger": trigger, "type": order_type, "override_day_trade_checks": False, "override_dtbp_checks": False, "ref_id": str(uuid.uuid4()) }) request_url = "https://api.robinhood.com/options/orders/" data = client.post(request_url, payload=payload) return data @classmethod def _validate_legs(cls, legs): for leg in legs: assert("option" in leg) assert(leg["position_effect"] in ["open", "close"]) # @TODO research required formatting # assert(leg["ratio_quantity"]) assert(leg["side"] in ["buy", "sell"]) return True @classmethod def get(cls, client, option_order_id): request_url = \ "https://api.robinhood.com/options/orders/{}/".format( option_order_id) return client.get(request_url) @classmethod def cancel(cls, client, cancel_url): result = client.post(cancel_url) if result == {}: return True else: return False @classmethod def replace(cls, client, option_order, new_price): result = cls.cancel(client, option_order["cancel_url"]) if not result: msg = "OptionOrder.replace() did not cancel previous OptionOrder" raise TradeExecutionError(msg) payload = json.dumps({ "account": client.account_url, "direction": option_order["direction"], "legs": option_order["legs"], "price": new_price, "quantity": option_order["quantity"], "time_in_force": option_order["time_in_force"], "trigger": option_order["trigger"], "type": option_order["type"], "override_day_trade_checks": False, "override_dtbp_checks": False, "ref_id": str(uuid.uuid4()) }) request_url = "https://api.robinhood.com/options/orders/" data = client.post(request_url, payload=payload) return data
westonplatter/fast_arrow
fast_arrow/resources/option_order.py
OptionOrder.submit
python
def submit(cls, client, direction, legs, price, quantity, time_in_force, trigger, order_type, run_validations=True): ''' params: - client - direction - legs - price - quantity - time_in_force - trigger - order_type - run_validations. default = True ''' if run_validations: assert(direction in ["debit", "credit"]) assert(type(price) is str) assert(type(quantity) is int) assert(time_in_force in ["gfd", "gtc"]) assert(trigger in ["immediate"]) assert(order_type in ["limit", "market"]) assert(cls._validate_legs(legs) is True) payload = json.dumps({ "account": client.account_url, "direction": direction, "legs": legs, "price": price, "quantity": quantity, "time_in_force": time_in_force, "trigger": trigger, "type": order_type, "override_day_trade_checks": False, "override_dtbp_checks": False, "ref_id": str(uuid.uuid4()) }) request_url = "https://api.robinhood.com/options/orders/" data = client.post(request_url, payload=payload) return data
params: - client - direction - legs - price - quantity - time_in_force - trigger - order_type - run_validations. default = True
train
https://github.com/westonplatter/fast_arrow/blob/514cbca4994f52a97222058167830a302e313d04/fast_arrow/resources/option_order.py#L98-L138
[ "def post(self, url=None, payload=None, retry=True):\n '''\n Execute HTTP POST\n '''\n headers = self._gen_headers(self.access_token, url)\n attempts = 1\n while attempts <= HTTP_ATTEMPTS_MAX:\n try:\n res = requests.post(url, headers=headers, data=payload,\n timeout=15, verify=self.certs)\n res.raise_for_status()\n if res.headers['Content-Length'] == '0':\n return None\n else:\n return res.json()\n except requests.exceptions.RequestException as e:\n attempts += 1\n if res.status_code in [400, 429]:\n raise e\n elif retry and res.status_code in [403]:\n self.relogin_oauth2()\n", "def _validate_legs(cls, legs):\n for leg in legs:\n assert(\"option\" in leg)\n assert(leg[\"position_effect\"] in [\"open\", \"close\"])\n\n # @TODO research required formatting\n # assert(leg[\"ratio_quantity\"])\n\n assert(leg[\"side\"] in [\"buy\", \"sell\"])\n return True\n" ]
class OptionOrder(object): @classmethod def all(cls, client, **kwargs): """ fetch all option positions """ max_date = kwargs['max_date'] if 'max_date' in kwargs else None max_fetches = \ kwargs['max_fetches'] if 'max_fetches' in kwargs else None url = 'https://api.robinhood.com/options/orders/' data = client.get(url) results = data["results"] if is_max_date_gt(max_date, results[-1]['updated_at'][0:10]): return results if max_fetches == 1: return results fetches = 1 while data["next"]: fetches = fetches + 1 data = client.get(data["next"]) results.extend(data["results"]) if is_max_date_gt(max_date, results[-1]['updated_at'][0:10]): return results if max_fetches and (fetches >= max_fetches): return results return results @classmethod def humanize_numbers(cls, option_orders): results = [] for oo in option_orders: keys_to_humanize = ["processed_premium"] coef = (1.0 if oo["direction"] == "credit" else -1.0) for k in keys_to_humanize: if oo[k] is None: continue oo[k] = float(oo[k]) * coef results.append(oo) return results @classmethod def unroll_option_legs(cls, client, option_orders): ''' unroll option orders like this, https://github.com/joshfraser/robinhood-to-csv/blob/master/csv-options-export.py ''' # # @TODO write this with python threats to make concurrent HTTP requests # results = [] for oo in option_orders: for index, leg in enumerate(oo['legs']): for execution in leg['executions']: order = dict() keys_in_question = ['legs', 'price', 'type', 'premium', 'processed_premium', 'response_category', 'cancel_url'] for k, v in oo.items(): if k not in keys_in_question: order[k] = oo[k] order['order_type'] = oo['type'] contract = client.get(leg['option']) order['leg'] = index+1 order['symbol'] = contract['chain_symbol'] order['strike_price'] = contract['strike_price'] order['expiration_date'] = contract['expiration_date'] order['contract_type'] = contract['type'] for k, v in leg.items(): if k not in ['id', 'executions']: order[k] = leg[k] coef = (-1.0 if leg['side'] == 'buy' else 1.0) order['price'] = float(execution['price']) * 100.0 * coef order['execution_id'] = execution['id'] results.append(order) return results @classmethod @classmethod def _validate_legs(cls, legs): for leg in legs: assert("option" in leg) assert(leg["position_effect"] in ["open", "close"]) # @TODO research required formatting # assert(leg["ratio_quantity"]) assert(leg["side"] in ["buy", "sell"]) return True @classmethod def get(cls, client, option_order_id): request_url = \ "https://api.robinhood.com/options/orders/{}/".format( option_order_id) return client.get(request_url) @classmethod def cancel(cls, client, cancel_url): result = client.post(cancel_url) if result == {}: return True else: return False @classmethod def replace(cls, client, option_order, new_price): result = cls.cancel(client, option_order["cancel_url"]) if not result: msg = "OptionOrder.replace() did not cancel previous OptionOrder" raise TradeExecutionError(msg) payload = json.dumps({ "account": client.account_url, "direction": option_order["direction"], "legs": option_order["legs"], "price": new_price, "quantity": option_order["quantity"], "time_in_force": option_order["time_in_force"], "trigger": option_order["trigger"], "type": option_order["type"], "override_day_trade_checks": False, "override_dtbp_checks": False, "ref_id": str(uuid.uuid4()) }) request_url = "https://api.robinhood.com/options/orders/" data = client.post(request_url, payload=payload) return data
westonplatter/fast_arrow
fast_arrow/option_strategies/iron_condor.py
IronCondor.generate_by_deltas
python
def generate_by_deltas(cls, options, width, put_inner_lte_delta, call_inner_lte_delta): raise Exception("Not Implemented starting at the 0.3.0 release") # # put credit spread # put_options_unsorted = list( filter(lambda x: x['type'] == 'put', options)) put_options = cls.sort_by_strike_price(put_options_unsorted) deltas_as_strings = [x['delta'] for x in put_options] deltas = cls.strings_to_np_array(deltas_as_strings) put_inner_index = np.argmin(deltas >= put_inner_lte_delta) - 1 put_outer_index = put_inner_index - width put_inner_leg = cls.gen_leg( put_options[put_inner_index]["instrument"], "sell") put_outer_leg = cls.gen_leg( put_options[put_outer_index]["instrument"], "buy") # # call credit spread # call_options_unsorted = list( filter(lambda x: x['type'] == 'call', options)) call_options = cls.sort_by_strike_price(call_options_unsorted) deltas_as_strings = [x['delta'] for x in call_options] x = np.array(deltas_as_strings) deltas = x.astype(np.float) # because deep ITM call options have a delta that comes up as NaN, # but are approximately 0.99 or 1.0, I'm replacing Nan with 1.0 # so np.argmax is able to walk up the index until it finds # "call_inner_lte_delta" # @TODO change this so (put credit / call credit) spreads work the same where_are_NaNs = np.isnan(deltas) deltas[where_are_NaNs] = 1.0 call_inner_index = np.argmax(deltas <= call_inner_lte_delta) call_outer_index = call_inner_index + width call_inner_leg = cls.gen_leg( call_options[call_inner_index]["instrument"], "sell") call_outer_leg = cls.gen_leg( call_options[call_outer_index]["instrument"], "buy") legs = [put_outer_leg, put_inner_leg, call_inner_leg, call_outer_leg] # # price calcs # price = ( - Decimal(put_options[put_outer_index]['adjusted_mark_price']) + Decimal(put_options[put_inner_index]['adjusted_mark_price']) + Decimal(call_options[call_inner_index]['adjusted_mark_price']) - Decimal(call_options[call_outer_index]['adjusted_mark_price']) ) # # provide max bid ask spread diff # ic_options = [ put_options[put_outer_index], put_options[put_inner_index], call_options[call_inner_index], call_options[call_outer_index] ] max_bid_ask_spread = cls.max_bid_ask_spread(ic_options) return {"legs": legs, "price": price, "max_bid_ask_spread": max_bid_ask_spread}
totally just playing around ideas for the API. this IC sells - credit put spread - credit call spread the approach - set width for the wing spread (eg, 1, ie, 1 unit width spread) - set delta for inner leg of the put credit spread (eg, -0.2) - set delta for inner leg of the call credit spread (eg, 0.1)
train
https://github.com/westonplatter/fast_arrow/blob/514cbca4994f52a97222058167830a302e313d04/fast_arrow/option_strategies/iron_condor.py#L41-L127
null
class IronCondor(object): @classmethod def sort_by_strike_price(cls, options): return sorted(options, key=(lambda x: x['strike_price'])) @classmethod def gen_leg(cls, option_url, side, position_effect="open", ratio_quantity=1): assert side in ["buy", "sell"] assert position_effect in ["open", "close"] return { "side": side, "option": option_url, "position_effect": position_effect, "ratio_quantity": ratio_quantity } @classmethod def max_bid_ask_spread(cls, ic_options): max_spread = Decimal(0.0) for x in ic_options: ask = Decimal(x["ask_price"]) bid = Decimal(x["bid_price"]) spread = ask - bid if spread > max_spread: max_spread = spread return float(max_spread) @classmethod def strings_to_np_array(cls, strings): x = np.array(strings) deltas = x.astype(np.float) return np.nan_to_num(deltas) @classmethod
westonplatter/fast_arrow
fast_arrow/resources/option_chain.py
OptionChain.fetch
python
def fetch(cls, client, _id, symbol): url = "https://api.robinhood.com/options/chains/" params = { "equity_instrument_ids": _id, "state": "active", "tradability": "tradable" } data = client.get(url, params=params) def filter_func(x): return x["symbol"] == symbol results = list(filter(filter_func, data["results"])) return results[0]
fetch option chain for instrument
train
https://github.com/westonplatter/fast_arrow/blob/514cbca4994f52a97222058167830a302e313d04/fast_arrow/resources/option_chain.py#L4-L19
[ "def get(self, url=None, params=None, retry=True):\n '''\n Execute HTTP GET\n '''\n headers = self._gen_headers(self.access_token, url)\n attempts = 1\n while attempts <= HTTP_ATTEMPTS_MAX:\n try:\n res = requests.get(url,\n headers=headers,\n params=params,\n timeout=15,\n verify=self.certs)\n res.raise_for_status()\n return res.json()\n except requests.exceptions.RequestException as e:\n attempts += 1\n if res.status_code in [400]:\n raise e\n elif retry and res.status_code in [403]:\n self.relogin_oauth2()\n" ]
class OptionChain(object): @classmethod
westonplatter/fast_arrow
fast_arrow/client.py
Client.authenticate
python
def authenticate(self): ''' Authenticate using data in `options` ''' if "username" in self.options and "password" in self.options: self.login_oauth2( self.options["username"], self.options["password"], self.options.get('mfa_code')) elif "access_token" in self.options: if "refresh_token" in self.options: self.access_token = self.options["access_token"] self.refresh_token = self.options["refresh_token"] self.__set_account_info() else: self.authenticated = False return self.authenticated
Authenticate using data in `options`
train
https://github.com/westonplatter/fast_arrow/blob/514cbca4994f52a97222058167830a302e313d04/fast_arrow/client.py#L27-L43
[ "def login_oauth2(self, username, password, mfa_code=None):\n '''\n Login using username and password\n '''\n data = {\n \"grant_type\": \"password\",\n \"scope\": \"internal\",\n \"client_id\": CLIENT_ID,\n \"expires_in\": 86400,\n \"password\": password,\n \"username\": username\n }\n if mfa_code is not None:\n data['mfa_code'] = mfa_code\n url = \"https://api.robinhood.com/oauth2/token/\"\n res = self.post(url, payload=data, retry=False)\n\n if res is None:\n if mfa_code is None:\n msg = (\"Client.login_oauth2(). Could not authenticate. Check \"\n + \"username and password.\")\n raise AuthenticationError(msg)\n else:\n msg = (\"Client.login_oauth2(). Could not authenticate. Check\" +\n \"username and password, and enter a valid MFA code.\")\n raise AuthenticationError(msg)\n elif res.get('mfa_required') is True:\n msg = \"Client.login_oauth2(). Couldn't authenticate. MFA required.\"\n raise AuthenticationError(msg)\n\n self.access_token = res[\"access_token\"]\n self.refresh_token = res[\"refresh_token\"]\n self.mfa_code = res[\"mfa_code\"]\n self.scope = res[\"scope\"]\n self.__set_account_info()\n return self.authenticated\n", "def __set_account_info(self):\n account_urls = Account.all_urls(self)\n if len(account_urls) > 1:\n msg = (\"fast_arrow 'currently' does not handle \" +\n \"multiple account authentication.\")\n raise NotImplementedError(msg)\n elif len(account_urls) == 0:\n msg = \"fast_arrow expected at least 1 account.\"\n raise AuthenticationError(msg)\n else:\n self.account_url = account_urls[0]\n self.account_id = get_last_path(self.account_url)\n self.authenticated = True\n" ]
class Client(object): def __init__(self, **kwargs): self.options = kwargs self.account_id = None self.account_url = None self.access_token = None self.refresh_token = None self.mfa_code = None self.scope = None self.authenticated = False self.certs = os.path.join( os.path.dirname(__file__), 'ssl_certs/certs.pem') def get(self, url=None, params=None, retry=True): ''' Execute HTTP GET ''' headers = self._gen_headers(self.access_token, url) attempts = 1 while attempts <= HTTP_ATTEMPTS_MAX: try: res = requests.get(url, headers=headers, params=params, timeout=15, verify=self.certs) res.raise_for_status() return res.json() except requests.exceptions.RequestException as e: attempts += 1 if res.status_code in [400]: raise e elif retry and res.status_code in [403]: self.relogin_oauth2() def post(self, url=None, payload=None, retry=True): ''' Execute HTTP POST ''' headers = self._gen_headers(self.access_token, url) attempts = 1 while attempts <= HTTP_ATTEMPTS_MAX: try: res = requests.post(url, headers=headers, data=payload, timeout=15, verify=self.certs) res.raise_for_status() if res.headers['Content-Length'] == '0': return None else: return res.json() except requests.exceptions.RequestException as e: attempts += 1 if res.status_code in [400, 429]: raise e elif retry and res.status_code in [403]: self.relogin_oauth2() def _gen_headers(self, bearer, url): ''' Generate headders, adding in Oauth2 bearer token if present ''' headers = { "Accept": "*/*", "Accept-Encoding": "gzip, deflate", "Accept-Language": ("en;q=1, fr;q=0.9, de;q=0.8, ja;q=0.7, " + "nl;q=0.6, it;q=0.5"), "User-Agent": ("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) " + "AppleWebKit/537.36 (KHTML, like Gecko) " + "Chrome/68.0.3440.106 Safari/537.36"), } if bearer: headers["Authorization"] = "Bearer {0}".format(bearer) if url == "https://api.robinhood.com/options/orders/": headers["Content-Type"] = "application/json; charset=utf-8" return headers def login_oauth2(self, username, password, mfa_code=None): ''' Login using username and password ''' data = { "grant_type": "password", "scope": "internal", "client_id": CLIENT_ID, "expires_in": 86400, "password": password, "username": username } if mfa_code is not None: data['mfa_code'] = mfa_code url = "https://api.robinhood.com/oauth2/token/" res = self.post(url, payload=data, retry=False) if res is None: if mfa_code is None: msg = ("Client.login_oauth2(). Could not authenticate. Check " + "username and password.") raise AuthenticationError(msg) else: msg = ("Client.login_oauth2(). Could not authenticate. Check" + "username and password, and enter a valid MFA code.") raise AuthenticationError(msg) elif res.get('mfa_required') is True: msg = "Client.login_oauth2(). Couldn't authenticate. MFA required." raise AuthenticationError(msg) self.access_token = res["access_token"] self.refresh_token = res["refresh_token"] self.mfa_code = res["mfa_code"] self.scope = res["scope"] self.__set_account_info() return self.authenticated def __set_account_info(self): account_urls = Account.all_urls(self) if len(account_urls) > 1: msg = ("fast_arrow 'currently' does not handle " + "multiple account authentication.") raise NotImplementedError(msg) elif len(account_urls) == 0: msg = "fast_arrow expected at least 1 account." raise AuthenticationError(msg) else: self.account_url = account_urls[0] self.account_id = get_last_path(self.account_url) self.authenticated = True def relogin_oauth2(self): ''' (Re)login using the Oauth2 refresh token ''' url = "https://api.robinhood.com/oauth2/token/" data = { "grant_type": "refresh_token", "refresh_token": self.refresh_token, "scope": "internal", "client_id": CLIENT_ID, "expires_in": 86400, } res = self.post(url, payload=data, retry=False) self.access_token = res["access_token"] self.refresh_token = res["refresh_token"] self.mfa_code = res["mfa_code"] self.scope = res["scope"] def logout_oauth2(self): ''' Logout for given Oauth2 bearer token ''' url = "https://api.robinhood.com/oauth2/revoke_token/" data = { "client_id": CLIENT_ID, "token": self.refresh_token, } res = self.post(url, payload=data) if res is None: self.account_id = None self.account_url = None self.access_token = None self.refresh_token = None self.mfa_code = None self.scope = None self.authenticated = False return True else: raise AuthenticationError("fast_arrow could not log out.")
westonplatter/fast_arrow
fast_arrow/client.py
Client.get
python
def get(self, url=None, params=None, retry=True): ''' Execute HTTP GET ''' headers = self._gen_headers(self.access_token, url) attempts = 1 while attempts <= HTTP_ATTEMPTS_MAX: try: res = requests.get(url, headers=headers, params=params, timeout=15, verify=self.certs) res.raise_for_status() return res.json() except requests.exceptions.RequestException as e: attempts += 1 if res.status_code in [400]: raise e elif retry and res.status_code in [403]: self.relogin_oauth2()
Execute HTTP GET
train
https://github.com/westonplatter/fast_arrow/blob/514cbca4994f52a97222058167830a302e313d04/fast_arrow/client.py#L45-L65
[ "def _gen_headers(self, bearer, url):\n '''\n Generate headders, adding in Oauth2 bearer token if present\n '''\n headers = {\n \"Accept\": \"*/*\",\n \"Accept-Encoding\": \"gzip, deflate\",\n \"Accept-Language\": (\"en;q=1, fr;q=0.9, de;q=0.8, ja;q=0.7, \" +\n \"nl;q=0.6, it;q=0.5\"),\n \"User-Agent\": (\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) \" +\n \"AppleWebKit/537.36 (KHTML, like Gecko) \" +\n \"Chrome/68.0.3440.106 Safari/537.36\"),\n\n }\n if bearer:\n headers[\"Authorization\"] = \"Bearer {0}\".format(bearer)\n if url == \"https://api.robinhood.com/options/orders/\":\n headers[\"Content-Type\"] = \"application/json; charset=utf-8\"\n return headers\n", "def relogin_oauth2(self):\n '''\n (Re)login using the Oauth2 refresh token\n '''\n url = \"https://api.robinhood.com/oauth2/token/\"\n data = {\n \"grant_type\": \"refresh_token\",\n \"refresh_token\": self.refresh_token,\n \"scope\": \"internal\",\n \"client_id\": CLIENT_ID,\n \"expires_in\": 86400,\n }\n res = self.post(url, payload=data, retry=False)\n self.access_token = res[\"access_token\"]\n self.refresh_token = res[\"refresh_token\"]\n self.mfa_code = res[\"mfa_code\"]\n self.scope = res[\"scope\"]\n" ]
class Client(object): def __init__(self, **kwargs): self.options = kwargs self.account_id = None self.account_url = None self.access_token = None self.refresh_token = None self.mfa_code = None self.scope = None self.authenticated = False self.certs = os.path.join( os.path.dirname(__file__), 'ssl_certs/certs.pem') def authenticate(self): ''' Authenticate using data in `options` ''' if "username" in self.options and "password" in self.options: self.login_oauth2( self.options["username"], self.options["password"], self.options.get('mfa_code')) elif "access_token" in self.options: if "refresh_token" in self.options: self.access_token = self.options["access_token"] self.refresh_token = self.options["refresh_token"] self.__set_account_info() else: self.authenticated = False return self.authenticated def post(self, url=None, payload=None, retry=True): ''' Execute HTTP POST ''' headers = self._gen_headers(self.access_token, url) attempts = 1 while attempts <= HTTP_ATTEMPTS_MAX: try: res = requests.post(url, headers=headers, data=payload, timeout=15, verify=self.certs) res.raise_for_status() if res.headers['Content-Length'] == '0': return None else: return res.json() except requests.exceptions.RequestException as e: attempts += 1 if res.status_code in [400, 429]: raise e elif retry and res.status_code in [403]: self.relogin_oauth2() def _gen_headers(self, bearer, url): ''' Generate headders, adding in Oauth2 bearer token if present ''' headers = { "Accept": "*/*", "Accept-Encoding": "gzip, deflate", "Accept-Language": ("en;q=1, fr;q=0.9, de;q=0.8, ja;q=0.7, " + "nl;q=0.6, it;q=0.5"), "User-Agent": ("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) " + "AppleWebKit/537.36 (KHTML, like Gecko) " + "Chrome/68.0.3440.106 Safari/537.36"), } if bearer: headers["Authorization"] = "Bearer {0}".format(bearer) if url == "https://api.robinhood.com/options/orders/": headers["Content-Type"] = "application/json; charset=utf-8" return headers def login_oauth2(self, username, password, mfa_code=None): ''' Login using username and password ''' data = { "grant_type": "password", "scope": "internal", "client_id": CLIENT_ID, "expires_in": 86400, "password": password, "username": username } if mfa_code is not None: data['mfa_code'] = mfa_code url = "https://api.robinhood.com/oauth2/token/" res = self.post(url, payload=data, retry=False) if res is None: if mfa_code is None: msg = ("Client.login_oauth2(). Could not authenticate. Check " + "username and password.") raise AuthenticationError(msg) else: msg = ("Client.login_oauth2(). Could not authenticate. Check" + "username and password, and enter a valid MFA code.") raise AuthenticationError(msg) elif res.get('mfa_required') is True: msg = "Client.login_oauth2(). Couldn't authenticate. MFA required." raise AuthenticationError(msg) self.access_token = res["access_token"] self.refresh_token = res["refresh_token"] self.mfa_code = res["mfa_code"] self.scope = res["scope"] self.__set_account_info() return self.authenticated def __set_account_info(self): account_urls = Account.all_urls(self) if len(account_urls) > 1: msg = ("fast_arrow 'currently' does not handle " + "multiple account authentication.") raise NotImplementedError(msg) elif len(account_urls) == 0: msg = "fast_arrow expected at least 1 account." raise AuthenticationError(msg) else: self.account_url = account_urls[0] self.account_id = get_last_path(self.account_url) self.authenticated = True def relogin_oauth2(self): ''' (Re)login using the Oauth2 refresh token ''' url = "https://api.robinhood.com/oauth2/token/" data = { "grant_type": "refresh_token", "refresh_token": self.refresh_token, "scope": "internal", "client_id": CLIENT_ID, "expires_in": 86400, } res = self.post(url, payload=data, retry=False) self.access_token = res["access_token"] self.refresh_token = res["refresh_token"] self.mfa_code = res["mfa_code"] self.scope = res["scope"] def logout_oauth2(self): ''' Logout for given Oauth2 bearer token ''' url = "https://api.robinhood.com/oauth2/revoke_token/" data = { "client_id": CLIENT_ID, "token": self.refresh_token, } res = self.post(url, payload=data) if res is None: self.account_id = None self.account_url = None self.access_token = None self.refresh_token = None self.mfa_code = None self.scope = None self.authenticated = False return True else: raise AuthenticationError("fast_arrow could not log out.")
westonplatter/fast_arrow
fast_arrow/client.py
Client._gen_headers
python
def _gen_headers(self, bearer, url): ''' Generate headders, adding in Oauth2 bearer token if present ''' headers = { "Accept": "*/*", "Accept-Encoding": "gzip, deflate", "Accept-Language": ("en;q=1, fr;q=0.9, de;q=0.8, ja;q=0.7, " + "nl;q=0.6, it;q=0.5"), "User-Agent": ("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) " + "AppleWebKit/537.36 (KHTML, like Gecko) " + "Chrome/68.0.3440.106 Safari/537.36"), } if bearer: headers["Authorization"] = "Bearer {0}".format(bearer) if url == "https://api.robinhood.com/options/orders/": headers["Content-Type"] = "application/json; charset=utf-8" return headers
Generate headders, adding in Oauth2 bearer token if present
train
https://github.com/westonplatter/fast_arrow/blob/514cbca4994f52a97222058167830a302e313d04/fast_arrow/client.py#L89-L107
null
class Client(object): def __init__(self, **kwargs): self.options = kwargs self.account_id = None self.account_url = None self.access_token = None self.refresh_token = None self.mfa_code = None self.scope = None self.authenticated = False self.certs = os.path.join( os.path.dirname(__file__), 'ssl_certs/certs.pem') def authenticate(self): ''' Authenticate using data in `options` ''' if "username" in self.options and "password" in self.options: self.login_oauth2( self.options["username"], self.options["password"], self.options.get('mfa_code')) elif "access_token" in self.options: if "refresh_token" in self.options: self.access_token = self.options["access_token"] self.refresh_token = self.options["refresh_token"] self.__set_account_info() else: self.authenticated = False return self.authenticated def get(self, url=None, params=None, retry=True): ''' Execute HTTP GET ''' headers = self._gen_headers(self.access_token, url) attempts = 1 while attempts <= HTTP_ATTEMPTS_MAX: try: res = requests.get(url, headers=headers, params=params, timeout=15, verify=self.certs) res.raise_for_status() return res.json() except requests.exceptions.RequestException as e: attempts += 1 if res.status_code in [400]: raise e elif retry and res.status_code in [403]: self.relogin_oauth2() def post(self, url=None, payload=None, retry=True): ''' Execute HTTP POST ''' headers = self._gen_headers(self.access_token, url) attempts = 1 while attempts <= HTTP_ATTEMPTS_MAX: try: res = requests.post(url, headers=headers, data=payload, timeout=15, verify=self.certs) res.raise_for_status() if res.headers['Content-Length'] == '0': return None else: return res.json() except requests.exceptions.RequestException as e: attempts += 1 if res.status_code in [400, 429]: raise e elif retry and res.status_code in [403]: self.relogin_oauth2() def login_oauth2(self, username, password, mfa_code=None): ''' Login using username and password ''' data = { "grant_type": "password", "scope": "internal", "client_id": CLIENT_ID, "expires_in": 86400, "password": password, "username": username } if mfa_code is not None: data['mfa_code'] = mfa_code url = "https://api.robinhood.com/oauth2/token/" res = self.post(url, payload=data, retry=False) if res is None: if mfa_code is None: msg = ("Client.login_oauth2(). Could not authenticate. Check " + "username and password.") raise AuthenticationError(msg) else: msg = ("Client.login_oauth2(). Could not authenticate. Check" + "username and password, and enter a valid MFA code.") raise AuthenticationError(msg) elif res.get('mfa_required') is True: msg = "Client.login_oauth2(). Couldn't authenticate. MFA required." raise AuthenticationError(msg) self.access_token = res["access_token"] self.refresh_token = res["refresh_token"] self.mfa_code = res["mfa_code"] self.scope = res["scope"] self.__set_account_info() return self.authenticated def __set_account_info(self): account_urls = Account.all_urls(self) if len(account_urls) > 1: msg = ("fast_arrow 'currently' does not handle " + "multiple account authentication.") raise NotImplementedError(msg) elif len(account_urls) == 0: msg = "fast_arrow expected at least 1 account." raise AuthenticationError(msg) else: self.account_url = account_urls[0] self.account_id = get_last_path(self.account_url) self.authenticated = True def relogin_oauth2(self): ''' (Re)login using the Oauth2 refresh token ''' url = "https://api.robinhood.com/oauth2/token/" data = { "grant_type": "refresh_token", "refresh_token": self.refresh_token, "scope": "internal", "client_id": CLIENT_ID, "expires_in": 86400, } res = self.post(url, payload=data, retry=False) self.access_token = res["access_token"] self.refresh_token = res["refresh_token"] self.mfa_code = res["mfa_code"] self.scope = res["scope"] def logout_oauth2(self): ''' Logout for given Oauth2 bearer token ''' url = "https://api.robinhood.com/oauth2/revoke_token/" data = { "client_id": CLIENT_ID, "token": self.refresh_token, } res = self.post(url, payload=data) if res is None: self.account_id = None self.account_url = None self.access_token = None self.refresh_token = None self.mfa_code = None self.scope = None self.authenticated = False return True else: raise AuthenticationError("fast_arrow could not log out.")
westonplatter/fast_arrow
fast_arrow/client.py
Client.login_oauth2
python
def login_oauth2(self, username, password, mfa_code=None): ''' Login using username and password ''' data = { "grant_type": "password", "scope": "internal", "client_id": CLIENT_ID, "expires_in": 86400, "password": password, "username": username } if mfa_code is not None: data['mfa_code'] = mfa_code url = "https://api.robinhood.com/oauth2/token/" res = self.post(url, payload=data, retry=False) if res is None: if mfa_code is None: msg = ("Client.login_oauth2(). Could not authenticate. Check " + "username and password.") raise AuthenticationError(msg) else: msg = ("Client.login_oauth2(). Could not authenticate. Check" + "username and password, and enter a valid MFA code.") raise AuthenticationError(msg) elif res.get('mfa_required') is True: msg = "Client.login_oauth2(). Couldn't authenticate. MFA required." raise AuthenticationError(msg) self.access_token = res["access_token"] self.refresh_token = res["refresh_token"] self.mfa_code = res["mfa_code"] self.scope = res["scope"] self.__set_account_info() return self.authenticated
Login using username and password
train
https://github.com/westonplatter/fast_arrow/blob/514cbca4994f52a97222058167830a302e313d04/fast_arrow/client.py#L109-L144
[ "def post(self, url=None, payload=None, retry=True):\n '''\n Execute HTTP POST\n '''\n headers = self._gen_headers(self.access_token, url)\n attempts = 1\n while attempts <= HTTP_ATTEMPTS_MAX:\n try:\n res = requests.post(url, headers=headers, data=payload,\n timeout=15, verify=self.certs)\n res.raise_for_status()\n if res.headers['Content-Length'] == '0':\n return None\n else:\n return res.json()\n except requests.exceptions.RequestException as e:\n attempts += 1\n if res.status_code in [400, 429]:\n raise e\n elif retry and res.status_code in [403]:\n self.relogin_oauth2()\n", "def __set_account_info(self):\n account_urls = Account.all_urls(self)\n if len(account_urls) > 1:\n msg = (\"fast_arrow 'currently' does not handle \" +\n \"multiple account authentication.\")\n raise NotImplementedError(msg)\n elif len(account_urls) == 0:\n msg = \"fast_arrow expected at least 1 account.\"\n raise AuthenticationError(msg)\n else:\n self.account_url = account_urls[0]\n self.account_id = get_last_path(self.account_url)\n self.authenticated = True\n" ]
class Client(object): def __init__(self, **kwargs): self.options = kwargs self.account_id = None self.account_url = None self.access_token = None self.refresh_token = None self.mfa_code = None self.scope = None self.authenticated = False self.certs = os.path.join( os.path.dirname(__file__), 'ssl_certs/certs.pem') def authenticate(self): ''' Authenticate using data in `options` ''' if "username" in self.options and "password" in self.options: self.login_oauth2( self.options["username"], self.options["password"], self.options.get('mfa_code')) elif "access_token" in self.options: if "refresh_token" in self.options: self.access_token = self.options["access_token"] self.refresh_token = self.options["refresh_token"] self.__set_account_info() else: self.authenticated = False return self.authenticated def get(self, url=None, params=None, retry=True): ''' Execute HTTP GET ''' headers = self._gen_headers(self.access_token, url) attempts = 1 while attempts <= HTTP_ATTEMPTS_MAX: try: res = requests.get(url, headers=headers, params=params, timeout=15, verify=self.certs) res.raise_for_status() return res.json() except requests.exceptions.RequestException as e: attempts += 1 if res.status_code in [400]: raise e elif retry and res.status_code in [403]: self.relogin_oauth2() def post(self, url=None, payload=None, retry=True): ''' Execute HTTP POST ''' headers = self._gen_headers(self.access_token, url) attempts = 1 while attempts <= HTTP_ATTEMPTS_MAX: try: res = requests.post(url, headers=headers, data=payload, timeout=15, verify=self.certs) res.raise_for_status() if res.headers['Content-Length'] == '0': return None else: return res.json() except requests.exceptions.RequestException as e: attempts += 1 if res.status_code in [400, 429]: raise e elif retry and res.status_code in [403]: self.relogin_oauth2() def _gen_headers(self, bearer, url): ''' Generate headders, adding in Oauth2 bearer token if present ''' headers = { "Accept": "*/*", "Accept-Encoding": "gzip, deflate", "Accept-Language": ("en;q=1, fr;q=0.9, de;q=0.8, ja;q=0.7, " + "nl;q=0.6, it;q=0.5"), "User-Agent": ("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) " + "AppleWebKit/537.36 (KHTML, like Gecko) " + "Chrome/68.0.3440.106 Safari/537.36"), } if bearer: headers["Authorization"] = "Bearer {0}".format(bearer) if url == "https://api.robinhood.com/options/orders/": headers["Content-Type"] = "application/json; charset=utf-8" return headers def __set_account_info(self): account_urls = Account.all_urls(self) if len(account_urls) > 1: msg = ("fast_arrow 'currently' does not handle " + "multiple account authentication.") raise NotImplementedError(msg) elif len(account_urls) == 0: msg = "fast_arrow expected at least 1 account." raise AuthenticationError(msg) else: self.account_url = account_urls[0] self.account_id = get_last_path(self.account_url) self.authenticated = True def relogin_oauth2(self): ''' (Re)login using the Oauth2 refresh token ''' url = "https://api.robinhood.com/oauth2/token/" data = { "grant_type": "refresh_token", "refresh_token": self.refresh_token, "scope": "internal", "client_id": CLIENT_ID, "expires_in": 86400, } res = self.post(url, payload=data, retry=False) self.access_token = res["access_token"] self.refresh_token = res["refresh_token"] self.mfa_code = res["mfa_code"] self.scope = res["scope"] def logout_oauth2(self): ''' Logout for given Oauth2 bearer token ''' url = "https://api.robinhood.com/oauth2/revoke_token/" data = { "client_id": CLIENT_ID, "token": self.refresh_token, } res = self.post(url, payload=data) if res is None: self.account_id = None self.account_url = None self.access_token = None self.refresh_token = None self.mfa_code = None self.scope = None self.authenticated = False return True else: raise AuthenticationError("fast_arrow could not log out.")
westonplatter/fast_arrow
fast_arrow/client.py
Client.relogin_oauth2
python
def relogin_oauth2(self): ''' (Re)login using the Oauth2 refresh token ''' url = "https://api.robinhood.com/oauth2/token/" data = { "grant_type": "refresh_token", "refresh_token": self.refresh_token, "scope": "internal", "client_id": CLIENT_ID, "expires_in": 86400, } res = self.post(url, payload=data, retry=False) self.access_token = res["access_token"] self.refresh_token = res["refresh_token"] self.mfa_code = res["mfa_code"] self.scope = res["scope"]
(Re)login using the Oauth2 refresh token
train
https://github.com/westonplatter/fast_arrow/blob/514cbca4994f52a97222058167830a302e313d04/fast_arrow/client.py#L160-L176
[ "def post(self, url=None, payload=None, retry=True):\n '''\n Execute HTTP POST\n '''\n headers = self._gen_headers(self.access_token, url)\n attempts = 1\n while attempts <= HTTP_ATTEMPTS_MAX:\n try:\n res = requests.post(url, headers=headers, data=payload,\n timeout=15, verify=self.certs)\n res.raise_for_status()\n if res.headers['Content-Length'] == '0':\n return None\n else:\n return res.json()\n except requests.exceptions.RequestException as e:\n attempts += 1\n if res.status_code in [400, 429]:\n raise e\n elif retry and res.status_code in [403]:\n self.relogin_oauth2()\n" ]
class Client(object): def __init__(self, **kwargs): self.options = kwargs self.account_id = None self.account_url = None self.access_token = None self.refresh_token = None self.mfa_code = None self.scope = None self.authenticated = False self.certs = os.path.join( os.path.dirname(__file__), 'ssl_certs/certs.pem') def authenticate(self): ''' Authenticate using data in `options` ''' if "username" in self.options and "password" in self.options: self.login_oauth2( self.options["username"], self.options["password"], self.options.get('mfa_code')) elif "access_token" in self.options: if "refresh_token" in self.options: self.access_token = self.options["access_token"] self.refresh_token = self.options["refresh_token"] self.__set_account_info() else: self.authenticated = False return self.authenticated def get(self, url=None, params=None, retry=True): ''' Execute HTTP GET ''' headers = self._gen_headers(self.access_token, url) attempts = 1 while attempts <= HTTP_ATTEMPTS_MAX: try: res = requests.get(url, headers=headers, params=params, timeout=15, verify=self.certs) res.raise_for_status() return res.json() except requests.exceptions.RequestException as e: attempts += 1 if res.status_code in [400]: raise e elif retry and res.status_code in [403]: self.relogin_oauth2() def post(self, url=None, payload=None, retry=True): ''' Execute HTTP POST ''' headers = self._gen_headers(self.access_token, url) attempts = 1 while attempts <= HTTP_ATTEMPTS_MAX: try: res = requests.post(url, headers=headers, data=payload, timeout=15, verify=self.certs) res.raise_for_status() if res.headers['Content-Length'] == '0': return None else: return res.json() except requests.exceptions.RequestException as e: attempts += 1 if res.status_code in [400, 429]: raise e elif retry and res.status_code in [403]: self.relogin_oauth2() def _gen_headers(self, bearer, url): ''' Generate headders, adding in Oauth2 bearer token if present ''' headers = { "Accept": "*/*", "Accept-Encoding": "gzip, deflate", "Accept-Language": ("en;q=1, fr;q=0.9, de;q=0.8, ja;q=0.7, " + "nl;q=0.6, it;q=0.5"), "User-Agent": ("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) " + "AppleWebKit/537.36 (KHTML, like Gecko) " + "Chrome/68.0.3440.106 Safari/537.36"), } if bearer: headers["Authorization"] = "Bearer {0}".format(bearer) if url == "https://api.robinhood.com/options/orders/": headers["Content-Type"] = "application/json; charset=utf-8" return headers def login_oauth2(self, username, password, mfa_code=None): ''' Login using username and password ''' data = { "grant_type": "password", "scope": "internal", "client_id": CLIENT_ID, "expires_in": 86400, "password": password, "username": username } if mfa_code is not None: data['mfa_code'] = mfa_code url = "https://api.robinhood.com/oauth2/token/" res = self.post(url, payload=data, retry=False) if res is None: if mfa_code is None: msg = ("Client.login_oauth2(). Could not authenticate. Check " + "username and password.") raise AuthenticationError(msg) else: msg = ("Client.login_oauth2(). Could not authenticate. Check" + "username and password, and enter a valid MFA code.") raise AuthenticationError(msg) elif res.get('mfa_required') is True: msg = "Client.login_oauth2(). Couldn't authenticate. MFA required." raise AuthenticationError(msg) self.access_token = res["access_token"] self.refresh_token = res["refresh_token"] self.mfa_code = res["mfa_code"] self.scope = res["scope"] self.__set_account_info() return self.authenticated def __set_account_info(self): account_urls = Account.all_urls(self) if len(account_urls) > 1: msg = ("fast_arrow 'currently' does not handle " + "multiple account authentication.") raise NotImplementedError(msg) elif len(account_urls) == 0: msg = "fast_arrow expected at least 1 account." raise AuthenticationError(msg) else: self.account_url = account_urls[0] self.account_id = get_last_path(self.account_url) self.authenticated = True def logout_oauth2(self): ''' Logout for given Oauth2 bearer token ''' url = "https://api.robinhood.com/oauth2/revoke_token/" data = { "client_id": CLIENT_ID, "token": self.refresh_token, } res = self.post(url, payload=data) if res is None: self.account_id = None self.account_url = None self.access_token = None self.refresh_token = None self.mfa_code = None self.scope = None self.authenticated = False return True else: raise AuthenticationError("fast_arrow could not log out.")
westonplatter/fast_arrow
fast_arrow/client.py
Client.logout_oauth2
python
def logout_oauth2(self): ''' Logout for given Oauth2 bearer token ''' url = "https://api.robinhood.com/oauth2/revoke_token/" data = { "client_id": CLIENT_ID, "token": self.refresh_token, } res = self.post(url, payload=data) if res is None: self.account_id = None self.account_url = None self.access_token = None self.refresh_token = None self.mfa_code = None self.scope = None self.authenticated = False return True else: raise AuthenticationError("fast_arrow could not log out.")
Logout for given Oauth2 bearer token
train
https://github.com/westonplatter/fast_arrow/blob/514cbca4994f52a97222058167830a302e313d04/fast_arrow/client.py#L178-L198
[ "def post(self, url=None, payload=None, retry=True):\n '''\n Execute HTTP POST\n '''\n headers = self._gen_headers(self.access_token, url)\n attempts = 1\n while attempts <= HTTP_ATTEMPTS_MAX:\n try:\n res = requests.post(url, headers=headers, data=payload,\n timeout=15, verify=self.certs)\n res.raise_for_status()\n if res.headers['Content-Length'] == '0':\n return None\n else:\n return res.json()\n except requests.exceptions.RequestException as e:\n attempts += 1\n if res.status_code in [400, 429]:\n raise e\n elif retry and res.status_code in [403]:\n self.relogin_oauth2()\n" ]
class Client(object): def __init__(self, **kwargs): self.options = kwargs self.account_id = None self.account_url = None self.access_token = None self.refresh_token = None self.mfa_code = None self.scope = None self.authenticated = False self.certs = os.path.join( os.path.dirname(__file__), 'ssl_certs/certs.pem') def authenticate(self): ''' Authenticate using data in `options` ''' if "username" in self.options and "password" in self.options: self.login_oauth2( self.options["username"], self.options["password"], self.options.get('mfa_code')) elif "access_token" in self.options: if "refresh_token" in self.options: self.access_token = self.options["access_token"] self.refresh_token = self.options["refresh_token"] self.__set_account_info() else: self.authenticated = False return self.authenticated def get(self, url=None, params=None, retry=True): ''' Execute HTTP GET ''' headers = self._gen_headers(self.access_token, url) attempts = 1 while attempts <= HTTP_ATTEMPTS_MAX: try: res = requests.get(url, headers=headers, params=params, timeout=15, verify=self.certs) res.raise_for_status() return res.json() except requests.exceptions.RequestException as e: attempts += 1 if res.status_code in [400]: raise e elif retry and res.status_code in [403]: self.relogin_oauth2() def post(self, url=None, payload=None, retry=True): ''' Execute HTTP POST ''' headers = self._gen_headers(self.access_token, url) attempts = 1 while attempts <= HTTP_ATTEMPTS_MAX: try: res = requests.post(url, headers=headers, data=payload, timeout=15, verify=self.certs) res.raise_for_status() if res.headers['Content-Length'] == '0': return None else: return res.json() except requests.exceptions.RequestException as e: attempts += 1 if res.status_code in [400, 429]: raise e elif retry and res.status_code in [403]: self.relogin_oauth2() def _gen_headers(self, bearer, url): ''' Generate headders, adding in Oauth2 bearer token if present ''' headers = { "Accept": "*/*", "Accept-Encoding": "gzip, deflate", "Accept-Language": ("en;q=1, fr;q=0.9, de;q=0.8, ja;q=0.7, " + "nl;q=0.6, it;q=0.5"), "User-Agent": ("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) " + "AppleWebKit/537.36 (KHTML, like Gecko) " + "Chrome/68.0.3440.106 Safari/537.36"), } if bearer: headers["Authorization"] = "Bearer {0}".format(bearer) if url == "https://api.robinhood.com/options/orders/": headers["Content-Type"] = "application/json; charset=utf-8" return headers def login_oauth2(self, username, password, mfa_code=None): ''' Login using username and password ''' data = { "grant_type": "password", "scope": "internal", "client_id": CLIENT_ID, "expires_in": 86400, "password": password, "username": username } if mfa_code is not None: data['mfa_code'] = mfa_code url = "https://api.robinhood.com/oauth2/token/" res = self.post(url, payload=data, retry=False) if res is None: if mfa_code is None: msg = ("Client.login_oauth2(). Could not authenticate. Check " + "username and password.") raise AuthenticationError(msg) else: msg = ("Client.login_oauth2(). Could not authenticate. Check" + "username and password, and enter a valid MFA code.") raise AuthenticationError(msg) elif res.get('mfa_required') is True: msg = "Client.login_oauth2(). Couldn't authenticate. MFA required." raise AuthenticationError(msg) self.access_token = res["access_token"] self.refresh_token = res["refresh_token"] self.mfa_code = res["mfa_code"] self.scope = res["scope"] self.__set_account_info() return self.authenticated def __set_account_info(self): account_urls = Account.all_urls(self) if len(account_urls) > 1: msg = ("fast_arrow 'currently' does not handle " + "multiple account authentication.") raise NotImplementedError(msg) elif len(account_urls) == 0: msg = "fast_arrow expected at least 1 account." raise AuthenticationError(msg) else: self.account_url = account_urls[0] self.account_id = get_last_path(self.account_url) self.authenticated = True def relogin_oauth2(self): ''' (Re)login using the Oauth2 refresh token ''' url = "https://api.robinhood.com/oauth2/token/" data = { "grant_type": "refresh_token", "refresh_token": self.refresh_token, "scope": "internal", "client_id": CLIENT_ID, "expires_in": 86400, } res = self.post(url, payload=data, retry=False) self.access_token = res["access_token"] self.refresh_token = res["refresh_token"] self.mfa_code = res["mfa_code"] self.scope = res["scope"]
westonplatter/fast_arrow
fast_arrow/resources/stock.py
Stock.fetch
python
def fetch(cls, client, symbol): assert(type(symbol) is str) url = ("https://api.robinhood.com/instruments/?symbol={0}". format(symbol)) data = client.get(url) return data["results"][0]
fetch data for stock
train
https://github.com/westonplatter/fast_arrow/blob/514cbca4994f52a97222058167830a302e313d04/fast_arrow/resources/stock.py#L7-L16
[ "def get(self, url=None, params=None, retry=True):\n '''\n Execute HTTP GET\n '''\n headers = self._gen_headers(self.access_token, url)\n attempts = 1\n while attempts <= HTTP_ATTEMPTS_MAX:\n try:\n res = requests.get(url,\n headers=headers,\n params=params,\n timeout=15,\n verify=self.certs)\n res.raise_for_status()\n return res.json()\n except requests.exceptions.RequestException as e:\n attempts += 1\n if res.status_code in [400]:\n raise e\n elif retry and res.status_code in [403]:\n self.relogin_oauth2()\n" ]
class Stock(object): @classmethod @classmethod def mergein_marketdata_list(cls, client, stocks): ids = [x["id"] for x in stocks] mds = StockMarketdata.quote_by_instruments(client, ids) mds = [x for x in mds if x] results = [] for s in stocks: # @TODO optimize this so it's better than O(n^2) md = [md for md in mds if md['instrument'] == s['url']] if len(md) > 0: md = md[0] md_kv = { "ask_price": md["ask_price"], "bid_price": md["bid_price"], } merged_dict = dict(list(s.items()) + list(md_kv.items())) else: merged_dict = dict(list(s.items())) results.append(merged_dict) return results @classmethod def all(cls, client, symbols): """" fetch data for multiple stocks """ params = {"symbol": ",".join(symbols)} request_url = "https://api.robinhood.com/instruments/" data = client.get(request_url, params=params) results = data["results"] while data["next"]: data = client.get(data["next"]) results.extend(data["results"]) return results
westonplatter/fast_arrow
fast_arrow/resources/stock.py
Stock.all
python
def all(cls, client, symbols): " params = {"symbol": ",".join(symbols)} request_url = "https://api.robinhood.com/instruments/" data = client.get(request_url, params=params) results = data["results"] while data["next"]: data = client.get(data["next"]) results.extend(data["results"]) return results
fetch data for multiple stocks
train
https://github.com/westonplatter/fast_arrow/blob/514cbca4994f52a97222058167830a302e313d04/fast_arrow/resources/stock.py#L41-L54
null
class Stock(object): @classmethod def fetch(cls, client, symbol): """ fetch data for stock """ assert(type(symbol) is str) url = ("https://api.robinhood.com/instruments/?symbol={0}". format(symbol)) data = client.get(url) return data["results"][0] @classmethod def mergein_marketdata_list(cls, client, stocks): ids = [x["id"] for x in stocks] mds = StockMarketdata.quote_by_instruments(client, ids) mds = [x for x in mds if x] results = [] for s in stocks: # @TODO optimize this so it's better than O(n^2) md = [md for md in mds if md['instrument'] == s['url']] if len(md) > 0: md = md[0] md_kv = { "ask_price": md["ask_price"], "bid_price": md["bid_price"], } merged_dict = dict(list(s.items()) + list(md_kv.items())) else: merged_dict = dict(list(s.items())) results.append(merged_dict) return results @classmethod
westonplatter/fast_arrow
fast_arrow/option_strategies/vertical.py
Vertical.gen_df
python
def gen_df(cls, options, width, spread_type="call", spread_kind="buy"): assert type(width) is int assert spread_type in ["call", "put"] assert spread_kind in ["buy", "sell"] # get CALLs or PUTs options = list(filter(lambda x: x["type"] == spread_type, options)) coef = (1 if spread_type == "put" else -1) shift = width * coef df = pd.DataFrame.from_dict(options) df['expiration_date'] = pd.to_datetime( df['expiration_date'], format="%Y-%m-%d") df['adjusted_mark_price'] = pd.to_numeric(df['adjusted_mark_price']) df['strike_price'] = pd.to_numeric(df['strike_price']) df.sort_values(["expiration_date", "strike_price"], inplace=True) for k, v in df.groupby("expiration_date"): sdf = v.shift(shift) df.loc[v.index, "strike_price_shifted"] = sdf["strike_price"] df.loc[v.index, "delta_shifted"] = sdf["delta"] df.loc[v.index, "volume_shifted"] = sdf["volume"] df.loc[v.index, "open_interest_shifted"] = sdf["open_interest"] df.loc[v.index, "instrument_shifted"] = sdf["instrument"] df.loc[v.index, "adjusted_mark_price_shift"] = \ sdf["adjusted_mark_price"] if spread_kind == "sell": df.loc[v.index, "margin"] = \ abs(sdf["strike_price"] - v["strike_price"]) else: df.loc[v.index, "margin"] = 0.0 if spread_kind == "buy": df.loc[v.index, "premium_adjusted_mark_price"] = ( v["adjusted_mark_price"] - sdf["adjusted_mark_price"]) elif spread_kind == "sell": df.loc[v.index, "premium_adjusted_mark_price"] = ( sdf["adjusted_mark_price"] - v["adjusted_mark_price"]) return df
Generate Pandas Dataframe of Vertical :param options: python dict of options. :param width: offset for spread. Must be integer. :param spread_type: call or put. defaults to "call". :param spread_kind: buy or sell. defaults to "buy".
train
https://github.com/westonplatter/fast_arrow/blob/514cbca4994f52a97222058167830a302e313d04/fast_arrow/option_strategies/vertical.py#L7-L57
null
class Vertical(object): @classmethod
westonplatter/fast_arrow
fast_arrow/resources/stock_order.py
StockOrder.all
python
def all(cls, client): " url = "https://api.robinhood.com/orders/" data = client.get(url) results = data["results"] while data["next"]: data = client.get(data["next"]) results.extend(data["results"]) return results
fetch data for multiple stocks
train
https://github.com/westonplatter/fast_arrow/blob/514cbca4994f52a97222058167830a302e313d04/fast_arrow/resources/stock_order.py#L5-L15
[ "def get(self, url=None, params=None, retry=True):\n '''\n Execute HTTP GET\n '''\n headers = self._gen_headers(self.access_token, url)\n attempts = 1\n while attempts <= HTTP_ATTEMPTS_MAX:\n try:\n res = requests.get(url,\n headers=headers,\n params=params,\n timeout=15,\n verify=self.certs)\n res.raise_for_status()\n return res.json()\n except requests.exceptions.RequestException as e:\n attempts += 1\n if res.status_code in [400]:\n raise e\n elif retry and res.status_code in [403]:\n self.relogin_oauth2()\n" ]
class StockOrder(object): @classmethod
westonplatter/fast_arrow
fast_arrow/util.py
chunked_list
python
def chunked_list(_list, _chunk_size=50): for i in range(0, len(_list), _chunk_size): yield _list[i:i + _chunk_size]
Break lists into small lists for processing:w
train
https://github.com/westonplatter/fast_arrow/blob/514cbca4994f52a97222058167830a302e313d04/fast_arrow/util.py#L18-L23
null
import configparser from urllib.parse import urlparse import datetime def get_username_password(config_file): config = configparser.ConfigParser() config.read(config_file) return [config['account']['username'], config['account']['password']] def get_last_path(url_string): o = urlparse(url_string) paths = o.path.rsplit("/") return list(filter(None, paths))[-1] def days_ago(days): """ Returns datetime object """ return datetime.date.today() - datetime.timedelta(days=days) def format_datetime(dt): """ Returns ISO 8601 string representation """ return dt.isoformat() def is_max_date_gt(max_date, date): if max_date is None: return False if date < max_date: return True else: return False
westonplatter/fast_arrow
fast_arrow/resources/stock_marketdata.py
StockMarketdata.quote_by_instruments
python
def quote_by_instruments(cls, client, ids): base_url = "https://api.robinhood.com/instruments" id_urls = ["{}/{}/".format(base_url, _id) for _id in ids] return cls.quotes_by_instrument_urls(client, id_urls)
create instrument urls, fetch, return results
train
https://github.com/westonplatter/fast_arrow/blob/514cbca4994f52a97222058167830a302e313d04/fast_arrow/resources/stock_marketdata.py#L13-L19
[ "def quotes_by_instrument_urls(cls, client, urls):\n \"\"\"\n fetch and return results\n \"\"\"\n instruments = \",\".join(urls)\n params = {\"instruments\": instruments}\n url = \"https://api.robinhood.com/marketdata/quotes/\"\n data = client.get(url, params=params)\n results = data[\"results\"]\n while \"next\" in data and data[\"next\"]:\n data = client.get(data[\"next\"])\n results.extend(data[\"results\"])\n return results\n" ]
class StockMarketdata(object): @classmethod def quote_by_instrument(cls, client, _id): return cls.quote_by_instruments(client, [_id])[0] @classmethod @classmethod def quotes_by_instrument_urls(cls, client, urls): """ fetch and return results """ instruments = ",".join(urls) params = {"instruments": instruments} url = "https://api.robinhood.com/marketdata/quotes/" data = client.get(url, params=params) results = data["results"] while "next" in data and data["next"]: data = client.get(data["next"]) results.extend(data["results"]) return results @classmethod @deprecation.deprecated( deprecated_in="0.3.1", removed_in="0.4", current_version=VERSION, details="Use 'historical_quote_by_symbol' instead") def historical(cls, client, symbol, span="year", bounds="regular"): return cls.historical_quote_by_symbol(client, symbol, span, bounds) @classmethod def historical_quote_by_symbol(cls, client, symbol, span="year", bounds="regular"): datas = cls.historical_quote_by_symbols(client, [symbol], span, bounds) return datas[0] @classmethod def historical_quote_by_symbols(cls, client, symbols, span="year", bounds="regular"): possible_intervals = { "day": "5minute", "week": "10minute", "year": "day", "5year": "week"} assert span in possible_intervals.keys() interval = possible_intervals[span] assert bounds in ["regular"] request_url = "https://api.robinhood.com/marketdata/historicals/" results = [] for _symbols in chunked_list(symbols, 25): params = {"span": span, "interval": interval, "bounds": bounds, "symbols": ",".join(_symbols)} data = client.get(request_url, params=params) if data and data["results"]: results.extend(data["results"]) return results
westonplatter/fast_arrow
fast_arrow/resources/stock_marketdata.py
StockMarketdata.quotes_by_instrument_urls
python
def quotes_by_instrument_urls(cls, client, urls): instruments = ",".join(urls) params = {"instruments": instruments} url = "https://api.robinhood.com/marketdata/quotes/" data = client.get(url, params=params) results = data["results"] while "next" in data and data["next"]: data = client.get(data["next"]) results.extend(data["results"]) return results
fetch and return results
train
https://github.com/westonplatter/fast_arrow/blob/514cbca4994f52a97222058167830a302e313d04/fast_arrow/resources/stock_marketdata.py#L22-L34
null
class StockMarketdata(object): @classmethod def quote_by_instrument(cls, client, _id): return cls.quote_by_instruments(client, [_id])[0] @classmethod def quote_by_instruments(cls, client, ids): """ create instrument urls, fetch, return results """ base_url = "https://api.robinhood.com/instruments" id_urls = ["{}/{}/".format(base_url, _id) for _id in ids] return cls.quotes_by_instrument_urls(client, id_urls) @classmethod @classmethod @deprecation.deprecated( deprecated_in="0.3.1", removed_in="0.4", current_version=VERSION, details="Use 'historical_quote_by_symbol' instead") def historical(cls, client, symbol, span="year", bounds="regular"): return cls.historical_quote_by_symbol(client, symbol, span, bounds) @classmethod def historical_quote_by_symbol(cls, client, symbol, span="year", bounds="regular"): datas = cls.historical_quote_by_symbols(client, [symbol], span, bounds) return datas[0] @classmethod def historical_quote_by_symbols(cls, client, symbols, span="year", bounds="regular"): possible_intervals = { "day": "5minute", "week": "10minute", "year": "day", "5year": "week"} assert span in possible_intervals.keys() interval = possible_intervals[span] assert bounds in ["regular"] request_url = "https://api.robinhood.com/marketdata/historicals/" results = [] for _symbols in chunked_list(symbols, 25): params = {"span": span, "interval": interval, "bounds": bounds, "symbols": ",".join(_symbols)} data = client.get(request_url, params=params) if data and data["results"]: results.extend(data["results"]) return results
westonplatter/fast_arrow
fast_arrow/resources/option_position.py
OptionPosition.all
python
def all(cls, client, **kwargs): max_date = kwargs['max_date'] if 'max_date' in kwargs else None max_fetches = \ kwargs['max_fetches'] if 'max_fetches' in kwargs else None url = 'https://api.robinhood.com/options/positions/' params = {} data = client.get(url, params=params) results = data["results"] if is_max_date_gt(max_date, results[-1]['updated_at'][0:10]): return results if max_fetches == 1: return results fetches = 1 while data["next"]: fetches = fetches + 1 data = client.get(data["next"]) results.extend(data["results"]) if is_max_date_gt(max_date, results[-1]['updated_at'][0:10]): return results if max_fetches and (fetches >= max_fetches): return results return results
fetch all option positions
train
https://github.com/westonplatter/fast_arrow/blob/514cbca4994f52a97222058167830a302e313d04/fast_arrow/resources/option_position.py#L10-L37
[ "def is_max_date_gt(max_date, date):\n if max_date is None:\n return False\n if date < max_date:\n return True\n else:\n return False\n", "def get(self, url=None, params=None, retry=True):\n '''\n Execute HTTP GET\n '''\n headers = self._gen_headers(self.access_token, url)\n attempts = 1\n while attempts <= HTTP_ATTEMPTS_MAX:\n try:\n res = requests.get(url,\n headers=headers,\n params=params,\n timeout=15,\n verify=self.certs)\n res.raise_for_status()\n return res.json()\n except requests.exceptions.RequestException as e:\n attempts += 1\n if res.status_code in [400]:\n raise e\n elif retry and res.status_code in [403]:\n self.relogin_oauth2()\n" ]
class OptionPosition(object): @classmethod @classmethod def append_marketdata(cls, client, option_position): """ Fetch and merge in Marketdata for option position """ return cls.append_marketdata_list(client, [option_position])[0] @classmethod def mergein_marketdata_list(cls, client, option_positions): """ Fetch and merge in Marketdata for each option position """ ids = cls._extract_ids(option_positions) mds = OptionMarketdata.quotes_by_instrument_ids(client, ids) results = [] for op in option_positions: # @TODO optimize this so it's better than O(n^2) md = [x for x in mds if x['instrument'] == op['option']][0] # there is no overlap in keys so this is fine merged_dict = dict(list(op.items()) + list(md.items())) results.append(merged_dict) return results @classmethod def mergein_instrumentdata_list(cls, client, option_positions): ids = cls._extract_ids(option_positions) idatas = Option.fetch_list(client, ids) results = [] for op in option_positions: idata = [x for x in idatas if x['url'] == op['instrument']][0] # there is an overlap in keys, # {'chain_symbol', 'url', 'type', 'created_at', 'id', # 'updated_at', 'chain_id'} # @TODO this is ugly. let's fix it later # alternative method, # wanted_keys = ['strike_price'] # idata_subset = \ # dict((k, idata[k]) for k in wanted_keys if k in idata) merge_me = { "option_type": idata["type"], "strike_price": idata["strike_price"], "expiration_date": idata["expiration_date"], "min_ticks": idata["min_ticks"] } merged_dict = dict(list(op.items()) + list(merge_me.items())) results.append(merged_dict) return results @classmethod def humanize_numbers(cls, option_positions): results = [] for op in option_positions: keys_to_humanize = [ "quantity", "delta", "theta", "gamma", "vega", "rho"] coef = (1.0 if op["type"] == "long" else -1.0) for k in keys_to_humanize: if op[k] is None: continue op[k] = float(op[k]) * coef if op["type"] == "long": op["chance_of_profit"] = op["chance_of_profit_long"] else: op["chance_of_profit"] = op["chance_of_profit_short"] results.append(op) return results @classmethod def _extract_ids(cls, option_positions): ids = [] for op in option_positions: _id = util.get_last_path(op["option"]) ids.append(_id) return ids
westonplatter/fast_arrow
fast_arrow/resources/option_position.py
OptionPosition.mergein_marketdata_list
python
def mergein_marketdata_list(cls, client, option_positions): ids = cls._extract_ids(option_positions) mds = OptionMarketdata.quotes_by_instrument_ids(client, ids) results = [] for op in option_positions: # @TODO optimize this so it's better than O(n^2) md = [x for x in mds if x['instrument'] == op['option']][0] # there is no overlap in keys so this is fine merged_dict = dict(list(op.items()) + list(md.items())) results.append(merged_dict) return results
Fetch and merge in Marketdata for each option position
train
https://github.com/westonplatter/fast_arrow/blob/514cbca4994f52a97222058167830a302e313d04/fast_arrow/resources/option_position.py#L47-L61
[ "def quotes_by_instrument_ids(cls, client, ids):\n base_url = \"https://api.robinhood.com/options/instruments/\"\n id_urls = [\"{}{}/\".format(base_url, _id) for _id in ids]\n return cls.quotes_by_instrument_urls(client, id_urls)\n", "def _extract_ids(cls, option_positions):\n ids = []\n for op in option_positions:\n _id = util.get_last_path(op[\"option\"])\n ids.append(_id)\n return ids\n" ]
class OptionPosition(object): @classmethod def all(cls, client, **kwargs): """ fetch all option positions """ max_date = kwargs['max_date'] if 'max_date' in kwargs else None max_fetches = \ kwargs['max_fetches'] if 'max_fetches' in kwargs else None url = 'https://api.robinhood.com/options/positions/' params = {} data = client.get(url, params=params) results = data["results"] if is_max_date_gt(max_date, results[-1]['updated_at'][0:10]): return results if max_fetches == 1: return results fetches = 1 while data["next"]: fetches = fetches + 1 data = client.get(data["next"]) results.extend(data["results"]) if is_max_date_gt(max_date, results[-1]['updated_at'][0:10]): return results if max_fetches and (fetches >= max_fetches): return results return results @classmethod def append_marketdata(cls, client, option_position): """ Fetch and merge in Marketdata for option position """ return cls.append_marketdata_list(client, [option_position])[0] @classmethod @classmethod def mergein_instrumentdata_list(cls, client, option_positions): ids = cls._extract_ids(option_positions) idatas = Option.fetch_list(client, ids) results = [] for op in option_positions: idata = [x for x in idatas if x['url'] == op['instrument']][0] # there is an overlap in keys, # {'chain_symbol', 'url', 'type', 'created_at', 'id', # 'updated_at', 'chain_id'} # @TODO this is ugly. let's fix it later # alternative method, # wanted_keys = ['strike_price'] # idata_subset = \ # dict((k, idata[k]) for k in wanted_keys if k in idata) merge_me = { "option_type": idata["type"], "strike_price": idata["strike_price"], "expiration_date": idata["expiration_date"], "min_ticks": idata["min_ticks"] } merged_dict = dict(list(op.items()) + list(merge_me.items())) results.append(merged_dict) return results @classmethod def humanize_numbers(cls, option_positions): results = [] for op in option_positions: keys_to_humanize = [ "quantity", "delta", "theta", "gamma", "vega", "rho"] coef = (1.0 if op["type"] == "long" else -1.0) for k in keys_to_humanize: if op[k] is None: continue op[k] = float(op[k]) * coef if op["type"] == "long": op["chance_of_profit"] = op["chance_of_profit_long"] else: op["chance_of_profit"] = op["chance_of_profit_short"] results.append(op) return results @classmethod def _extract_ids(cls, option_positions): ids = [] for op in option_positions: _id = util.get_last_path(op["option"]) ids.append(_id) return ids
basler/pypylon
scripts/builddoxy2swig/doxy2swig/doxy2swig.py
shift
python
def shift(txt, indent = ' ', prepend = ''): if type(indent) is int: indent = indent * ' ' special_end = txt[-1:] == [''] lines = ''.join(txt).splitlines(True) for i in range(1,len(lines)): if lines[i].strip() or indent.strip(): lines[i] = indent + lines[i] if not lines: return prepend prepend = prepend[:len(indent)] indent = indent[len(prepend):] lines[0] = prepend + indent + lines[0] ret = [''.join(lines)] if special_end: ret.append('') return ret
Return a list corresponding to the lines of text in the `txt` list indented by `indent`. Prepend instead the string given in `prepend` to the beginning of the first line. Note that if len(prepend) > len(indent), then `prepend` will be truncated (doing better is tricky!). This preserves a special '' entry at the end of `txt` (see `do_para` for the meaning).
train
https://github.com/basler/pypylon/blob/d3510fa419b1c2b17f3f0b80a5fbb720c7b84008/scripts/builddoxy2swig/doxy2swig/doxy2swig.py#L75-L97
null
#!/usr/bin/env python """doxy2swig.py [options] index.xml output.i Doxygen XML to SWIG docstring converter (improved version). Converts Doxygen generated XML files into a file containing docstrings for use by SWIG. index.xml is your doxygen generated XML file and output.i is where the output will be written (the file will be clobbered). """ # # The current version of this code is hosted on a github repository: # https://github.com/m7thon/doxy2swig # # This code is implemented using Mark Pilgrim's code as a guideline: # http://www.faqs.org/docs/diveintopython/kgp_divein.html # # Original Author: Prabhu Ramachandran # Modified by: Michael Thon (June 2015) # License: BSD style # # Thanks: # Johan Hake: the include_function_definition feature # Bill Spotz: bug reports and testing. # Sebastian Henschel: Misc. enhancements. # # Changes: # June 2015 (Michael Thon): # - class documentation: # -c: add constructor call signatures and a "Constructors" section # collecting the respective docs (e.g. for python) # -a: add "Attributes" section collecting the documentation for member # variables (e.g. for python) # - overloaded functions: # -o: collect all documentation into one "Overloaded function" section # - option to include function definition / signature renamed to -f # - formatting: # + included function signatures slightly reformatted # + option (-t) to turn off/on type information for funciton signatures # + lists (incl. nested and ordered) # + attempt to produce docstrings that render nicely as markdown # + translate code, emphasis, bold, linebreak, hruler, blockquote, # verbatim, heading tags to markdown # + new text-wrapping and option -w to specify the text width # from xml.dom import minidom import re import textwrap import sys import os.path import optparse def my_open_read(source): if hasattr(source, "read"): return source else: try: return open(source, encoding='utf-8') except TypeError: return open(source) def my_open_write(dest): if hasattr(dest, "write"): return dest else: try: return open(dest, 'w', encoding='utf-8') except TypeError: return open(dest, 'w') # MARK: Text handling: class Doxy2SWIG: """Converts Doxygen generated XML files into a file containing docstrings that can be used by SWIG-1.3.x that have support for feature("docstring"). Once the data is parsed it is stored in self.pieces. """ def __init__(self, src, with_function_signature = False, with_type_info = False, with_constructor_list = False, with_attribute_list = False, with_overloaded_functions = False, textwidth = 80, quiet = False): """Initialize the instance given a source object. `src` can be a file or filename. If you do not want to include function definitions from doxygen then set `include_function_definition` to `False`. This is handy since this allows you to use the swig generated function definition using %feature("autodoc", [0,1]). """ # options: self.with_function_signature = with_function_signature self.with_type_info = with_type_info self.with_constructor_list = with_constructor_list self.with_attribute_list = with_attribute_list self.with_overloaded_functions = with_overloaded_functions self.textwidth = textwidth self.quiet = quiet # state: self.indent = 0 self.listitem = '' self.pieces = [] f = my_open_read(src) self.my_dir = os.path.dirname(f.name) self.xmldoc = minidom.parse(f).documentElement f.close() self.pieces.append('\n// File: %s\n' % os.path.basename(f.name)) self.space_re = re.compile(r'\s+') self.lead_spc = re.compile(r'^(%feature\S+\s+\S+\s*?)"\s+(\S)') self.multi = 0 self.ignores = ['inheritancegraph', 'param', 'listofallmembers', 'innerclass', 'name', 'declname', 'incdepgraph', 'invincdepgraph', 'programlisting', 'type', 'references', 'referencedby', 'location', 'collaborationgraph', 'reimplements', 'reimplementedby', 'derivedcompoundref', 'basecompoundref', 'argsstring', 'definition', 'exceptions'] #self.generics = [] def generate(self): """Parses the file set in the initialization. The resulting data is stored in `self.pieces`. """ self.parse(self.xmldoc) def write(self, fname): o = my_open_write(fname) o.write(''.join(self.pieces)) o.write('\n') o.close() def parse(self, node): """Parse a given node. This function in turn calls the `parse_<nodeType>` functions which handle the respective nodes. """ pm = getattr(self, "parse_%s" % node.__class__.__name__) pm(node) def parse_Document(self, node): self.parse(node.documentElement) def parse_Text(self, node): txt = node.data if txt == ' ': # this can happen when two tags follow in a text, e.g., # " ...</emph> <formaula>$..." etc. # here we want to keep the space. self.add_text(txt) return txt = txt.replace('\\', r'\\') txt = txt.replace('"', r'\"') # ignore pure whitespace m = self.space_re.match(txt) if m and len(m.group()) == len(txt): pass else: self.add_text(txt) def parse_Comment(self, node): """Parse a `COMMENT_NODE`. This does nothing for now.""" return def parse_Element(self, node): """Parse an `ELEMENT_NODE`. This calls specific `do_<tagName>` handers for different elements. If no handler is available the `subnode_parse` method is called. All tagNames specified in `self.ignores` are simply ignored. """ name = node.tagName ignores = self.ignores if name in ignores: return attr = "do_%s" % name if hasattr(self, attr): handlerMethod = getattr(self, attr) handlerMethod(node) else: self.subnode_parse(node) #if name not in self.generics: self.generics.append(name) # MARK: Special format parsing def subnode_parse(self, node, pieces=None, indent=0, ignore=[], restrict=None): """Parse the subnodes of a given node. Subnodes with tags in the `ignore` list are ignored. If pieces is given, use this as target for the parse results instead of self.pieces. Indent all lines by the amount given in `indent`. Note that the initial content in `pieces` is not indented. The final result is in any case added to self.pieces.""" if pieces is not None: old_pieces, self.pieces = self.pieces, pieces else: old_pieces = [] if type(indent) is int: indent = indent * ' ' if len(indent) > 0: pieces = ''.join(self.pieces) i_piece = pieces[:len(indent)] if self.pieces[-1:] == ['']: self.pieces = [pieces[len(indent):]] + [''] elif self.pieces != []: self.pieces = [pieces[len(indent):]] self.indent += len(indent) for n in node.childNodes: if restrict is not None: if n.nodeType == n.ELEMENT_NODE and n.tagName in restrict: self.parse(n) elif n.nodeType != n.ELEMENT_NODE or n.tagName not in ignore: self.parse(n) if len(indent) > 0: self.pieces = shift(self.pieces, indent, i_piece) self.indent -= len(indent) old_pieces.extend(self.pieces) self.pieces = old_pieces def surround_parse(self, node, pre_char, post_char): """Parse the subnodes of a given node. Subnodes with tags in the `ignore` list are ignored. Prepend `pre_char` and append `post_char` to the output in self.pieces.""" self.add_text(pre_char) self.subnode_parse(node) self.add_text(post_char) # MARK: Helper functions def get_specific_subnodes(self, node, name, recursive=0): """Given a node and a name, return a list of child `ELEMENT_NODEs`, that have a `tagName` matching the `name`. Search recursively for `recursive` levels. """ children = [x for x in node.childNodes if x.nodeType == x.ELEMENT_NODE] ret = [x for x in children if x.tagName == name] if recursive > 0: for x in children: ret.extend(self.get_specific_subnodes(x, name, recursive-1)) return ret def get_specific_nodes(self, node, names): """Given a node and a sequence of strings in `names`, return a dictionary containing the names as keys and child `ELEMENT_NODEs`, that have a `tagName` equal to the name. """ nodes = [(x.tagName, x) for x in node.childNodes if x.nodeType == x.ELEMENT_NODE and x.tagName in names] return dict(nodes) def add_text(self, value): """Adds text corresponding to `value` into `self.pieces`.""" if isinstance(value, (list, tuple)): self.pieces.extend(value) else: self.pieces.append(value) def start_new_paragraph(self): """Make sure to create an empty line. This is overridden, if the previous text ends with the special marker ''. In that case, nothing is done. """ if self.pieces[-1:] == ['']: # respect special marker return elif self.pieces == []: # first paragraph, add '\n', override with '' self.pieces = ['\n'] elif self.pieces[-1][-1:] != '\n': # previous line not ended self.pieces.extend([' \n' ,'\n']) else: #default self.pieces.append('\n') def add_line_with_subsequent_indent(self, line, indent=4): """Add line of text and wrap such that subsequent lines are indented by `indent` spaces. """ if isinstance(line, (list, tuple)): line = ''.join(line) line = line.strip() width = self.textwidth-self.indent-indent wrapped_lines = textwrap.wrap(line[indent:], width=width) for i in range(len(wrapped_lines)): if wrapped_lines[i] != '': wrapped_lines[i] = indent * ' ' + wrapped_lines[i] self.pieces.append(line[:indent] + '\n'.join(wrapped_lines)[indent:] + ' \n') def extract_text(self, node): """Return the string representation of the node or list of nodes by parsing the subnodes, but returning the result as a string instead of adding it to `self.pieces`. Note that this allows extracting text even if the node is in the ignore list. """ if not isinstance(node, (list, tuple)): node = [node] pieces, self.pieces = self.pieces, [''] for n in node: for sn in n.childNodes: self.parse(sn) ret = ''.join(self.pieces) self.pieces = pieces return ret def get_function_signature(self, node): """Returns the function signature string for memberdef nodes.""" name = self.extract_text(self.get_specific_subnodes(node, 'name')) if self.with_type_info: argsstring = self.extract_text(self.get_specific_subnodes(node, 'argsstring')) else: argsstring = [] param_id = 1 for n_param in self.get_specific_subnodes(node, 'param'): declname = self.extract_text(self.get_specific_subnodes(n_param, 'declname')) if not declname: declname = 'arg' + str(param_id) defval = self.extract_text(self.get_specific_subnodes(n_param, 'defval')) if defval: defval = '=' + defval argsstring.append(declname + defval) param_id = param_id + 1 argsstring = '(' + ', '.join(argsstring) + ')' type = self.extract_text(self.get_specific_subnodes(node, 'type')) function_definition = name + argsstring if type != '' and type != 'void': function_definition = function_definition + ' -> ' + type return '`' + function_definition + '` ' # MARK: Special parsing tasks (need to be called manually) def make_constructor_list(self, constructor_nodes, classname): """Produces the "Constructors" section and the constructor signatures (since swig does not do so for classes) for class docstrings.""" if constructor_nodes == []: return self.add_text(['\n', 'Constructors', '\n', '------------']) for n in constructor_nodes: self.add_text('\n') self.add_line_with_subsequent_indent('* ' + self.get_function_signature(n)) self.subnode_parse(n, pieces = [], indent=4, ignore=['definition', 'name']) def make_attribute_list(self, node): """Produces the "Attributes" section in class docstrings for public member variables (attributes). """ atr_nodes = [] for n in self.get_specific_subnodes(node, 'memberdef', recursive=2): if n.attributes['kind'].value == 'variable' and n.attributes['prot'].value == 'public': atr_nodes.append(n) if not atr_nodes: return self.add_text(['\n', 'Attributes', '\n', '----------']) for n in atr_nodes: name = self.extract_text(self.get_specific_subnodes(n, 'name')) self.add_text(['\n* ', '`', name, '`', ' : ']) self.add_text(['`', self.extract_text(self.get_specific_subnodes(n, 'type')), '`']) self.add_text(' \n') restrict = ['briefdescription', 'detaileddescription'] self.subnode_parse(n, pieces=[''], indent=4, restrict=restrict) def get_memberdef_nodes_and_signatures(self, node, kind): """Collects the memberdef nodes and corresponding signatures that correspond to public function entries that are at most depth 2 deeper than the current (compounddef) node. Returns a dictionary with function signatures (what swig expects after the %feature directive) as keys, and a list of corresponding memberdef nodes as values.""" sig_dict = {} sig_prefix = '' if kind in ('file', 'namespace'): ns_node = node.getElementsByTagName('innernamespace') if not ns_node and kind == 'namespace': ns_node = node.getElementsByTagName('compoundname') if ns_node: sig_prefix = self.extract_text(ns_node[0]) + '::' elif kind in ('class', 'struct'): # Get the full function name. cn_node = node.getElementsByTagName('compoundname') sig_prefix = self.extract_text(cn_node[0]) + '::' md_nodes = self.get_specific_subnodes(node, 'memberdef', recursive=2) for n in md_nodes: if n.attributes['prot'].value != 'public': continue if n.attributes['kind'].value in ['variable', 'typedef']: continue if not self.get_specific_subnodes(n, 'definition'): continue name = self.extract_text(self.get_specific_subnodes(n, 'name')) if name[:8] == 'operator': continue sig = sig_prefix + name if sig in sig_dict: sig_dict[sig].append(n) else: sig_dict[sig] = [n] return sig_dict def handle_typical_memberdefs_no_overload(self, signature, memberdef_nodes): """Produce standard documentation for memberdef_nodes.""" for n in memberdef_nodes: self.add_text(['\n', '%feature("docstring") ', signature, ' "', '\n']) if self.with_function_signature: self.add_line_with_subsequent_indent(self.get_function_signature(n)) self.subnode_parse(n, pieces=[], ignore=['definition', 'name']) self.add_text(['";', '\n']) def handle_typical_memberdefs(self, signature, memberdef_nodes): """Produces docstring entries containing an "Overloaded function" section with the documentation for each overload, if the function is overloaded and self.with_overloaded_functions is set. Else, produce normal documentation. """ if len(memberdef_nodes) == 1 or not self.with_overloaded_functions: self.handle_typical_memberdefs_no_overload(signature, memberdef_nodes) return self.add_text(['\n', '%feature("docstring") ', signature, ' "', '\n']) if self.with_function_signature: for n in memberdef_nodes: self.add_line_with_subsequent_indent(self.get_function_signature(n)) self.add_text('\n') self.add_text(['Overloaded function', '\n', '-------------------']) for n in memberdef_nodes: self.add_text('\n') self.add_line_with_subsequent_indent('* ' + self.get_function_signature(n)) self.subnode_parse(n, pieces=[], indent=4, ignore=['definition', 'name']) self.add_text(['";', '\n']) # MARK: Tag handlers def do_linebreak(self, node): self.add_text(' ') def do_ndash(self, node): self.add_text('--') def do_mdash(self, node): self.add_text('---') def do_emphasis(self, node): self.surround_parse(node, '*', '*') def do_bold(self, node): self.surround_parse(node, '**', '**') def do_computeroutput(self, node): self.surround_parse(node, '`', '`') def do_heading(self, node): self.start_new_paragraph() pieces, self.pieces = self.pieces, [''] level = int(node.attributes['level'].value) self.subnode_parse(node) if level == 1: self.pieces.insert(0, '\n') self.add_text(['\n', len(''.join(self.pieces).strip()) * '=']) elif level == 2: self.add_text(['\n', len(''.join(self.pieces).strip()) * '-']) elif level >= 3: self.pieces.insert(0, level * '#' + ' ') # make following text have no gap to the heading: pieces.extend([''.join(self.pieces) + ' \n', '']) self.pieces = pieces def do_verbatim(self, node): self.start_new_paragraph() self.subnode_parse(node, pieces=[''], indent=4) def do_blockquote(self, node): self.start_new_paragraph() self.subnode_parse(node, pieces=[''], indent='> ') def do_hruler(self, node): self.start_new_paragraph() self.add_text('* * * * * \n') def do_includes(self, node): self.add_text('\nC++ includes: ') self.subnode_parse(node) self.add_text('\n') # MARK: Para tag handler def do_para(self, node): """This is the only place where text wrapping is automatically performed. Generally, this function parses the node (locally), wraps the text, and then adds the result to self.pieces. However, it may be convenient to allow the previous content of self.pieces to be included in the text wrapping. For this, use the following *convention*: If self.pieces ends with '', treat the _previous_ entry as part of the current paragraph. Else, insert new-line and start a new paragraph and "wrapping context". Paragraphs always end with ' \n', but if the parsed content ends with the special symbol '', this is passed on. """ if self.pieces[-1:] == ['']: pieces, self.pieces = self.pieces[:-2], self.pieces[-2:-1] else: self.add_text('\n') pieces, self.pieces = self.pieces, [''] self.subnode_parse(node) dont_end_paragraph = self.pieces[-1:] == [''] # Now do the text wrapping: width = self.textwidth - self.indent wrapped_para = [] for line in ''.join(self.pieces).splitlines(): keep_markdown_newline = line[-2:] == ' ' w_line = textwrap.wrap(line, width=width, break_long_words=False) if w_line == []: w_line = [''] if keep_markdown_newline: w_line[-1] = w_line[-1] + ' ' for wl in w_line: wrapped_para.append(wl + '\n') if wrapped_para: if wrapped_para[-1][-3:] != ' \n': wrapped_para[-1] = wrapped_para[-1][:-1] + ' \n' if dont_end_paragraph: wrapped_para.append('') pieces.extend(wrapped_para) self.pieces = pieces # MARK: List tag handlers def do_itemizedlist(self, node): if self.listitem == '': self.start_new_paragraph() elif self.pieces != [] and self.pieces[-1:] != ['']: self.add_text('\n') listitem = self.listitem if self.listitem in ['*', '-']: self.listitem = '-' else: self.listitem = '*' self.subnode_parse(node) self.listitem = listitem def do_orderedlist(self, node): if self.listitem == '': self.start_new_paragraph() elif self.pieces != [] and self.pieces[-1:] != ['']: self.add_text('\n') listitem = self.listitem self.listitem = 0 self.subnode_parse(node) self.listitem = listitem def do_listitem(self, node): try: self.listitem = int(self.listitem) + 1 item = str(self.listitem) + '. ' except: item = str(self.listitem) + ' ' self.subnode_parse(node, item, indent=4) # MARK: Parameter list tag handlers def do_parameterlist(self, node): self.start_new_paragraph() text = 'unknown' for key, val in node.attributes.items(): if key == 'kind': if val == 'param': text = 'Parameters' elif val == 'exception': text = 'Exceptions' elif val == 'retval': text = 'Returns' else: text = val break if self.indent == 0: self.add_text([text, '\n', len(text) * '-', '\n']) else: self.add_text([text, ': \n']) self.subnode_parse(node) def do_parameteritem(self, node): self.subnode_parse(node, pieces=['* ', '']) def do_parameternamelist(self, node): self.subnode_parse(node) self.add_text([' :', ' \n']) def do_parametername(self, node): if self.pieces != [] and self.pieces != ['* ', '']: self.add_text(', ') data = self.extract_text(node) self.add_text(['`', data, '`']) def do_parameterdescription(self, node): self.subnode_parse(node, pieces=[''], indent=4) # MARK: Section tag handler def do_simplesect(self, node): kind = node.attributes['kind'].value if kind in ('date', 'rcs', 'version'): return self.start_new_paragraph() if kind == 'warning': self.subnode_parse(node, pieces=['**Warning**: ',''], indent=4) elif kind == 'see': self.subnode_parse(node, pieces=['See also: ',''], indent=4) elif kind == 'return': if self.indent == 0: pieces = ['Returns', '\n', len('Returns') * '-', '\n', ''] else: pieces = ['Returns:', '\n', ''] self.subnode_parse(node, pieces=pieces) else: self.subnode_parse(node, pieces=[kind + ': ',''], indent=4) # MARK: %feature("docstring") producing tag handlers def do_compounddef(self, node): """This produces %feature("docstring") entries for classes, and handles class, namespace and file memberdef entries specially to allow for overloaded functions. For other cases, passes parsing on to standard handlers (which may produce unexpected results). """ kind = node.attributes['kind'].value if kind in ('class', 'struct'): prot = node.attributes['prot'].value if prot != 'public': return self.add_text('\n\n') classdefn = self.extract_text(self.get_specific_subnodes(node, 'compoundname')) classname = classdefn.split('::')[-1] self.add_text('%%feature("docstring") %s "\n' % classdefn) if self.with_constructor_list: constructor_nodes = [] for n in self.get_specific_subnodes(node, 'memberdef', recursive=2): if n.attributes['prot'].value == 'public': if self.extract_text(self.get_specific_subnodes(n, 'definition')) == classdefn + '::' + classname: constructor_nodes.append(n) for n in constructor_nodes: self.add_line_with_subsequent_indent(self.get_function_signature(n)) names = ('briefdescription','detaileddescription') sub_dict = self.get_specific_nodes(node, names) for n in ('briefdescription','detaileddescription'): if n in sub_dict: self.parse(sub_dict[n]) if self.with_constructor_list: self.make_constructor_list(constructor_nodes, classname) if self.with_attribute_list: self.make_attribute_list(node) sub_list = self.get_specific_subnodes(node, 'includes') if sub_list: self.parse(sub_list[0]) self.add_text(['";', '\n']) names = ['compoundname', 'briefdescription','detaileddescription', 'includes'] self.subnode_parse(node, ignore = names) elif kind in ('file', 'namespace'): nodes = node.getElementsByTagName('sectiondef') for n in nodes: self.parse(n) # now explicitely handle possibly overloaded member functions. if kind in ['class', 'struct','file', 'namespace']: md_nodes = self.get_memberdef_nodes_and_signatures(node, kind) for sig in md_nodes: self.handle_typical_memberdefs(sig, md_nodes[sig]) def do_memberdef(self, node): """Handle cases outside of class, struct, file or namespace. These are now dealt with by `handle_overloaded_memberfunction`. Do these even exist??? """ prot = node.attributes['prot'].value id = node.attributes['id'].value kind = node.attributes['kind'].value tmp = node.parentNode.parentNode.parentNode compdef = tmp.getElementsByTagName('compounddef')[0] cdef_kind = compdef.attributes['kind'].value if cdef_kind in ('file', 'namespace', 'class', 'struct'): # These cases are now handled by `handle_typical_memberdefs` return if prot != 'public': return first = self.get_specific_nodes(node, ('definition', 'name')) name = self.extract_text(first['name']) if name[:8] == 'operator': # Don't handle operators yet. return if not 'definition' in first or kind in ['variable', 'typedef']: return data = self.extract_text(first['definition']) self.add_text('\n') self.add_text(['/* where did this entry come from??? */', '\n']) self.add_text('%feature("docstring") %s "\n%s' % (data, data)) for n in node.childNodes: if n not in first.values(): self.parse(n) self.add_text(['";', '\n']) # MARK: Entry tag handlers (dont print anything meaningful) def do_sectiondef(self, node): kind = node.attributes['kind'].value if kind in ('public-func', 'func', 'user-defined', ''): self.subnode_parse(node) def do_header(self, node): """For a user defined section def a header field is present which should not be printed as such, so we comment it in the output.""" data = self.extract_text(node) self.add_text('\n/*\n %s \n*/\n' % data) # If our immediate sibling is a 'description' node then we # should comment that out also and remove it from the parent # node's children. parent = node.parentNode idx = parent.childNodes.index(node) if len(parent.childNodes) >= idx + 2: nd = parent.childNodes[idx + 2] if nd.nodeName == 'description': nd = parent.removeChild(nd) self.add_text('\n/*') self.subnode_parse(nd) self.add_text('\n*/\n') def do_member(self, node): kind = node.attributes['kind'].value refid = node.attributes['refid'].value if kind == 'function' and refid[:9] == 'namespace': self.subnode_parse(node) def do_doxygenindex(self, node): self.multi = 1 comps = node.getElementsByTagName('compound') for c in comps: refid = c.attributes['refid'].value fname = refid + '.xml' if not os.path.exists(fname): fname = os.path.join(self.my_dir, fname) if not self.quiet: print("parsing file: %s" % fname) p = Doxy2SWIG(fname, with_function_signature = self.with_function_signature, with_type_info = self.with_type_info, with_constructor_list = self.with_constructor_list, with_attribute_list = self.with_attribute_list, with_overloaded_functions = self.with_overloaded_functions, textwidth = self.textwidth, quiet = self.quiet) p.generate() self.pieces.extend(p.pieces) # MARK: main def main(): usage = __doc__ parser = optparse.OptionParser(usage) parser.add_option("-f", '--function-signature', action='store_true', default=False, dest='f', help='include function signature in the documentation. This is handy when not using swig auto-generated function definitions %feature("autodoc", [0,1])') parser.add_option("-t", '--type-info', action='store_true', default=False, dest='t', help='include type information for arguments in function signatures. This is similar to swig autodoc level 1') parser.add_option("-c", '--constructor-list', action='store_true', default=False, dest='c', help='generate a constructor list for class documentation. Useful for target languages where the object construction should be documented in the class documentation.') parser.add_option("-a", '--attribute-list', action='store_true', default=False, dest='a', help='generate an attributes list for class documentation. Useful for target languages where class attributes should be documented in the class documentation.') parser.add_option("-o", '--overloaded-functions', action='store_true', default=False, dest='o', help='collect all documentation for overloaded functions. Useful for target languages that have no concept of overloaded functions, but also to avoid having to attach the correct docstring to each function overload manually') parser.add_option("-w", '--width', type="int", action='store', dest='w', default=80, help='textwidth for wrapping (default: 80). Note that the generated lines may include 2 additional spaces (for markdown).') parser.add_option("-q", '--quiet', action='store_true', default=False, dest='q', help='be quiet and minimize output') options, args = parser.parse_args() if len(args) != 2: parser.error("no input and output specified") p = Doxy2SWIG(args[0], with_function_signature = options.f, with_type_info = options.t, with_constructor_list = options.c, with_attribute_list = options.a, with_overloaded_functions = options.o, textwidth = options.w, quiet = options.q) p.generate() p.write(args[1]) if __name__ == '__main__': main()
basler/pypylon
scripts/builddoxy2swig/doxy2swig/doxy2swig.py
Doxy2SWIG.parse
python
def parse(self, node): pm = getattr(self, "parse_%s" % node.__class__.__name__) pm(node)
Parse a given node. This function in turn calls the `parse_<nodeType>` functions which handle the respective nodes.
train
https://github.com/basler/pypylon/blob/d3510fa419b1c2b17f3f0b80a5fbb720c7b84008/scripts/builddoxy2swig/doxy2swig/doxy2swig.py#L171-L178
null
class Doxy2SWIG: """Converts Doxygen generated XML files into a file containing docstrings that can be used by SWIG-1.3.x that have support for feature("docstring"). Once the data is parsed it is stored in self.pieces. """ def __init__(self, src, with_function_signature = False, with_type_info = False, with_constructor_list = False, with_attribute_list = False, with_overloaded_functions = False, textwidth = 80, quiet = False): """Initialize the instance given a source object. `src` can be a file or filename. If you do not want to include function definitions from doxygen then set `include_function_definition` to `False`. This is handy since this allows you to use the swig generated function definition using %feature("autodoc", [0,1]). """ # options: self.with_function_signature = with_function_signature self.with_type_info = with_type_info self.with_constructor_list = with_constructor_list self.with_attribute_list = with_attribute_list self.with_overloaded_functions = with_overloaded_functions self.textwidth = textwidth self.quiet = quiet # state: self.indent = 0 self.listitem = '' self.pieces = [] f = my_open_read(src) self.my_dir = os.path.dirname(f.name) self.xmldoc = minidom.parse(f).documentElement f.close() self.pieces.append('\n// File: %s\n' % os.path.basename(f.name)) self.space_re = re.compile(r'\s+') self.lead_spc = re.compile(r'^(%feature\S+\s+\S+\s*?)"\s+(\S)') self.multi = 0 self.ignores = ['inheritancegraph', 'param', 'listofallmembers', 'innerclass', 'name', 'declname', 'incdepgraph', 'invincdepgraph', 'programlisting', 'type', 'references', 'referencedby', 'location', 'collaborationgraph', 'reimplements', 'reimplementedby', 'derivedcompoundref', 'basecompoundref', 'argsstring', 'definition', 'exceptions'] #self.generics = [] def generate(self): """Parses the file set in the initialization. The resulting data is stored in `self.pieces`. """ self.parse(self.xmldoc) def write(self, fname): o = my_open_write(fname) o.write(''.join(self.pieces)) o.write('\n') o.close() def parse_Document(self, node): self.parse(node.documentElement) def parse_Text(self, node): txt = node.data if txt == ' ': # this can happen when two tags follow in a text, e.g., # " ...</emph> <formaula>$..." etc. # here we want to keep the space. self.add_text(txt) return txt = txt.replace('\\', r'\\') txt = txt.replace('"', r'\"') # ignore pure whitespace m = self.space_re.match(txt) if m and len(m.group()) == len(txt): pass else: self.add_text(txt) def parse_Comment(self, node): """Parse a `COMMENT_NODE`. This does nothing for now.""" return def parse_Element(self, node): """Parse an `ELEMENT_NODE`. This calls specific `do_<tagName>` handers for different elements. If no handler is available the `subnode_parse` method is called. All tagNames specified in `self.ignores` are simply ignored. """ name = node.tagName ignores = self.ignores if name in ignores: return attr = "do_%s" % name if hasattr(self, attr): handlerMethod = getattr(self, attr) handlerMethod(node) else: self.subnode_parse(node) #if name not in self.generics: self.generics.append(name) # MARK: Special format parsing def subnode_parse(self, node, pieces=None, indent=0, ignore=[], restrict=None): """Parse the subnodes of a given node. Subnodes with tags in the `ignore` list are ignored. If pieces is given, use this as target for the parse results instead of self.pieces. Indent all lines by the amount given in `indent`. Note that the initial content in `pieces` is not indented. The final result is in any case added to self.pieces.""" if pieces is not None: old_pieces, self.pieces = self.pieces, pieces else: old_pieces = [] if type(indent) is int: indent = indent * ' ' if len(indent) > 0: pieces = ''.join(self.pieces) i_piece = pieces[:len(indent)] if self.pieces[-1:] == ['']: self.pieces = [pieces[len(indent):]] + [''] elif self.pieces != []: self.pieces = [pieces[len(indent):]] self.indent += len(indent) for n in node.childNodes: if restrict is not None: if n.nodeType == n.ELEMENT_NODE and n.tagName in restrict: self.parse(n) elif n.nodeType != n.ELEMENT_NODE or n.tagName not in ignore: self.parse(n) if len(indent) > 0: self.pieces = shift(self.pieces, indent, i_piece) self.indent -= len(indent) old_pieces.extend(self.pieces) self.pieces = old_pieces def surround_parse(self, node, pre_char, post_char): """Parse the subnodes of a given node. Subnodes with tags in the `ignore` list are ignored. Prepend `pre_char` and append `post_char` to the output in self.pieces.""" self.add_text(pre_char) self.subnode_parse(node) self.add_text(post_char) # MARK: Helper functions def get_specific_subnodes(self, node, name, recursive=0): """Given a node and a name, return a list of child `ELEMENT_NODEs`, that have a `tagName` matching the `name`. Search recursively for `recursive` levels. """ children = [x for x in node.childNodes if x.nodeType == x.ELEMENT_NODE] ret = [x for x in children if x.tagName == name] if recursive > 0: for x in children: ret.extend(self.get_specific_subnodes(x, name, recursive-1)) return ret def get_specific_nodes(self, node, names): """Given a node and a sequence of strings in `names`, return a dictionary containing the names as keys and child `ELEMENT_NODEs`, that have a `tagName` equal to the name. """ nodes = [(x.tagName, x) for x in node.childNodes if x.nodeType == x.ELEMENT_NODE and x.tagName in names] return dict(nodes) def add_text(self, value): """Adds text corresponding to `value` into `self.pieces`.""" if isinstance(value, (list, tuple)): self.pieces.extend(value) else: self.pieces.append(value) def start_new_paragraph(self): """Make sure to create an empty line. This is overridden, if the previous text ends with the special marker ''. In that case, nothing is done. """ if self.pieces[-1:] == ['']: # respect special marker return elif self.pieces == []: # first paragraph, add '\n', override with '' self.pieces = ['\n'] elif self.pieces[-1][-1:] != '\n': # previous line not ended self.pieces.extend([' \n' ,'\n']) else: #default self.pieces.append('\n') def add_line_with_subsequent_indent(self, line, indent=4): """Add line of text and wrap such that subsequent lines are indented by `indent` spaces. """ if isinstance(line, (list, tuple)): line = ''.join(line) line = line.strip() width = self.textwidth-self.indent-indent wrapped_lines = textwrap.wrap(line[indent:], width=width) for i in range(len(wrapped_lines)): if wrapped_lines[i] != '': wrapped_lines[i] = indent * ' ' + wrapped_lines[i] self.pieces.append(line[:indent] + '\n'.join(wrapped_lines)[indent:] + ' \n') def extract_text(self, node): """Return the string representation of the node or list of nodes by parsing the subnodes, but returning the result as a string instead of adding it to `self.pieces`. Note that this allows extracting text even if the node is in the ignore list. """ if not isinstance(node, (list, tuple)): node = [node] pieces, self.pieces = self.pieces, [''] for n in node: for sn in n.childNodes: self.parse(sn) ret = ''.join(self.pieces) self.pieces = pieces return ret def get_function_signature(self, node): """Returns the function signature string for memberdef nodes.""" name = self.extract_text(self.get_specific_subnodes(node, 'name')) if self.with_type_info: argsstring = self.extract_text(self.get_specific_subnodes(node, 'argsstring')) else: argsstring = [] param_id = 1 for n_param in self.get_specific_subnodes(node, 'param'): declname = self.extract_text(self.get_specific_subnodes(n_param, 'declname')) if not declname: declname = 'arg' + str(param_id) defval = self.extract_text(self.get_specific_subnodes(n_param, 'defval')) if defval: defval = '=' + defval argsstring.append(declname + defval) param_id = param_id + 1 argsstring = '(' + ', '.join(argsstring) + ')' type = self.extract_text(self.get_specific_subnodes(node, 'type')) function_definition = name + argsstring if type != '' and type != 'void': function_definition = function_definition + ' -> ' + type return '`' + function_definition + '` ' # MARK: Special parsing tasks (need to be called manually) def make_constructor_list(self, constructor_nodes, classname): """Produces the "Constructors" section and the constructor signatures (since swig does not do so for classes) for class docstrings.""" if constructor_nodes == []: return self.add_text(['\n', 'Constructors', '\n', '------------']) for n in constructor_nodes: self.add_text('\n') self.add_line_with_subsequent_indent('* ' + self.get_function_signature(n)) self.subnode_parse(n, pieces = [], indent=4, ignore=['definition', 'name']) def make_attribute_list(self, node): """Produces the "Attributes" section in class docstrings for public member variables (attributes). """ atr_nodes = [] for n in self.get_specific_subnodes(node, 'memberdef', recursive=2): if n.attributes['kind'].value == 'variable' and n.attributes['prot'].value == 'public': atr_nodes.append(n) if not atr_nodes: return self.add_text(['\n', 'Attributes', '\n', '----------']) for n in atr_nodes: name = self.extract_text(self.get_specific_subnodes(n, 'name')) self.add_text(['\n* ', '`', name, '`', ' : ']) self.add_text(['`', self.extract_text(self.get_specific_subnodes(n, 'type')), '`']) self.add_text(' \n') restrict = ['briefdescription', 'detaileddescription'] self.subnode_parse(n, pieces=[''], indent=4, restrict=restrict) def get_memberdef_nodes_and_signatures(self, node, kind): """Collects the memberdef nodes and corresponding signatures that correspond to public function entries that are at most depth 2 deeper than the current (compounddef) node. Returns a dictionary with function signatures (what swig expects after the %feature directive) as keys, and a list of corresponding memberdef nodes as values.""" sig_dict = {} sig_prefix = '' if kind in ('file', 'namespace'): ns_node = node.getElementsByTagName('innernamespace') if not ns_node and kind == 'namespace': ns_node = node.getElementsByTagName('compoundname') if ns_node: sig_prefix = self.extract_text(ns_node[0]) + '::' elif kind in ('class', 'struct'): # Get the full function name. cn_node = node.getElementsByTagName('compoundname') sig_prefix = self.extract_text(cn_node[0]) + '::' md_nodes = self.get_specific_subnodes(node, 'memberdef', recursive=2) for n in md_nodes: if n.attributes['prot'].value != 'public': continue if n.attributes['kind'].value in ['variable', 'typedef']: continue if not self.get_specific_subnodes(n, 'definition'): continue name = self.extract_text(self.get_specific_subnodes(n, 'name')) if name[:8] == 'operator': continue sig = sig_prefix + name if sig in sig_dict: sig_dict[sig].append(n) else: sig_dict[sig] = [n] return sig_dict def handle_typical_memberdefs_no_overload(self, signature, memberdef_nodes): """Produce standard documentation for memberdef_nodes.""" for n in memberdef_nodes: self.add_text(['\n', '%feature("docstring") ', signature, ' "', '\n']) if self.with_function_signature: self.add_line_with_subsequent_indent(self.get_function_signature(n)) self.subnode_parse(n, pieces=[], ignore=['definition', 'name']) self.add_text(['";', '\n']) def handle_typical_memberdefs(self, signature, memberdef_nodes): """Produces docstring entries containing an "Overloaded function" section with the documentation for each overload, if the function is overloaded and self.with_overloaded_functions is set. Else, produce normal documentation. """ if len(memberdef_nodes) == 1 or not self.with_overloaded_functions: self.handle_typical_memberdefs_no_overload(signature, memberdef_nodes) return self.add_text(['\n', '%feature("docstring") ', signature, ' "', '\n']) if self.with_function_signature: for n in memberdef_nodes: self.add_line_with_subsequent_indent(self.get_function_signature(n)) self.add_text('\n') self.add_text(['Overloaded function', '\n', '-------------------']) for n in memberdef_nodes: self.add_text('\n') self.add_line_with_subsequent_indent('* ' + self.get_function_signature(n)) self.subnode_parse(n, pieces=[], indent=4, ignore=['definition', 'name']) self.add_text(['";', '\n']) # MARK: Tag handlers def do_linebreak(self, node): self.add_text(' ') def do_ndash(self, node): self.add_text('--') def do_mdash(self, node): self.add_text('---') def do_emphasis(self, node): self.surround_parse(node, '*', '*') def do_bold(self, node): self.surround_parse(node, '**', '**') def do_computeroutput(self, node): self.surround_parse(node, '`', '`') def do_heading(self, node): self.start_new_paragraph() pieces, self.pieces = self.pieces, [''] level = int(node.attributes['level'].value) self.subnode_parse(node) if level == 1: self.pieces.insert(0, '\n') self.add_text(['\n', len(''.join(self.pieces).strip()) * '=']) elif level == 2: self.add_text(['\n', len(''.join(self.pieces).strip()) * '-']) elif level >= 3: self.pieces.insert(0, level * '#' + ' ') # make following text have no gap to the heading: pieces.extend([''.join(self.pieces) + ' \n', '']) self.pieces = pieces def do_verbatim(self, node): self.start_new_paragraph() self.subnode_parse(node, pieces=[''], indent=4) def do_blockquote(self, node): self.start_new_paragraph() self.subnode_parse(node, pieces=[''], indent='> ') def do_hruler(self, node): self.start_new_paragraph() self.add_text('* * * * * \n') def do_includes(self, node): self.add_text('\nC++ includes: ') self.subnode_parse(node) self.add_text('\n') # MARK: Para tag handler def do_para(self, node): """This is the only place where text wrapping is automatically performed. Generally, this function parses the node (locally), wraps the text, and then adds the result to self.pieces. However, it may be convenient to allow the previous content of self.pieces to be included in the text wrapping. For this, use the following *convention*: If self.pieces ends with '', treat the _previous_ entry as part of the current paragraph. Else, insert new-line and start a new paragraph and "wrapping context". Paragraphs always end with ' \n', but if the parsed content ends with the special symbol '', this is passed on. """ if self.pieces[-1:] == ['']: pieces, self.pieces = self.pieces[:-2], self.pieces[-2:-1] else: self.add_text('\n') pieces, self.pieces = self.pieces, [''] self.subnode_parse(node) dont_end_paragraph = self.pieces[-1:] == [''] # Now do the text wrapping: width = self.textwidth - self.indent wrapped_para = [] for line in ''.join(self.pieces).splitlines(): keep_markdown_newline = line[-2:] == ' ' w_line = textwrap.wrap(line, width=width, break_long_words=False) if w_line == []: w_line = [''] if keep_markdown_newline: w_line[-1] = w_line[-1] + ' ' for wl in w_line: wrapped_para.append(wl + '\n') if wrapped_para: if wrapped_para[-1][-3:] != ' \n': wrapped_para[-1] = wrapped_para[-1][:-1] + ' \n' if dont_end_paragraph: wrapped_para.append('') pieces.extend(wrapped_para) self.pieces = pieces # MARK: List tag handlers def do_itemizedlist(self, node): if self.listitem == '': self.start_new_paragraph() elif self.pieces != [] and self.pieces[-1:] != ['']: self.add_text('\n') listitem = self.listitem if self.listitem in ['*', '-']: self.listitem = '-' else: self.listitem = '*' self.subnode_parse(node) self.listitem = listitem def do_orderedlist(self, node): if self.listitem == '': self.start_new_paragraph() elif self.pieces != [] and self.pieces[-1:] != ['']: self.add_text('\n') listitem = self.listitem self.listitem = 0 self.subnode_parse(node) self.listitem = listitem def do_listitem(self, node): try: self.listitem = int(self.listitem) + 1 item = str(self.listitem) + '. ' except: item = str(self.listitem) + ' ' self.subnode_parse(node, item, indent=4) # MARK: Parameter list tag handlers def do_parameterlist(self, node): self.start_new_paragraph() text = 'unknown' for key, val in node.attributes.items(): if key == 'kind': if val == 'param': text = 'Parameters' elif val == 'exception': text = 'Exceptions' elif val == 'retval': text = 'Returns' else: text = val break if self.indent == 0: self.add_text([text, '\n', len(text) * '-', '\n']) else: self.add_text([text, ': \n']) self.subnode_parse(node) def do_parameteritem(self, node): self.subnode_parse(node, pieces=['* ', '']) def do_parameternamelist(self, node): self.subnode_parse(node) self.add_text([' :', ' \n']) def do_parametername(self, node): if self.pieces != [] and self.pieces != ['* ', '']: self.add_text(', ') data = self.extract_text(node) self.add_text(['`', data, '`']) def do_parameterdescription(self, node): self.subnode_parse(node, pieces=[''], indent=4) # MARK: Section tag handler def do_simplesect(self, node): kind = node.attributes['kind'].value if kind in ('date', 'rcs', 'version'): return self.start_new_paragraph() if kind == 'warning': self.subnode_parse(node, pieces=['**Warning**: ',''], indent=4) elif kind == 'see': self.subnode_parse(node, pieces=['See also: ',''], indent=4) elif kind == 'return': if self.indent == 0: pieces = ['Returns', '\n', len('Returns') * '-', '\n', ''] else: pieces = ['Returns:', '\n', ''] self.subnode_parse(node, pieces=pieces) else: self.subnode_parse(node, pieces=[kind + ': ',''], indent=4) # MARK: %feature("docstring") producing tag handlers def do_compounddef(self, node): """This produces %feature("docstring") entries for classes, and handles class, namespace and file memberdef entries specially to allow for overloaded functions. For other cases, passes parsing on to standard handlers (which may produce unexpected results). """ kind = node.attributes['kind'].value if kind in ('class', 'struct'): prot = node.attributes['prot'].value if prot != 'public': return self.add_text('\n\n') classdefn = self.extract_text(self.get_specific_subnodes(node, 'compoundname')) classname = classdefn.split('::')[-1] self.add_text('%%feature("docstring") %s "\n' % classdefn) if self.with_constructor_list: constructor_nodes = [] for n in self.get_specific_subnodes(node, 'memberdef', recursive=2): if n.attributes['prot'].value == 'public': if self.extract_text(self.get_specific_subnodes(n, 'definition')) == classdefn + '::' + classname: constructor_nodes.append(n) for n in constructor_nodes: self.add_line_with_subsequent_indent(self.get_function_signature(n)) names = ('briefdescription','detaileddescription') sub_dict = self.get_specific_nodes(node, names) for n in ('briefdescription','detaileddescription'): if n in sub_dict: self.parse(sub_dict[n]) if self.with_constructor_list: self.make_constructor_list(constructor_nodes, classname) if self.with_attribute_list: self.make_attribute_list(node) sub_list = self.get_specific_subnodes(node, 'includes') if sub_list: self.parse(sub_list[0]) self.add_text(['";', '\n']) names = ['compoundname', 'briefdescription','detaileddescription', 'includes'] self.subnode_parse(node, ignore = names) elif kind in ('file', 'namespace'): nodes = node.getElementsByTagName('sectiondef') for n in nodes: self.parse(n) # now explicitely handle possibly overloaded member functions. if kind in ['class', 'struct','file', 'namespace']: md_nodes = self.get_memberdef_nodes_and_signatures(node, kind) for sig in md_nodes: self.handle_typical_memberdefs(sig, md_nodes[sig]) def do_memberdef(self, node): """Handle cases outside of class, struct, file or namespace. These are now dealt with by `handle_overloaded_memberfunction`. Do these even exist??? """ prot = node.attributes['prot'].value id = node.attributes['id'].value kind = node.attributes['kind'].value tmp = node.parentNode.parentNode.parentNode compdef = tmp.getElementsByTagName('compounddef')[0] cdef_kind = compdef.attributes['kind'].value if cdef_kind in ('file', 'namespace', 'class', 'struct'): # These cases are now handled by `handle_typical_memberdefs` return if prot != 'public': return first = self.get_specific_nodes(node, ('definition', 'name')) name = self.extract_text(first['name']) if name[:8] == 'operator': # Don't handle operators yet. return if not 'definition' in first or kind in ['variable', 'typedef']: return data = self.extract_text(first['definition']) self.add_text('\n') self.add_text(['/* where did this entry come from??? */', '\n']) self.add_text('%feature("docstring") %s "\n%s' % (data, data)) for n in node.childNodes: if n not in first.values(): self.parse(n) self.add_text(['";', '\n']) # MARK: Entry tag handlers (dont print anything meaningful) def do_sectiondef(self, node): kind = node.attributes['kind'].value if kind in ('public-func', 'func', 'user-defined', ''): self.subnode_parse(node) def do_header(self, node): """For a user defined section def a header field is present which should not be printed as such, so we comment it in the output.""" data = self.extract_text(node) self.add_text('\n/*\n %s \n*/\n' % data) # If our immediate sibling is a 'description' node then we # should comment that out also and remove it from the parent # node's children. parent = node.parentNode idx = parent.childNodes.index(node) if len(parent.childNodes) >= idx + 2: nd = parent.childNodes[idx + 2] if nd.nodeName == 'description': nd = parent.removeChild(nd) self.add_text('\n/*') self.subnode_parse(nd) self.add_text('\n*/\n') def do_member(self, node): kind = node.attributes['kind'].value refid = node.attributes['refid'].value if kind == 'function' and refid[:9] == 'namespace': self.subnode_parse(node) def do_doxygenindex(self, node): self.multi = 1 comps = node.getElementsByTagName('compound') for c in comps: refid = c.attributes['refid'].value fname = refid + '.xml' if not os.path.exists(fname): fname = os.path.join(self.my_dir, fname) if not self.quiet: print("parsing file: %s" % fname) p = Doxy2SWIG(fname, with_function_signature = self.with_function_signature, with_type_info = self.with_type_info, with_constructor_list = self.with_constructor_list, with_attribute_list = self.with_attribute_list, with_overloaded_functions = self.with_overloaded_functions, textwidth = self.textwidth, quiet = self.quiet) p.generate() self.pieces.extend(p.pieces)
basler/pypylon
scripts/builddoxy2swig/doxy2swig/doxy2swig.py
Doxy2SWIG.subnode_parse
python
def subnode_parse(self, node, pieces=None, indent=0, ignore=[], restrict=None): if pieces is not None: old_pieces, self.pieces = self.pieces, pieces else: old_pieces = [] if type(indent) is int: indent = indent * ' ' if len(indent) > 0: pieces = ''.join(self.pieces) i_piece = pieces[:len(indent)] if self.pieces[-1:] == ['']: self.pieces = [pieces[len(indent):]] + [''] elif self.pieces != []: self.pieces = [pieces[len(indent):]] self.indent += len(indent) for n in node.childNodes: if restrict is not None: if n.nodeType == n.ELEMENT_NODE and n.tagName in restrict: self.parse(n) elif n.nodeType != n.ELEMENT_NODE or n.tagName not in ignore: self.parse(n) if len(indent) > 0: self.pieces = shift(self.pieces, indent, i_piece) self.indent -= len(indent) old_pieces.extend(self.pieces) self.pieces = old_pieces
Parse the subnodes of a given node. Subnodes with tags in the `ignore` list are ignored. If pieces is given, use this as target for the parse results instead of self.pieces. Indent all lines by the amount given in `indent`. Note that the initial content in `pieces` is not indented. The final result is in any case added to self.pieces.
train
https://github.com/basler/pypylon/blob/d3510fa419b1c2b17f3f0b80a5fbb720c7b84008/scripts/builddoxy2swig/doxy2swig/doxy2swig.py#L224-L254
[ "def shift(txt, indent = ' ', prepend = ''):\n \"\"\"Return a list corresponding to the lines of text in the `txt` list\n indented by `indent`. Prepend instead the string given in `prepend` to the\n beginning of the first line. Note that if len(prepend) > len(indent), then\n `prepend` will be truncated (doing better is tricky!). This preserves a \n special '' entry at the end of `txt` (see `do_para` for the meaning).\n \"\"\"\n if type(indent) is int:\n indent = indent * ' '\n special_end = txt[-1:] == ['']\n lines = ''.join(txt).splitlines(True)\n for i in range(1,len(lines)):\n if lines[i].strip() or indent.strip():\n lines[i] = indent + lines[i]\n if not lines:\n return prepend\n prepend = prepend[:len(indent)]\n indent = indent[len(prepend):]\n lines[0] = prepend + indent + lines[0]\n ret = [''.join(lines)]\n if special_end:\n ret.append('')\n return ret\n", "def parse(self, node):\n \"\"\"Parse a given node. This function in turn calls the\n `parse_<nodeType>` functions which handle the respective\n nodes.\n\n \"\"\"\n pm = getattr(self, \"parse_%s\" % node.__class__.__name__)\n pm(node)\n" ]
class Doxy2SWIG: """Converts Doxygen generated XML files into a file containing docstrings that can be used by SWIG-1.3.x that have support for feature("docstring"). Once the data is parsed it is stored in self.pieces. """ def __init__(self, src, with_function_signature = False, with_type_info = False, with_constructor_list = False, with_attribute_list = False, with_overloaded_functions = False, textwidth = 80, quiet = False): """Initialize the instance given a source object. `src` can be a file or filename. If you do not want to include function definitions from doxygen then set `include_function_definition` to `False`. This is handy since this allows you to use the swig generated function definition using %feature("autodoc", [0,1]). """ # options: self.with_function_signature = with_function_signature self.with_type_info = with_type_info self.with_constructor_list = with_constructor_list self.with_attribute_list = with_attribute_list self.with_overloaded_functions = with_overloaded_functions self.textwidth = textwidth self.quiet = quiet # state: self.indent = 0 self.listitem = '' self.pieces = [] f = my_open_read(src) self.my_dir = os.path.dirname(f.name) self.xmldoc = minidom.parse(f).documentElement f.close() self.pieces.append('\n// File: %s\n' % os.path.basename(f.name)) self.space_re = re.compile(r'\s+') self.lead_spc = re.compile(r'^(%feature\S+\s+\S+\s*?)"\s+(\S)') self.multi = 0 self.ignores = ['inheritancegraph', 'param', 'listofallmembers', 'innerclass', 'name', 'declname', 'incdepgraph', 'invincdepgraph', 'programlisting', 'type', 'references', 'referencedby', 'location', 'collaborationgraph', 'reimplements', 'reimplementedby', 'derivedcompoundref', 'basecompoundref', 'argsstring', 'definition', 'exceptions'] #self.generics = [] def generate(self): """Parses the file set in the initialization. The resulting data is stored in `self.pieces`. """ self.parse(self.xmldoc) def write(self, fname): o = my_open_write(fname) o.write(''.join(self.pieces)) o.write('\n') o.close() def parse(self, node): """Parse a given node. This function in turn calls the `parse_<nodeType>` functions which handle the respective nodes. """ pm = getattr(self, "parse_%s" % node.__class__.__name__) pm(node) def parse_Document(self, node): self.parse(node.documentElement) def parse_Text(self, node): txt = node.data if txt == ' ': # this can happen when two tags follow in a text, e.g., # " ...</emph> <formaula>$..." etc. # here we want to keep the space. self.add_text(txt) return txt = txt.replace('\\', r'\\') txt = txt.replace('"', r'\"') # ignore pure whitespace m = self.space_re.match(txt) if m and len(m.group()) == len(txt): pass else: self.add_text(txt) def parse_Comment(self, node): """Parse a `COMMENT_NODE`. This does nothing for now.""" return def parse_Element(self, node): """Parse an `ELEMENT_NODE`. This calls specific `do_<tagName>` handers for different elements. If no handler is available the `subnode_parse` method is called. All tagNames specified in `self.ignores` are simply ignored. """ name = node.tagName ignores = self.ignores if name in ignores: return attr = "do_%s" % name if hasattr(self, attr): handlerMethod = getattr(self, attr) handlerMethod(node) else: self.subnode_parse(node) #if name not in self.generics: self.generics.append(name) # MARK: Special format parsing def surround_parse(self, node, pre_char, post_char): """Parse the subnodes of a given node. Subnodes with tags in the `ignore` list are ignored. Prepend `pre_char` and append `post_char` to the output in self.pieces.""" self.add_text(pre_char) self.subnode_parse(node) self.add_text(post_char) # MARK: Helper functions def get_specific_subnodes(self, node, name, recursive=0): """Given a node and a name, return a list of child `ELEMENT_NODEs`, that have a `tagName` matching the `name`. Search recursively for `recursive` levels. """ children = [x for x in node.childNodes if x.nodeType == x.ELEMENT_NODE] ret = [x for x in children if x.tagName == name] if recursive > 0: for x in children: ret.extend(self.get_specific_subnodes(x, name, recursive-1)) return ret def get_specific_nodes(self, node, names): """Given a node and a sequence of strings in `names`, return a dictionary containing the names as keys and child `ELEMENT_NODEs`, that have a `tagName` equal to the name. """ nodes = [(x.tagName, x) for x in node.childNodes if x.nodeType == x.ELEMENT_NODE and x.tagName in names] return dict(nodes) def add_text(self, value): """Adds text corresponding to `value` into `self.pieces`.""" if isinstance(value, (list, tuple)): self.pieces.extend(value) else: self.pieces.append(value) def start_new_paragraph(self): """Make sure to create an empty line. This is overridden, if the previous text ends with the special marker ''. In that case, nothing is done. """ if self.pieces[-1:] == ['']: # respect special marker return elif self.pieces == []: # first paragraph, add '\n', override with '' self.pieces = ['\n'] elif self.pieces[-1][-1:] != '\n': # previous line not ended self.pieces.extend([' \n' ,'\n']) else: #default self.pieces.append('\n') def add_line_with_subsequent_indent(self, line, indent=4): """Add line of text and wrap such that subsequent lines are indented by `indent` spaces. """ if isinstance(line, (list, tuple)): line = ''.join(line) line = line.strip() width = self.textwidth-self.indent-indent wrapped_lines = textwrap.wrap(line[indent:], width=width) for i in range(len(wrapped_lines)): if wrapped_lines[i] != '': wrapped_lines[i] = indent * ' ' + wrapped_lines[i] self.pieces.append(line[:indent] + '\n'.join(wrapped_lines)[indent:] + ' \n') def extract_text(self, node): """Return the string representation of the node or list of nodes by parsing the subnodes, but returning the result as a string instead of adding it to `self.pieces`. Note that this allows extracting text even if the node is in the ignore list. """ if not isinstance(node, (list, tuple)): node = [node] pieces, self.pieces = self.pieces, [''] for n in node: for sn in n.childNodes: self.parse(sn) ret = ''.join(self.pieces) self.pieces = pieces return ret def get_function_signature(self, node): """Returns the function signature string for memberdef nodes.""" name = self.extract_text(self.get_specific_subnodes(node, 'name')) if self.with_type_info: argsstring = self.extract_text(self.get_specific_subnodes(node, 'argsstring')) else: argsstring = [] param_id = 1 for n_param in self.get_specific_subnodes(node, 'param'): declname = self.extract_text(self.get_specific_subnodes(n_param, 'declname')) if not declname: declname = 'arg' + str(param_id) defval = self.extract_text(self.get_specific_subnodes(n_param, 'defval')) if defval: defval = '=' + defval argsstring.append(declname + defval) param_id = param_id + 1 argsstring = '(' + ', '.join(argsstring) + ')' type = self.extract_text(self.get_specific_subnodes(node, 'type')) function_definition = name + argsstring if type != '' and type != 'void': function_definition = function_definition + ' -> ' + type return '`' + function_definition + '` ' # MARK: Special parsing tasks (need to be called manually) def make_constructor_list(self, constructor_nodes, classname): """Produces the "Constructors" section and the constructor signatures (since swig does not do so for classes) for class docstrings.""" if constructor_nodes == []: return self.add_text(['\n', 'Constructors', '\n', '------------']) for n in constructor_nodes: self.add_text('\n') self.add_line_with_subsequent_indent('* ' + self.get_function_signature(n)) self.subnode_parse(n, pieces = [], indent=4, ignore=['definition', 'name']) def make_attribute_list(self, node): """Produces the "Attributes" section in class docstrings for public member variables (attributes). """ atr_nodes = [] for n in self.get_specific_subnodes(node, 'memberdef', recursive=2): if n.attributes['kind'].value == 'variable' and n.attributes['prot'].value == 'public': atr_nodes.append(n) if not atr_nodes: return self.add_text(['\n', 'Attributes', '\n', '----------']) for n in atr_nodes: name = self.extract_text(self.get_specific_subnodes(n, 'name')) self.add_text(['\n* ', '`', name, '`', ' : ']) self.add_text(['`', self.extract_text(self.get_specific_subnodes(n, 'type')), '`']) self.add_text(' \n') restrict = ['briefdescription', 'detaileddescription'] self.subnode_parse(n, pieces=[''], indent=4, restrict=restrict) def get_memberdef_nodes_and_signatures(self, node, kind): """Collects the memberdef nodes and corresponding signatures that correspond to public function entries that are at most depth 2 deeper than the current (compounddef) node. Returns a dictionary with function signatures (what swig expects after the %feature directive) as keys, and a list of corresponding memberdef nodes as values.""" sig_dict = {} sig_prefix = '' if kind in ('file', 'namespace'): ns_node = node.getElementsByTagName('innernamespace') if not ns_node and kind == 'namespace': ns_node = node.getElementsByTagName('compoundname') if ns_node: sig_prefix = self.extract_text(ns_node[0]) + '::' elif kind in ('class', 'struct'): # Get the full function name. cn_node = node.getElementsByTagName('compoundname') sig_prefix = self.extract_text(cn_node[0]) + '::' md_nodes = self.get_specific_subnodes(node, 'memberdef', recursive=2) for n in md_nodes: if n.attributes['prot'].value != 'public': continue if n.attributes['kind'].value in ['variable', 'typedef']: continue if not self.get_specific_subnodes(n, 'definition'): continue name = self.extract_text(self.get_specific_subnodes(n, 'name')) if name[:8] == 'operator': continue sig = sig_prefix + name if sig in sig_dict: sig_dict[sig].append(n) else: sig_dict[sig] = [n] return sig_dict def handle_typical_memberdefs_no_overload(self, signature, memberdef_nodes): """Produce standard documentation for memberdef_nodes.""" for n in memberdef_nodes: self.add_text(['\n', '%feature("docstring") ', signature, ' "', '\n']) if self.with_function_signature: self.add_line_with_subsequent_indent(self.get_function_signature(n)) self.subnode_parse(n, pieces=[], ignore=['definition', 'name']) self.add_text(['";', '\n']) def handle_typical_memberdefs(self, signature, memberdef_nodes): """Produces docstring entries containing an "Overloaded function" section with the documentation for each overload, if the function is overloaded and self.with_overloaded_functions is set. Else, produce normal documentation. """ if len(memberdef_nodes) == 1 or not self.with_overloaded_functions: self.handle_typical_memberdefs_no_overload(signature, memberdef_nodes) return self.add_text(['\n', '%feature("docstring") ', signature, ' "', '\n']) if self.with_function_signature: for n in memberdef_nodes: self.add_line_with_subsequent_indent(self.get_function_signature(n)) self.add_text('\n') self.add_text(['Overloaded function', '\n', '-------------------']) for n in memberdef_nodes: self.add_text('\n') self.add_line_with_subsequent_indent('* ' + self.get_function_signature(n)) self.subnode_parse(n, pieces=[], indent=4, ignore=['definition', 'name']) self.add_text(['";', '\n']) # MARK: Tag handlers def do_linebreak(self, node): self.add_text(' ') def do_ndash(self, node): self.add_text('--') def do_mdash(self, node): self.add_text('---') def do_emphasis(self, node): self.surround_parse(node, '*', '*') def do_bold(self, node): self.surround_parse(node, '**', '**') def do_computeroutput(self, node): self.surround_parse(node, '`', '`') def do_heading(self, node): self.start_new_paragraph() pieces, self.pieces = self.pieces, [''] level = int(node.attributes['level'].value) self.subnode_parse(node) if level == 1: self.pieces.insert(0, '\n') self.add_text(['\n', len(''.join(self.pieces).strip()) * '=']) elif level == 2: self.add_text(['\n', len(''.join(self.pieces).strip()) * '-']) elif level >= 3: self.pieces.insert(0, level * '#' + ' ') # make following text have no gap to the heading: pieces.extend([''.join(self.pieces) + ' \n', '']) self.pieces = pieces def do_verbatim(self, node): self.start_new_paragraph() self.subnode_parse(node, pieces=[''], indent=4) def do_blockquote(self, node): self.start_new_paragraph() self.subnode_parse(node, pieces=[''], indent='> ') def do_hruler(self, node): self.start_new_paragraph() self.add_text('* * * * * \n') def do_includes(self, node): self.add_text('\nC++ includes: ') self.subnode_parse(node) self.add_text('\n') # MARK: Para tag handler def do_para(self, node): """This is the only place where text wrapping is automatically performed. Generally, this function parses the node (locally), wraps the text, and then adds the result to self.pieces. However, it may be convenient to allow the previous content of self.pieces to be included in the text wrapping. For this, use the following *convention*: If self.pieces ends with '', treat the _previous_ entry as part of the current paragraph. Else, insert new-line and start a new paragraph and "wrapping context". Paragraphs always end with ' \n', but if the parsed content ends with the special symbol '', this is passed on. """ if self.pieces[-1:] == ['']: pieces, self.pieces = self.pieces[:-2], self.pieces[-2:-1] else: self.add_text('\n') pieces, self.pieces = self.pieces, [''] self.subnode_parse(node) dont_end_paragraph = self.pieces[-1:] == [''] # Now do the text wrapping: width = self.textwidth - self.indent wrapped_para = [] for line in ''.join(self.pieces).splitlines(): keep_markdown_newline = line[-2:] == ' ' w_line = textwrap.wrap(line, width=width, break_long_words=False) if w_line == []: w_line = [''] if keep_markdown_newline: w_line[-1] = w_line[-1] + ' ' for wl in w_line: wrapped_para.append(wl + '\n') if wrapped_para: if wrapped_para[-1][-3:] != ' \n': wrapped_para[-1] = wrapped_para[-1][:-1] + ' \n' if dont_end_paragraph: wrapped_para.append('') pieces.extend(wrapped_para) self.pieces = pieces # MARK: List tag handlers def do_itemizedlist(self, node): if self.listitem == '': self.start_new_paragraph() elif self.pieces != [] and self.pieces[-1:] != ['']: self.add_text('\n') listitem = self.listitem if self.listitem in ['*', '-']: self.listitem = '-' else: self.listitem = '*' self.subnode_parse(node) self.listitem = listitem def do_orderedlist(self, node): if self.listitem == '': self.start_new_paragraph() elif self.pieces != [] and self.pieces[-1:] != ['']: self.add_text('\n') listitem = self.listitem self.listitem = 0 self.subnode_parse(node) self.listitem = listitem def do_listitem(self, node): try: self.listitem = int(self.listitem) + 1 item = str(self.listitem) + '. ' except: item = str(self.listitem) + ' ' self.subnode_parse(node, item, indent=4) # MARK: Parameter list tag handlers def do_parameterlist(self, node): self.start_new_paragraph() text = 'unknown' for key, val in node.attributes.items(): if key == 'kind': if val == 'param': text = 'Parameters' elif val == 'exception': text = 'Exceptions' elif val == 'retval': text = 'Returns' else: text = val break if self.indent == 0: self.add_text([text, '\n', len(text) * '-', '\n']) else: self.add_text([text, ': \n']) self.subnode_parse(node) def do_parameteritem(self, node): self.subnode_parse(node, pieces=['* ', '']) def do_parameternamelist(self, node): self.subnode_parse(node) self.add_text([' :', ' \n']) def do_parametername(self, node): if self.pieces != [] and self.pieces != ['* ', '']: self.add_text(', ') data = self.extract_text(node) self.add_text(['`', data, '`']) def do_parameterdescription(self, node): self.subnode_parse(node, pieces=[''], indent=4) # MARK: Section tag handler def do_simplesect(self, node): kind = node.attributes['kind'].value if kind in ('date', 'rcs', 'version'): return self.start_new_paragraph() if kind == 'warning': self.subnode_parse(node, pieces=['**Warning**: ',''], indent=4) elif kind == 'see': self.subnode_parse(node, pieces=['See also: ',''], indent=4) elif kind == 'return': if self.indent == 0: pieces = ['Returns', '\n', len('Returns') * '-', '\n', ''] else: pieces = ['Returns:', '\n', ''] self.subnode_parse(node, pieces=pieces) else: self.subnode_parse(node, pieces=[kind + ': ',''], indent=4) # MARK: %feature("docstring") producing tag handlers def do_compounddef(self, node): """This produces %feature("docstring") entries for classes, and handles class, namespace and file memberdef entries specially to allow for overloaded functions. For other cases, passes parsing on to standard handlers (which may produce unexpected results). """ kind = node.attributes['kind'].value if kind in ('class', 'struct'): prot = node.attributes['prot'].value if prot != 'public': return self.add_text('\n\n') classdefn = self.extract_text(self.get_specific_subnodes(node, 'compoundname')) classname = classdefn.split('::')[-1] self.add_text('%%feature("docstring") %s "\n' % classdefn) if self.with_constructor_list: constructor_nodes = [] for n in self.get_specific_subnodes(node, 'memberdef', recursive=2): if n.attributes['prot'].value == 'public': if self.extract_text(self.get_specific_subnodes(n, 'definition')) == classdefn + '::' + classname: constructor_nodes.append(n) for n in constructor_nodes: self.add_line_with_subsequent_indent(self.get_function_signature(n)) names = ('briefdescription','detaileddescription') sub_dict = self.get_specific_nodes(node, names) for n in ('briefdescription','detaileddescription'): if n in sub_dict: self.parse(sub_dict[n]) if self.with_constructor_list: self.make_constructor_list(constructor_nodes, classname) if self.with_attribute_list: self.make_attribute_list(node) sub_list = self.get_specific_subnodes(node, 'includes') if sub_list: self.parse(sub_list[0]) self.add_text(['";', '\n']) names = ['compoundname', 'briefdescription','detaileddescription', 'includes'] self.subnode_parse(node, ignore = names) elif kind in ('file', 'namespace'): nodes = node.getElementsByTagName('sectiondef') for n in nodes: self.parse(n) # now explicitely handle possibly overloaded member functions. if kind in ['class', 'struct','file', 'namespace']: md_nodes = self.get_memberdef_nodes_and_signatures(node, kind) for sig in md_nodes: self.handle_typical_memberdefs(sig, md_nodes[sig]) def do_memberdef(self, node): """Handle cases outside of class, struct, file or namespace. These are now dealt with by `handle_overloaded_memberfunction`. Do these even exist??? """ prot = node.attributes['prot'].value id = node.attributes['id'].value kind = node.attributes['kind'].value tmp = node.parentNode.parentNode.parentNode compdef = tmp.getElementsByTagName('compounddef')[0] cdef_kind = compdef.attributes['kind'].value if cdef_kind in ('file', 'namespace', 'class', 'struct'): # These cases are now handled by `handle_typical_memberdefs` return if prot != 'public': return first = self.get_specific_nodes(node, ('definition', 'name')) name = self.extract_text(first['name']) if name[:8] == 'operator': # Don't handle operators yet. return if not 'definition' in first or kind in ['variable', 'typedef']: return data = self.extract_text(first['definition']) self.add_text('\n') self.add_text(['/* where did this entry come from??? */', '\n']) self.add_text('%feature("docstring") %s "\n%s' % (data, data)) for n in node.childNodes: if n not in first.values(): self.parse(n) self.add_text(['";', '\n']) # MARK: Entry tag handlers (dont print anything meaningful) def do_sectiondef(self, node): kind = node.attributes['kind'].value if kind in ('public-func', 'func', 'user-defined', ''): self.subnode_parse(node) def do_header(self, node): """For a user defined section def a header field is present which should not be printed as such, so we comment it in the output.""" data = self.extract_text(node) self.add_text('\n/*\n %s \n*/\n' % data) # If our immediate sibling is a 'description' node then we # should comment that out also and remove it from the parent # node's children. parent = node.parentNode idx = parent.childNodes.index(node) if len(parent.childNodes) >= idx + 2: nd = parent.childNodes[idx + 2] if nd.nodeName == 'description': nd = parent.removeChild(nd) self.add_text('\n/*') self.subnode_parse(nd) self.add_text('\n*/\n') def do_member(self, node): kind = node.attributes['kind'].value refid = node.attributes['refid'].value if kind == 'function' and refid[:9] == 'namespace': self.subnode_parse(node) def do_doxygenindex(self, node): self.multi = 1 comps = node.getElementsByTagName('compound') for c in comps: refid = c.attributes['refid'].value fname = refid + '.xml' if not os.path.exists(fname): fname = os.path.join(self.my_dir, fname) if not self.quiet: print("parsing file: %s" % fname) p = Doxy2SWIG(fname, with_function_signature = self.with_function_signature, with_type_info = self.with_type_info, with_constructor_list = self.with_constructor_list, with_attribute_list = self.with_attribute_list, with_overloaded_functions = self.with_overloaded_functions, textwidth = self.textwidth, quiet = self.quiet) p.generate() self.pieces.extend(p.pieces)
basler/pypylon
scripts/builddoxy2swig/doxy2swig/doxy2swig.py
Doxy2SWIG.surround_parse
python
def surround_parse(self, node, pre_char, post_char): self.add_text(pre_char) self.subnode_parse(node) self.add_text(post_char)
Parse the subnodes of a given node. Subnodes with tags in the `ignore` list are ignored. Prepend `pre_char` and append `post_char` to the output in self.pieces.
train
https://github.com/basler/pypylon/blob/d3510fa419b1c2b17f3f0b80a5fbb720c7b84008/scripts/builddoxy2swig/doxy2swig/doxy2swig.py#L256-L262
[ "def subnode_parse(self, node, pieces=None, indent=0, ignore=[], restrict=None):\n \"\"\"Parse the subnodes of a given node. Subnodes with tags in the\n `ignore` list are ignored. If pieces is given, use this as target for\n the parse results instead of self.pieces. Indent all lines by the amount\n given in `indent`. Note that the initial content in `pieces` is not\n indented. The final result is in any case added to self.pieces.\"\"\"\n if pieces is not None:\n old_pieces, self.pieces = self.pieces, pieces\n else:\n old_pieces = []\n if type(indent) is int:\n indent = indent * ' '\n if len(indent) > 0:\n pieces = ''.join(self.pieces)\n i_piece = pieces[:len(indent)]\n if self.pieces[-1:] == ['']:\n self.pieces = [pieces[len(indent):]] + ['']\n elif self.pieces != []:\n self.pieces = [pieces[len(indent):]]\n self.indent += len(indent)\n for n in node.childNodes:\n if restrict is not None:\n if n.nodeType == n.ELEMENT_NODE and n.tagName in restrict:\n self.parse(n)\n elif n.nodeType != n.ELEMENT_NODE or n.tagName not in ignore:\n self.parse(n)\n if len(indent) > 0:\n self.pieces = shift(self.pieces, indent, i_piece)\n self.indent -= len(indent)\n old_pieces.extend(self.pieces)\n self.pieces = old_pieces\n", "def add_text(self, value):\n \"\"\"Adds text corresponding to `value` into `self.pieces`.\"\"\"\n if isinstance(value, (list, tuple)):\n self.pieces.extend(value)\n else:\n self.pieces.append(value)\n" ]
class Doxy2SWIG: """Converts Doxygen generated XML files into a file containing docstrings that can be used by SWIG-1.3.x that have support for feature("docstring"). Once the data is parsed it is stored in self.pieces. """ def __init__(self, src, with_function_signature = False, with_type_info = False, with_constructor_list = False, with_attribute_list = False, with_overloaded_functions = False, textwidth = 80, quiet = False): """Initialize the instance given a source object. `src` can be a file or filename. If you do not want to include function definitions from doxygen then set `include_function_definition` to `False`. This is handy since this allows you to use the swig generated function definition using %feature("autodoc", [0,1]). """ # options: self.with_function_signature = with_function_signature self.with_type_info = with_type_info self.with_constructor_list = with_constructor_list self.with_attribute_list = with_attribute_list self.with_overloaded_functions = with_overloaded_functions self.textwidth = textwidth self.quiet = quiet # state: self.indent = 0 self.listitem = '' self.pieces = [] f = my_open_read(src) self.my_dir = os.path.dirname(f.name) self.xmldoc = minidom.parse(f).documentElement f.close() self.pieces.append('\n// File: %s\n' % os.path.basename(f.name)) self.space_re = re.compile(r'\s+') self.lead_spc = re.compile(r'^(%feature\S+\s+\S+\s*?)"\s+(\S)') self.multi = 0 self.ignores = ['inheritancegraph', 'param', 'listofallmembers', 'innerclass', 'name', 'declname', 'incdepgraph', 'invincdepgraph', 'programlisting', 'type', 'references', 'referencedby', 'location', 'collaborationgraph', 'reimplements', 'reimplementedby', 'derivedcompoundref', 'basecompoundref', 'argsstring', 'definition', 'exceptions'] #self.generics = [] def generate(self): """Parses the file set in the initialization. The resulting data is stored in `self.pieces`. """ self.parse(self.xmldoc) def write(self, fname): o = my_open_write(fname) o.write(''.join(self.pieces)) o.write('\n') o.close() def parse(self, node): """Parse a given node. This function in turn calls the `parse_<nodeType>` functions which handle the respective nodes. """ pm = getattr(self, "parse_%s" % node.__class__.__name__) pm(node) def parse_Document(self, node): self.parse(node.documentElement) def parse_Text(self, node): txt = node.data if txt == ' ': # this can happen when two tags follow in a text, e.g., # " ...</emph> <formaula>$..." etc. # here we want to keep the space. self.add_text(txt) return txt = txt.replace('\\', r'\\') txt = txt.replace('"', r'\"') # ignore pure whitespace m = self.space_re.match(txt) if m and len(m.group()) == len(txt): pass else: self.add_text(txt) def parse_Comment(self, node): """Parse a `COMMENT_NODE`. This does nothing for now.""" return def parse_Element(self, node): """Parse an `ELEMENT_NODE`. This calls specific `do_<tagName>` handers for different elements. If no handler is available the `subnode_parse` method is called. All tagNames specified in `self.ignores` are simply ignored. """ name = node.tagName ignores = self.ignores if name in ignores: return attr = "do_%s" % name if hasattr(self, attr): handlerMethod = getattr(self, attr) handlerMethod(node) else: self.subnode_parse(node) #if name not in self.generics: self.generics.append(name) # MARK: Special format parsing def subnode_parse(self, node, pieces=None, indent=0, ignore=[], restrict=None): """Parse the subnodes of a given node. Subnodes with tags in the `ignore` list are ignored. If pieces is given, use this as target for the parse results instead of self.pieces. Indent all lines by the amount given in `indent`. Note that the initial content in `pieces` is not indented. The final result is in any case added to self.pieces.""" if pieces is not None: old_pieces, self.pieces = self.pieces, pieces else: old_pieces = [] if type(indent) is int: indent = indent * ' ' if len(indent) > 0: pieces = ''.join(self.pieces) i_piece = pieces[:len(indent)] if self.pieces[-1:] == ['']: self.pieces = [pieces[len(indent):]] + [''] elif self.pieces != []: self.pieces = [pieces[len(indent):]] self.indent += len(indent) for n in node.childNodes: if restrict is not None: if n.nodeType == n.ELEMENT_NODE and n.tagName in restrict: self.parse(n) elif n.nodeType != n.ELEMENT_NODE or n.tagName not in ignore: self.parse(n) if len(indent) > 0: self.pieces = shift(self.pieces, indent, i_piece) self.indent -= len(indent) old_pieces.extend(self.pieces) self.pieces = old_pieces # MARK: Helper functions def get_specific_subnodes(self, node, name, recursive=0): """Given a node and a name, return a list of child `ELEMENT_NODEs`, that have a `tagName` matching the `name`. Search recursively for `recursive` levels. """ children = [x for x in node.childNodes if x.nodeType == x.ELEMENT_NODE] ret = [x for x in children if x.tagName == name] if recursive > 0: for x in children: ret.extend(self.get_specific_subnodes(x, name, recursive-1)) return ret def get_specific_nodes(self, node, names): """Given a node and a sequence of strings in `names`, return a dictionary containing the names as keys and child `ELEMENT_NODEs`, that have a `tagName` equal to the name. """ nodes = [(x.tagName, x) for x in node.childNodes if x.nodeType == x.ELEMENT_NODE and x.tagName in names] return dict(nodes) def add_text(self, value): """Adds text corresponding to `value` into `self.pieces`.""" if isinstance(value, (list, tuple)): self.pieces.extend(value) else: self.pieces.append(value) def start_new_paragraph(self): """Make sure to create an empty line. This is overridden, if the previous text ends with the special marker ''. In that case, nothing is done. """ if self.pieces[-1:] == ['']: # respect special marker return elif self.pieces == []: # first paragraph, add '\n', override with '' self.pieces = ['\n'] elif self.pieces[-1][-1:] != '\n': # previous line not ended self.pieces.extend([' \n' ,'\n']) else: #default self.pieces.append('\n') def add_line_with_subsequent_indent(self, line, indent=4): """Add line of text and wrap such that subsequent lines are indented by `indent` spaces. """ if isinstance(line, (list, tuple)): line = ''.join(line) line = line.strip() width = self.textwidth-self.indent-indent wrapped_lines = textwrap.wrap(line[indent:], width=width) for i in range(len(wrapped_lines)): if wrapped_lines[i] != '': wrapped_lines[i] = indent * ' ' + wrapped_lines[i] self.pieces.append(line[:indent] + '\n'.join(wrapped_lines)[indent:] + ' \n') def extract_text(self, node): """Return the string representation of the node or list of nodes by parsing the subnodes, but returning the result as a string instead of adding it to `self.pieces`. Note that this allows extracting text even if the node is in the ignore list. """ if not isinstance(node, (list, tuple)): node = [node] pieces, self.pieces = self.pieces, [''] for n in node: for sn in n.childNodes: self.parse(sn) ret = ''.join(self.pieces) self.pieces = pieces return ret def get_function_signature(self, node): """Returns the function signature string for memberdef nodes.""" name = self.extract_text(self.get_specific_subnodes(node, 'name')) if self.with_type_info: argsstring = self.extract_text(self.get_specific_subnodes(node, 'argsstring')) else: argsstring = [] param_id = 1 for n_param in self.get_specific_subnodes(node, 'param'): declname = self.extract_text(self.get_specific_subnodes(n_param, 'declname')) if not declname: declname = 'arg' + str(param_id) defval = self.extract_text(self.get_specific_subnodes(n_param, 'defval')) if defval: defval = '=' + defval argsstring.append(declname + defval) param_id = param_id + 1 argsstring = '(' + ', '.join(argsstring) + ')' type = self.extract_text(self.get_specific_subnodes(node, 'type')) function_definition = name + argsstring if type != '' and type != 'void': function_definition = function_definition + ' -> ' + type return '`' + function_definition + '` ' # MARK: Special parsing tasks (need to be called manually) def make_constructor_list(self, constructor_nodes, classname): """Produces the "Constructors" section and the constructor signatures (since swig does not do so for classes) for class docstrings.""" if constructor_nodes == []: return self.add_text(['\n', 'Constructors', '\n', '------------']) for n in constructor_nodes: self.add_text('\n') self.add_line_with_subsequent_indent('* ' + self.get_function_signature(n)) self.subnode_parse(n, pieces = [], indent=4, ignore=['definition', 'name']) def make_attribute_list(self, node): """Produces the "Attributes" section in class docstrings for public member variables (attributes). """ atr_nodes = [] for n in self.get_specific_subnodes(node, 'memberdef', recursive=2): if n.attributes['kind'].value == 'variable' and n.attributes['prot'].value == 'public': atr_nodes.append(n) if not atr_nodes: return self.add_text(['\n', 'Attributes', '\n', '----------']) for n in atr_nodes: name = self.extract_text(self.get_specific_subnodes(n, 'name')) self.add_text(['\n* ', '`', name, '`', ' : ']) self.add_text(['`', self.extract_text(self.get_specific_subnodes(n, 'type')), '`']) self.add_text(' \n') restrict = ['briefdescription', 'detaileddescription'] self.subnode_parse(n, pieces=[''], indent=4, restrict=restrict) def get_memberdef_nodes_and_signatures(self, node, kind): """Collects the memberdef nodes and corresponding signatures that correspond to public function entries that are at most depth 2 deeper than the current (compounddef) node. Returns a dictionary with function signatures (what swig expects after the %feature directive) as keys, and a list of corresponding memberdef nodes as values.""" sig_dict = {} sig_prefix = '' if kind in ('file', 'namespace'): ns_node = node.getElementsByTagName('innernamespace') if not ns_node and kind == 'namespace': ns_node = node.getElementsByTagName('compoundname') if ns_node: sig_prefix = self.extract_text(ns_node[0]) + '::' elif kind in ('class', 'struct'): # Get the full function name. cn_node = node.getElementsByTagName('compoundname') sig_prefix = self.extract_text(cn_node[0]) + '::' md_nodes = self.get_specific_subnodes(node, 'memberdef', recursive=2) for n in md_nodes: if n.attributes['prot'].value != 'public': continue if n.attributes['kind'].value in ['variable', 'typedef']: continue if not self.get_specific_subnodes(n, 'definition'): continue name = self.extract_text(self.get_specific_subnodes(n, 'name')) if name[:8] == 'operator': continue sig = sig_prefix + name if sig in sig_dict: sig_dict[sig].append(n) else: sig_dict[sig] = [n] return sig_dict def handle_typical_memberdefs_no_overload(self, signature, memberdef_nodes): """Produce standard documentation for memberdef_nodes.""" for n in memberdef_nodes: self.add_text(['\n', '%feature("docstring") ', signature, ' "', '\n']) if self.with_function_signature: self.add_line_with_subsequent_indent(self.get_function_signature(n)) self.subnode_parse(n, pieces=[], ignore=['definition', 'name']) self.add_text(['";', '\n']) def handle_typical_memberdefs(self, signature, memberdef_nodes): """Produces docstring entries containing an "Overloaded function" section with the documentation for each overload, if the function is overloaded and self.with_overloaded_functions is set. Else, produce normal documentation. """ if len(memberdef_nodes) == 1 or not self.with_overloaded_functions: self.handle_typical_memberdefs_no_overload(signature, memberdef_nodes) return self.add_text(['\n', '%feature("docstring") ', signature, ' "', '\n']) if self.with_function_signature: for n in memberdef_nodes: self.add_line_with_subsequent_indent(self.get_function_signature(n)) self.add_text('\n') self.add_text(['Overloaded function', '\n', '-------------------']) for n in memberdef_nodes: self.add_text('\n') self.add_line_with_subsequent_indent('* ' + self.get_function_signature(n)) self.subnode_parse(n, pieces=[], indent=4, ignore=['definition', 'name']) self.add_text(['";', '\n']) # MARK: Tag handlers def do_linebreak(self, node): self.add_text(' ') def do_ndash(self, node): self.add_text('--') def do_mdash(self, node): self.add_text('---') def do_emphasis(self, node): self.surround_parse(node, '*', '*') def do_bold(self, node): self.surround_parse(node, '**', '**') def do_computeroutput(self, node): self.surround_parse(node, '`', '`') def do_heading(self, node): self.start_new_paragraph() pieces, self.pieces = self.pieces, [''] level = int(node.attributes['level'].value) self.subnode_parse(node) if level == 1: self.pieces.insert(0, '\n') self.add_text(['\n', len(''.join(self.pieces).strip()) * '=']) elif level == 2: self.add_text(['\n', len(''.join(self.pieces).strip()) * '-']) elif level >= 3: self.pieces.insert(0, level * '#' + ' ') # make following text have no gap to the heading: pieces.extend([''.join(self.pieces) + ' \n', '']) self.pieces = pieces def do_verbatim(self, node): self.start_new_paragraph() self.subnode_parse(node, pieces=[''], indent=4) def do_blockquote(self, node): self.start_new_paragraph() self.subnode_parse(node, pieces=[''], indent='> ') def do_hruler(self, node): self.start_new_paragraph() self.add_text('* * * * * \n') def do_includes(self, node): self.add_text('\nC++ includes: ') self.subnode_parse(node) self.add_text('\n') # MARK: Para tag handler def do_para(self, node): """This is the only place where text wrapping is automatically performed. Generally, this function parses the node (locally), wraps the text, and then adds the result to self.pieces. However, it may be convenient to allow the previous content of self.pieces to be included in the text wrapping. For this, use the following *convention*: If self.pieces ends with '', treat the _previous_ entry as part of the current paragraph. Else, insert new-line and start a new paragraph and "wrapping context". Paragraphs always end with ' \n', but if the parsed content ends with the special symbol '', this is passed on. """ if self.pieces[-1:] == ['']: pieces, self.pieces = self.pieces[:-2], self.pieces[-2:-1] else: self.add_text('\n') pieces, self.pieces = self.pieces, [''] self.subnode_parse(node) dont_end_paragraph = self.pieces[-1:] == [''] # Now do the text wrapping: width = self.textwidth - self.indent wrapped_para = [] for line in ''.join(self.pieces).splitlines(): keep_markdown_newline = line[-2:] == ' ' w_line = textwrap.wrap(line, width=width, break_long_words=False) if w_line == []: w_line = [''] if keep_markdown_newline: w_line[-1] = w_line[-1] + ' ' for wl in w_line: wrapped_para.append(wl + '\n') if wrapped_para: if wrapped_para[-1][-3:] != ' \n': wrapped_para[-1] = wrapped_para[-1][:-1] + ' \n' if dont_end_paragraph: wrapped_para.append('') pieces.extend(wrapped_para) self.pieces = pieces # MARK: List tag handlers def do_itemizedlist(self, node): if self.listitem == '': self.start_new_paragraph() elif self.pieces != [] and self.pieces[-1:] != ['']: self.add_text('\n') listitem = self.listitem if self.listitem in ['*', '-']: self.listitem = '-' else: self.listitem = '*' self.subnode_parse(node) self.listitem = listitem def do_orderedlist(self, node): if self.listitem == '': self.start_new_paragraph() elif self.pieces != [] and self.pieces[-1:] != ['']: self.add_text('\n') listitem = self.listitem self.listitem = 0 self.subnode_parse(node) self.listitem = listitem def do_listitem(self, node): try: self.listitem = int(self.listitem) + 1 item = str(self.listitem) + '. ' except: item = str(self.listitem) + ' ' self.subnode_parse(node, item, indent=4) # MARK: Parameter list tag handlers def do_parameterlist(self, node): self.start_new_paragraph() text = 'unknown' for key, val in node.attributes.items(): if key == 'kind': if val == 'param': text = 'Parameters' elif val == 'exception': text = 'Exceptions' elif val == 'retval': text = 'Returns' else: text = val break if self.indent == 0: self.add_text([text, '\n', len(text) * '-', '\n']) else: self.add_text([text, ': \n']) self.subnode_parse(node) def do_parameteritem(self, node): self.subnode_parse(node, pieces=['* ', '']) def do_parameternamelist(self, node): self.subnode_parse(node) self.add_text([' :', ' \n']) def do_parametername(self, node): if self.pieces != [] and self.pieces != ['* ', '']: self.add_text(', ') data = self.extract_text(node) self.add_text(['`', data, '`']) def do_parameterdescription(self, node): self.subnode_parse(node, pieces=[''], indent=4) # MARK: Section tag handler def do_simplesect(self, node): kind = node.attributes['kind'].value if kind in ('date', 'rcs', 'version'): return self.start_new_paragraph() if kind == 'warning': self.subnode_parse(node, pieces=['**Warning**: ',''], indent=4) elif kind == 'see': self.subnode_parse(node, pieces=['See also: ',''], indent=4) elif kind == 'return': if self.indent == 0: pieces = ['Returns', '\n', len('Returns') * '-', '\n', ''] else: pieces = ['Returns:', '\n', ''] self.subnode_parse(node, pieces=pieces) else: self.subnode_parse(node, pieces=[kind + ': ',''], indent=4) # MARK: %feature("docstring") producing tag handlers def do_compounddef(self, node): """This produces %feature("docstring") entries for classes, and handles class, namespace and file memberdef entries specially to allow for overloaded functions. For other cases, passes parsing on to standard handlers (which may produce unexpected results). """ kind = node.attributes['kind'].value if kind in ('class', 'struct'): prot = node.attributes['prot'].value if prot != 'public': return self.add_text('\n\n') classdefn = self.extract_text(self.get_specific_subnodes(node, 'compoundname')) classname = classdefn.split('::')[-1] self.add_text('%%feature("docstring") %s "\n' % classdefn) if self.with_constructor_list: constructor_nodes = [] for n in self.get_specific_subnodes(node, 'memberdef', recursive=2): if n.attributes['prot'].value == 'public': if self.extract_text(self.get_specific_subnodes(n, 'definition')) == classdefn + '::' + classname: constructor_nodes.append(n) for n in constructor_nodes: self.add_line_with_subsequent_indent(self.get_function_signature(n)) names = ('briefdescription','detaileddescription') sub_dict = self.get_specific_nodes(node, names) for n in ('briefdescription','detaileddescription'): if n in sub_dict: self.parse(sub_dict[n]) if self.with_constructor_list: self.make_constructor_list(constructor_nodes, classname) if self.with_attribute_list: self.make_attribute_list(node) sub_list = self.get_specific_subnodes(node, 'includes') if sub_list: self.parse(sub_list[0]) self.add_text(['";', '\n']) names = ['compoundname', 'briefdescription','detaileddescription', 'includes'] self.subnode_parse(node, ignore = names) elif kind in ('file', 'namespace'): nodes = node.getElementsByTagName('sectiondef') for n in nodes: self.parse(n) # now explicitely handle possibly overloaded member functions. if kind in ['class', 'struct','file', 'namespace']: md_nodes = self.get_memberdef_nodes_and_signatures(node, kind) for sig in md_nodes: self.handle_typical_memberdefs(sig, md_nodes[sig]) def do_memberdef(self, node): """Handle cases outside of class, struct, file or namespace. These are now dealt with by `handle_overloaded_memberfunction`. Do these even exist??? """ prot = node.attributes['prot'].value id = node.attributes['id'].value kind = node.attributes['kind'].value tmp = node.parentNode.parentNode.parentNode compdef = tmp.getElementsByTagName('compounddef')[0] cdef_kind = compdef.attributes['kind'].value if cdef_kind in ('file', 'namespace', 'class', 'struct'): # These cases are now handled by `handle_typical_memberdefs` return if prot != 'public': return first = self.get_specific_nodes(node, ('definition', 'name')) name = self.extract_text(first['name']) if name[:8] == 'operator': # Don't handle operators yet. return if not 'definition' in first or kind in ['variable', 'typedef']: return data = self.extract_text(first['definition']) self.add_text('\n') self.add_text(['/* where did this entry come from??? */', '\n']) self.add_text('%feature("docstring") %s "\n%s' % (data, data)) for n in node.childNodes: if n not in first.values(): self.parse(n) self.add_text(['";', '\n']) # MARK: Entry tag handlers (dont print anything meaningful) def do_sectiondef(self, node): kind = node.attributes['kind'].value if kind in ('public-func', 'func', 'user-defined', ''): self.subnode_parse(node) def do_header(self, node): """For a user defined section def a header field is present which should not be printed as such, so we comment it in the output.""" data = self.extract_text(node) self.add_text('\n/*\n %s \n*/\n' % data) # If our immediate sibling is a 'description' node then we # should comment that out also and remove it from the parent # node's children. parent = node.parentNode idx = parent.childNodes.index(node) if len(parent.childNodes) >= idx + 2: nd = parent.childNodes[idx + 2] if nd.nodeName == 'description': nd = parent.removeChild(nd) self.add_text('\n/*') self.subnode_parse(nd) self.add_text('\n*/\n') def do_member(self, node): kind = node.attributes['kind'].value refid = node.attributes['refid'].value if kind == 'function' and refid[:9] == 'namespace': self.subnode_parse(node) def do_doxygenindex(self, node): self.multi = 1 comps = node.getElementsByTagName('compound') for c in comps: refid = c.attributes['refid'].value fname = refid + '.xml' if not os.path.exists(fname): fname = os.path.join(self.my_dir, fname) if not self.quiet: print("parsing file: %s" % fname) p = Doxy2SWIG(fname, with_function_signature = self.with_function_signature, with_type_info = self.with_type_info, with_constructor_list = self.with_constructor_list, with_attribute_list = self.with_attribute_list, with_overloaded_functions = self.with_overloaded_functions, textwidth = self.textwidth, quiet = self.quiet) p.generate() self.pieces.extend(p.pieces)
basler/pypylon
scripts/builddoxy2swig/doxy2swig/doxy2swig.py
Doxy2SWIG.get_specific_subnodes
python
def get_specific_subnodes(self, node, name, recursive=0): children = [x for x in node.childNodes if x.nodeType == x.ELEMENT_NODE] ret = [x for x in children if x.tagName == name] if recursive > 0: for x in children: ret.extend(self.get_specific_subnodes(x, name, recursive-1)) return ret
Given a node and a name, return a list of child `ELEMENT_NODEs`, that have a `tagName` matching the `name`. Search recursively for `recursive` levels.
train
https://github.com/basler/pypylon/blob/d3510fa419b1c2b17f3f0b80a5fbb720c7b84008/scripts/builddoxy2swig/doxy2swig/doxy2swig.py#L265-L275
[ "def get_specific_subnodes(self, node, name, recursive=0):\n \"\"\"Given a node and a name, return a list of child `ELEMENT_NODEs`, that\n have a `tagName` matching the `name`. Search recursively for `recursive`\n levels.\n \"\"\"\n children = [x for x in node.childNodes if x.nodeType == x.ELEMENT_NODE]\n ret = [x for x in children if x.tagName == name]\n if recursive > 0:\n for x in children:\n ret.extend(self.get_specific_subnodes(x, name, recursive-1))\n return ret\n" ]
class Doxy2SWIG: """Converts Doxygen generated XML files into a file containing docstrings that can be used by SWIG-1.3.x that have support for feature("docstring"). Once the data is parsed it is stored in self.pieces. """ def __init__(self, src, with_function_signature = False, with_type_info = False, with_constructor_list = False, with_attribute_list = False, with_overloaded_functions = False, textwidth = 80, quiet = False): """Initialize the instance given a source object. `src` can be a file or filename. If you do not want to include function definitions from doxygen then set `include_function_definition` to `False`. This is handy since this allows you to use the swig generated function definition using %feature("autodoc", [0,1]). """ # options: self.with_function_signature = with_function_signature self.with_type_info = with_type_info self.with_constructor_list = with_constructor_list self.with_attribute_list = with_attribute_list self.with_overloaded_functions = with_overloaded_functions self.textwidth = textwidth self.quiet = quiet # state: self.indent = 0 self.listitem = '' self.pieces = [] f = my_open_read(src) self.my_dir = os.path.dirname(f.name) self.xmldoc = minidom.parse(f).documentElement f.close() self.pieces.append('\n// File: %s\n' % os.path.basename(f.name)) self.space_re = re.compile(r'\s+') self.lead_spc = re.compile(r'^(%feature\S+\s+\S+\s*?)"\s+(\S)') self.multi = 0 self.ignores = ['inheritancegraph', 'param', 'listofallmembers', 'innerclass', 'name', 'declname', 'incdepgraph', 'invincdepgraph', 'programlisting', 'type', 'references', 'referencedby', 'location', 'collaborationgraph', 'reimplements', 'reimplementedby', 'derivedcompoundref', 'basecompoundref', 'argsstring', 'definition', 'exceptions'] #self.generics = [] def generate(self): """Parses the file set in the initialization. The resulting data is stored in `self.pieces`. """ self.parse(self.xmldoc) def write(self, fname): o = my_open_write(fname) o.write(''.join(self.pieces)) o.write('\n') o.close() def parse(self, node): """Parse a given node. This function in turn calls the `parse_<nodeType>` functions which handle the respective nodes. """ pm = getattr(self, "parse_%s" % node.__class__.__name__) pm(node) def parse_Document(self, node): self.parse(node.documentElement) def parse_Text(self, node): txt = node.data if txt == ' ': # this can happen when two tags follow in a text, e.g., # " ...</emph> <formaula>$..." etc. # here we want to keep the space. self.add_text(txt) return txt = txt.replace('\\', r'\\') txt = txt.replace('"', r'\"') # ignore pure whitespace m = self.space_re.match(txt) if m and len(m.group()) == len(txt): pass else: self.add_text(txt) def parse_Comment(self, node): """Parse a `COMMENT_NODE`. This does nothing for now.""" return def parse_Element(self, node): """Parse an `ELEMENT_NODE`. This calls specific `do_<tagName>` handers for different elements. If no handler is available the `subnode_parse` method is called. All tagNames specified in `self.ignores` are simply ignored. """ name = node.tagName ignores = self.ignores if name in ignores: return attr = "do_%s" % name if hasattr(self, attr): handlerMethod = getattr(self, attr) handlerMethod(node) else: self.subnode_parse(node) #if name not in self.generics: self.generics.append(name) # MARK: Special format parsing def subnode_parse(self, node, pieces=None, indent=0, ignore=[], restrict=None): """Parse the subnodes of a given node. Subnodes with tags in the `ignore` list are ignored. If pieces is given, use this as target for the parse results instead of self.pieces. Indent all lines by the amount given in `indent`. Note that the initial content in `pieces` is not indented. The final result is in any case added to self.pieces.""" if pieces is not None: old_pieces, self.pieces = self.pieces, pieces else: old_pieces = [] if type(indent) is int: indent = indent * ' ' if len(indent) > 0: pieces = ''.join(self.pieces) i_piece = pieces[:len(indent)] if self.pieces[-1:] == ['']: self.pieces = [pieces[len(indent):]] + [''] elif self.pieces != []: self.pieces = [pieces[len(indent):]] self.indent += len(indent) for n in node.childNodes: if restrict is not None: if n.nodeType == n.ELEMENT_NODE and n.tagName in restrict: self.parse(n) elif n.nodeType != n.ELEMENT_NODE or n.tagName not in ignore: self.parse(n) if len(indent) > 0: self.pieces = shift(self.pieces, indent, i_piece) self.indent -= len(indent) old_pieces.extend(self.pieces) self.pieces = old_pieces def surround_parse(self, node, pre_char, post_char): """Parse the subnodes of a given node. Subnodes with tags in the `ignore` list are ignored. Prepend `pre_char` and append `post_char` to the output in self.pieces.""" self.add_text(pre_char) self.subnode_parse(node) self.add_text(post_char) # MARK: Helper functions def get_specific_nodes(self, node, names): """Given a node and a sequence of strings in `names`, return a dictionary containing the names as keys and child `ELEMENT_NODEs`, that have a `tagName` equal to the name. """ nodes = [(x.tagName, x) for x in node.childNodes if x.nodeType == x.ELEMENT_NODE and x.tagName in names] return dict(nodes) def add_text(self, value): """Adds text corresponding to `value` into `self.pieces`.""" if isinstance(value, (list, tuple)): self.pieces.extend(value) else: self.pieces.append(value) def start_new_paragraph(self): """Make sure to create an empty line. This is overridden, if the previous text ends with the special marker ''. In that case, nothing is done. """ if self.pieces[-1:] == ['']: # respect special marker return elif self.pieces == []: # first paragraph, add '\n', override with '' self.pieces = ['\n'] elif self.pieces[-1][-1:] != '\n': # previous line not ended self.pieces.extend([' \n' ,'\n']) else: #default self.pieces.append('\n') def add_line_with_subsequent_indent(self, line, indent=4): """Add line of text and wrap such that subsequent lines are indented by `indent` spaces. """ if isinstance(line, (list, tuple)): line = ''.join(line) line = line.strip() width = self.textwidth-self.indent-indent wrapped_lines = textwrap.wrap(line[indent:], width=width) for i in range(len(wrapped_lines)): if wrapped_lines[i] != '': wrapped_lines[i] = indent * ' ' + wrapped_lines[i] self.pieces.append(line[:indent] + '\n'.join(wrapped_lines)[indent:] + ' \n') def extract_text(self, node): """Return the string representation of the node or list of nodes by parsing the subnodes, but returning the result as a string instead of adding it to `self.pieces`. Note that this allows extracting text even if the node is in the ignore list. """ if not isinstance(node, (list, tuple)): node = [node] pieces, self.pieces = self.pieces, [''] for n in node: for sn in n.childNodes: self.parse(sn) ret = ''.join(self.pieces) self.pieces = pieces return ret def get_function_signature(self, node): """Returns the function signature string for memberdef nodes.""" name = self.extract_text(self.get_specific_subnodes(node, 'name')) if self.with_type_info: argsstring = self.extract_text(self.get_specific_subnodes(node, 'argsstring')) else: argsstring = [] param_id = 1 for n_param in self.get_specific_subnodes(node, 'param'): declname = self.extract_text(self.get_specific_subnodes(n_param, 'declname')) if not declname: declname = 'arg' + str(param_id) defval = self.extract_text(self.get_specific_subnodes(n_param, 'defval')) if defval: defval = '=' + defval argsstring.append(declname + defval) param_id = param_id + 1 argsstring = '(' + ', '.join(argsstring) + ')' type = self.extract_text(self.get_specific_subnodes(node, 'type')) function_definition = name + argsstring if type != '' and type != 'void': function_definition = function_definition + ' -> ' + type return '`' + function_definition + '` ' # MARK: Special parsing tasks (need to be called manually) def make_constructor_list(self, constructor_nodes, classname): """Produces the "Constructors" section and the constructor signatures (since swig does not do so for classes) for class docstrings.""" if constructor_nodes == []: return self.add_text(['\n', 'Constructors', '\n', '------------']) for n in constructor_nodes: self.add_text('\n') self.add_line_with_subsequent_indent('* ' + self.get_function_signature(n)) self.subnode_parse(n, pieces = [], indent=4, ignore=['definition', 'name']) def make_attribute_list(self, node): """Produces the "Attributes" section in class docstrings for public member variables (attributes). """ atr_nodes = [] for n in self.get_specific_subnodes(node, 'memberdef', recursive=2): if n.attributes['kind'].value == 'variable' and n.attributes['prot'].value == 'public': atr_nodes.append(n) if not atr_nodes: return self.add_text(['\n', 'Attributes', '\n', '----------']) for n in atr_nodes: name = self.extract_text(self.get_specific_subnodes(n, 'name')) self.add_text(['\n* ', '`', name, '`', ' : ']) self.add_text(['`', self.extract_text(self.get_specific_subnodes(n, 'type')), '`']) self.add_text(' \n') restrict = ['briefdescription', 'detaileddescription'] self.subnode_parse(n, pieces=[''], indent=4, restrict=restrict) def get_memberdef_nodes_and_signatures(self, node, kind): """Collects the memberdef nodes and corresponding signatures that correspond to public function entries that are at most depth 2 deeper than the current (compounddef) node. Returns a dictionary with function signatures (what swig expects after the %feature directive) as keys, and a list of corresponding memberdef nodes as values.""" sig_dict = {} sig_prefix = '' if kind in ('file', 'namespace'): ns_node = node.getElementsByTagName('innernamespace') if not ns_node and kind == 'namespace': ns_node = node.getElementsByTagName('compoundname') if ns_node: sig_prefix = self.extract_text(ns_node[0]) + '::' elif kind in ('class', 'struct'): # Get the full function name. cn_node = node.getElementsByTagName('compoundname') sig_prefix = self.extract_text(cn_node[0]) + '::' md_nodes = self.get_specific_subnodes(node, 'memberdef', recursive=2) for n in md_nodes: if n.attributes['prot'].value != 'public': continue if n.attributes['kind'].value in ['variable', 'typedef']: continue if not self.get_specific_subnodes(n, 'definition'): continue name = self.extract_text(self.get_specific_subnodes(n, 'name')) if name[:8] == 'operator': continue sig = sig_prefix + name if sig in sig_dict: sig_dict[sig].append(n) else: sig_dict[sig] = [n] return sig_dict def handle_typical_memberdefs_no_overload(self, signature, memberdef_nodes): """Produce standard documentation for memberdef_nodes.""" for n in memberdef_nodes: self.add_text(['\n', '%feature("docstring") ', signature, ' "', '\n']) if self.with_function_signature: self.add_line_with_subsequent_indent(self.get_function_signature(n)) self.subnode_parse(n, pieces=[], ignore=['definition', 'name']) self.add_text(['";', '\n']) def handle_typical_memberdefs(self, signature, memberdef_nodes): """Produces docstring entries containing an "Overloaded function" section with the documentation for each overload, if the function is overloaded and self.with_overloaded_functions is set. Else, produce normal documentation. """ if len(memberdef_nodes) == 1 or not self.with_overloaded_functions: self.handle_typical_memberdefs_no_overload(signature, memberdef_nodes) return self.add_text(['\n', '%feature("docstring") ', signature, ' "', '\n']) if self.with_function_signature: for n in memberdef_nodes: self.add_line_with_subsequent_indent(self.get_function_signature(n)) self.add_text('\n') self.add_text(['Overloaded function', '\n', '-------------------']) for n in memberdef_nodes: self.add_text('\n') self.add_line_with_subsequent_indent('* ' + self.get_function_signature(n)) self.subnode_parse(n, pieces=[], indent=4, ignore=['definition', 'name']) self.add_text(['";', '\n']) # MARK: Tag handlers def do_linebreak(self, node): self.add_text(' ') def do_ndash(self, node): self.add_text('--') def do_mdash(self, node): self.add_text('---') def do_emphasis(self, node): self.surround_parse(node, '*', '*') def do_bold(self, node): self.surround_parse(node, '**', '**') def do_computeroutput(self, node): self.surround_parse(node, '`', '`') def do_heading(self, node): self.start_new_paragraph() pieces, self.pieces = self.pieces, [''] level = int(node.attributes['level'].value) self.subnode_parse(node) if level == 1: self.pieces.insert(0, '\n') self.add_text(['\n', len(''.join(self.pieces).strip()) * '=']) elif level == 2: self.add_text(['\n', len(''.join(self.pieces).strip()) * '-']) elif level >= 3: self.pieces.insert(0, level * '#' + ' ') # make following text have no gap to the heading: pieces.extend([''.join(self.pieces) + ' \n', '']) self.pieces = pieces def do_verbatim(self, node): self.start_new_paragraph() self.subnode_parse(node, pieces=[''], indent=4) def do_blockquote(self, node): self.start_new_paragraph() self.subnode_parse(node, pieces=[''], indent='> ') def do_hruler(self, node): self.start_new_paragraph() self.add_text('* * * * * \n') def do_includes(self, node): self.add_text('\nC++ includes: ') self.subnode_parse(node) self.add_text('\n') # MARK: Para tag handler def do_para(self, node): """This is the only place where text wrapping is automatically performed. Generally, this function parses the node (locally), wraps the text, and then adds the result to self.pieces. However, it may be convenient to allow the previous content of self.pieces to be included in the text wrapping. For this, use the following *convention*: If self.pieces ends with '', treat the _previous_ entry as part of the current paragraph. Else, insert new-line and start a new paragraph and "wrapping context". Paragraphs always end with ' \n', but if the parsed content ends with the special symbol '', this is passed on. """ if self.pieces[-1:] == ['']: pieces, self.pieces = self.pieces[:-2], self.pieces[-2:-1] else: self.add_text('\n') pieces, self.pieces = self.pieces, [''] self.subnode_parse(node) dont_end_paragraph = self.pieces[-1:] == [''] # Now do the text wrapping: width = self.textwidth - self.indent wrapped_para = [] for line in ''.join(self.pieces).splitlines(): keep_markdown_newline = line[-2:] == ' ' w_line = textwrap.wrap(line, width=width, break_long_words=False) if w_line == []: w_line = [''] if keep_markdown_newline: w_line[-1] = w_line[-1] + ' ' for wl in w_line: wrapped_para.append(wl + '\n') if wrapped_para: if wrapped_para[-1][-3:] != ' \n': wrapped_para[-1] = wrapped_para[-1][:-1] + ' \n' if dont_end_paragraph: wrapped_para.append('') pieces.extend(wrapped_para) self.pieces = pieces # MARK: List tag handlers def do_itemizedlist(self, node): if self.listitem == '': self.start_new_paragraph() elif self.pieces != [] and self.pieces[-1:] != ['']: self.add_text('\n') listitem = self.listitem if self.listitem in ['*', '-']: self.listitem = '-' else: self.listitem = '*' self.subnode_parse(node) self.listitem = listitem def do_orderedlist(self, node): if self.listitem == '': self.start_new_paragraph() elif self.pieces != [] and self.pieces[-1:] != ['']: self.add_text('\n') listitem = self.listitem self.listitem = 0 self.subnode_parse(node) self.listitem = listitem def do_listitem(self, node): try: self.listitem = int(self.listitem) + 1 item = str(self.listitem) + '. ' except: item = str(self.listitem) + ' ' self.subnode_parse(node, item, indent=4) # MARK: Parameter list tag handlers def do_parameterlist(self, node): self.start_new_paragraph() text = 'unknown' for key, val in node.attributes.items(): if key == 'kind': if val == 'param': text = 'Parameters' elif val == 'exception': text = 'Exceptions' elif val == 'retval': text = 'Returns' else: text = val break if self.indent == 0: self.add_text([text, '\n', len(text) * '-', '\n']) else: self.add_text([text, ': \n']) self.subnode_parse(node) def do_parameteritem(self, node): self.subnode_parse(node, pieces=['* ', '']) def do_parameternamelist(self, node): self.subnode_parse(node) self.add_text([' :', ' \n']) def do_parametername(self, node): if self.pieces != [] and self.pieces != ['* ', '']: self.add_text(', ') data = self.extract_text(node) self.add_text(['`', data, '`']) def do_parameterdescription(self, node): self.subnode_parse(node, pieces=[''], indent=4) # MARK: Section tag handler def do_simplesect(self, node): kind = node.attributes['kind'].value if kind in ('date', 'rcs', 'version'): return self.start_new_paragraph() if kind == 'warning': self.subnode_parse(node, pieces=['**Warning**: ',''], indent=4) elif kind == 'see': self.subnode_parse(node, pieces=['See also: ',''], indent=4) elif kind == 'return': if self.indent == 0: pieces = ['Returns', '\n', len('Returns') * '-', '\n', ''] else: pieces = ['Returns:', '\n', ''] self.subnode_parse(node, pieces=pieces) else: self.subnode_parse(node, pieces=[kind + ': ',''], indent=4) # MARK: %feature("docstring") producing tag handlers def do_compounddef(self, node): """This produces %feature("docstring") entries for classes, and handles class, namespace and file memberdef entries specially to allow for overloaded functions. For other cases, passes parsing on to standard handlers (which may produce unexpected results). """ kind = node.attributes['kind'].value if kind in ('class', 'struct'): prot = node.attributes['prot'].value if prot != 'public': return self.add_text('\n\n') classdefn = self.extract_text(self.get_specific_subnodes(node, 'compoundname')) classname = classdefn.split('::')[-1] self.add_text('%%feature("docstring") %s "\n' % classdefn) if self.with_constructor_list: constructor_nodes = [] for n in self.get_specific_subnodes(node, 'memberdef', recursive=2): if n.attributes['prot'].value == 'public': if self.extract_text(self.get_specific_subnodes(n, 'definition')) == classdefn + '::' + classname: constructor_nodes.append(n) for n in constructor_nodes: self.add_line_with_subsequent_indent(self.get_function_signature(n)) names = ('briefdescription','detaileddescription') sub_dict = self.get_specific_nodes(node, names) for n in ('briefdescription','detaileddescription'): if n in sub_dict: self.parse(sub_dict[n]) if self.with_constructor_list: self.make_constructor_list(constructor_nodes, classname) if self.with_attribute_list: self.make_attribute_list(node) sub_list = self.get_specific_subnodes(node, 'includes') if sub_list: self.parse(sub_list[0]) self.add_text(['";', '\n']) names = ['compoundname', 'briefdescription','detaileddescription', 'includes'] self.subnode_parse(node, ignore = names) elif kind in ('file', 'namespace'): nodes = node.getElementsByTagName('sectiondef') for n in nodes: self.parse(n) # now explicitely handle possibly overloaded member functions. if kind in ['class', 'struct','file', 'namespace']: md_nodes = self.get_memberdef_nodes_and_signatures(node, kind) for sig in md_nodes: self.handle_typical_memberdefs(sig, md_nodes[sig]) def do_memberdef(self, node): """Handle cases outside of class, struct, file or namespace. These are now dealt with by `handle_overloaded_memberfunction`. Do these even exist??? """ prot = node.attributes['prot'].value id = node.attributes['id'].value kind = node.attributes['kind'].value tmp = node.parentNode.parentNode.parentNode compdef = tmp.getElementsByTagName('compounddef')[0] cdef_kind = compdef.attributes['kind'].value if cdef_kind in ('file', 'namespace', 'class', 'struct'): # These cases are now handled by `handle_typical_memberdefs` return if prot != 'public': return first = self.get_specific_nodes(node, ('definition', 'name')) name = self.extract_text(first['name']) if name[:8] == 'operator': # Don't handle operators yet. return if not 'definition' in first or kind in ['variable', 'typedef']: return data = self.extract_text(first['definition']) self.add_text('\n') self.add_text(['/* where did this entry come from??? */', '\n']) self.add_text('%feature("docstring") %s "\n%s' % (data, data)) for n in node.childNodes: if n not in first.values(): self.parse(n) self.add_text(['";', '\n']) # MARK: Entry tag handlers (dont print anything meaningful) def do_sectiondef(self, node): kind = node.attributes['kind'].value if kind in ('public-func', 'func', 'user-defined', ''): self.subnode_parse(node) def do_header(self, node): """For a user defined section def a header field is present which should not be printed as such, so we comment it in the output.""" data = self.extract_text(node) self.add_text('\n/*\n %s \n*/\n' % data) # If our immediate sibling is a 'description' node then we # should comment that out also and remove it from the parent # node's children. parent = node.parentNode idx = parent.childNodes.index(node) if len(parent.childNodes) >= idx + 2: nd = parent.childNodes[idx + 2] if nd.nodeName == 'description': nd = parent.removeChild(nd) self.add_text('\n/*') self.subnode_parse(nd) self.add_text('\n*/\n') def do_member(self, node): kind = node.attributes['kind'].value refid = node.attributes['refid'].value if kind == 'function' and refid[:9] == 'namespace': self.subnode_parse(node) def do_doxygenindex(self, node): self.multi = 1 comps = node.getElementsByTagName('compound') for c in comps: refid = c.attributes['refid'].value fname = refid + '.xml' if not os.path.exists(fname): fname = os.path.join(self.my_dir, fname) if not self.quiet: print("parsing file: %s" % fname) p = Doxy2SWIG(fname, with_function_signature = self.with_function_signature, with_type_info = self.with_type_info, with_constructor_list = self.with_constructor_list, with_attribute_list = self.with_attribute_list, with_overloaded_functions = self.with_overloaded_functions, textwidth = self.textwidth, quiet = self.quiet) p.generate() self.pieces.extend(p.pieces)
basler/pypylon
scripts/builddoxy2swig/doxy2swig/doxy2swig.py
Doxy2SWIG.get_specific_nodes
python
def get_specific_nodes(self, node, names): nodes = [(x.tagName, x) for x in node.childNodes if x.nodeType == x.ELEMENT_NODE and x.tagName in names] return dict(nodes)
Given a node and a sequence of strings in `names`, return a dictionary containing the names as keys and child `ELEMENT_NODEs`, that have a `tagName` equal to the name.
train
https://github.com/basler/pypylon/blob/d3510fa419b1c2b17f3f0b80a5fbb720c7b84008/scripts/builddoxy2swig/doxy2swig/doxy2swig.py#L277-L286
null
class Doxy2SWIG: """Converts Doxygen generated XML files into a file containing docstrings that can be used by SWIG-1.3.x that have support for feature("docstring"). Once the data is parsed it is stored in self.pieces. """ def __init__(self, src, with_function_signature = False, with_type_info = False, with_constructor_list = False, with_attribute_list = False, with_overloaded_functions = False, textwidth = 80, quiet = False): """Initialize the instance given a source object. `src` can be a file or filename. If you do not want to include function definitions from doxygen then set `include_function_definition` to `False`. This is handy since this allows you to use the swig generated function definition using %feature("autodoc", [0,1]). """ # options: self.with_function_signature = with_function_signature self.with_type_info = with_type_info self.with_constructor_list = with_constructor_list self.with_attribute_list = with_attribute_list self.with_overloaded_functions = with_overloaded_functions self.textwidth = textwidth self.quiet = quiet # state: self.indent = 0 self.listitem = '' self.pieces = [] f = my_open_read(src) self.my_dir = os.path.dirname(f.name) self.xmldoc = minidom.parse(f).documentElement f.close() self.pieces.append('\n// File: %s\n' % os.path.basename(f.name)) self.space_re = re.compile(r'\s+') self.lead_spc = re.compile(r'^(%feature\S+\s+\S+\s*?)"\s+(\S)') self.multi = 0 self.ignores = ['inheritancegraph', 'param', 'listofallmembers', 'innerclass', 'name', 'declname', 'incdepgraph', 'invincdepgraph', 'programlisting', 'type', 'references', 'referencedby', 'location', 'collaborationgraph', 'reimplements', 'reimplementedby', 'derivedcompoundref', 'basecompoundref', 'argsstring', 'definition', 'exceptions'] #self.generics = [] def generate(self): """Parses the file set in the initialization. The resulting data is stored in `self.pieces`. """ self.parse(self.xmldoc) def write(self, fname): o = my_open_write(fname) o.write(''.join(self.pieces)) o.write('\n') o.close() def parse(self, node): """Parse a given node. This function in turn calls the `parse_<nodeType>` functions which handle the respective nodes. """ pm = getattr(self, "parse_%s" % node.__class__.__name__) pm(node) def parse_Document(self, node): self.parse(node.documentElement) def parse_Text(self, node): txt = node.data if txt == ' ': # this can happen when two tags follow in a text, e.g., # " ...</emph> <formaula>$..." etc. # here we want to keep the space. self.add_text(txt) return txt = txt.replace('\\', r'\\') txt = txt.replace('"', r'\"') # ignore pure whitespace m = self.space_re.match(txt) if m and len(m.group()) == len(txt): pass else: self.add_text(txt) def parse_Comment(self, node): """Parse a `COMMENT_NODE`. This does nothing for now.""" return def parse_Element(self, node): """Parse an `ELEMENT_NODE`. This calls specific `do_<tagName>` handers for different elements. If no handler is available the `subnode_parse` method is called. All tagNames specified in `self.ignores` are simply ignored. """ name = node.tagName ignores = self.ignores if name in ignores: return attr = "do_%s" % name if hasattr(self, attr): handlerMethod = getattr(self, attr) handlerMethod(node) else: self.subnode_parse(node) #if name not in self.generics: self.generics.append(name) # MARK: Special format parsing def subnode_parse(self, node, pieces=None, indent=0, ignore=[], restrict=None): """Parse the subnodes of a given node. Subnodes with tags in the `ignore` list are ignored. If pieces is given, use this as target for the parse results instead of self.pieces. Indent all lines by the amount given in `indent`. Note that the initial content in `pieces` is not indented. The final result is in any case added to self.pieces.""" if pieces is not None: old_pieces, self.pieces = self.pieces, pieces else: old_pieces = [] if type(indent) is int: indent = indent * ' ' if len(indent) > 0: pieces = ''.join(self.pieces) i_piece = pieces[:len(indent)] if self.pieces[-1:] == ['']: self.pieces = [pieces[len(indent):]] + [''] elif self.pieces != []: self.pieces = [pieces[len(indent):]] self.indent += len(indent) for n in node.childNodes: if restrict is not None: if n.nodeType == n.ELEMENT_NODE and n.tagName in restrict: self.parse(n) elif n.nodeType != n.ELEMENT_NODE or n.tagName not in ignore: self.parse(n) if len(indent) > 0: self.pieces = shift(self.pieces, indent, i_piece) self.indent -= len(indent) old_pieces.extend(self.pieces) self.pieces = old_pieces def surround_parse(self, node, pre_char, post_char): """Parse the subnodes of a given node. Subnodes with tags in the `ignore` list are ignored. Prepend `pre_char` and append `post_char` to the output in self.pieces.""" self.add_text(pre_char) self.subnode_parse(node) self.add_text(post_char) # MARK: Helper functions def get_specific_subnodes(self, node, name, recursive=0): """Given a node and a name, return a list of child `ELEMENT_NODEs`, that have a `tagName` matching the `name`. Search recursively for `recursive` levels. """ children = [x for x in node.childNodes if x.nodeType == x.ELEMENT_NODE] ret = [x for x in children if x.tagName == name] if recursive > 0: for x in children: ret.extend(self.get_specific_subnodes(x, name, recursive-1)) return ret def add_text(self, value): """Adds text corresponding to `value` into `self.pieces`.""" if isinstance(value, (list, tuple)): self.pieces.extend(value) else: self.pieces.append(value) def start_new_paragraph(self): """Make sure to create an empty line. This is overridden, if the previous text ends with the special marker ''. In that case, nothing is done. """ if self.pieces[-1:] == ['']: # respect special marker return elif self.pieces == []: # first paragraph, add '\n', override with '' self.pieces = ['\n'] elif self.pieces[-1][-1:] != '\n': # previous line not ended self.pieces.extend([' \n' ,'\n']) else: #default self.pieces.append('\n') def add_line_with_subsequent_indent(self, line, indent=4): """Add line of text and wrap such that subsequent lines are indented by `indent` spaces. """ if isinstance(line, (list, tuple)): line = ''.join(line) line = line.strip() width = self.textwidth-self.indent-indent wrapped_lines = textwrap.wrap(line[indent:], width=width) for i in range(len(wrapped_lines)): if wrapped_lines[i] != '': wrapped_lines[i] = indent * ' ' + wrapped_lines[i] self.pieces.append(line[:indent] + '\n'.join(wrapped_lines)[indent:] + ' \n') def extract_text(self, node): """Return the string representation of the node or list of nodes by parsing the subnodes, but returning the result as a string instead of adding it to `self.pieces`. Note that this allows extracting text even if the node is in the ignore list. """ if not isinstance(node, (list, tuple)): node = [node] pieces, self.pieces = self.pieces, [''] for n in node: for sn in n.childNodes: self.parse(sn) ret = ''.join(self.pieces) self.pieces = pieces return ret def get_function_signature(self, node): """Returns the function signature string for memberdef nodes.""" name = self.extract_text(self.get_specific_subnodes(node, 'name')) if self.with_type_info: argsstring = self.extract_text(self.get_specific_subnodes(node, 'argsstring')) else: argsstring = [] param_id = 1 for n_param in self.get_specific_subnodes(node, 'param'): declname = self.extract_text(self.get_specific_subnodes(n_param, 'declname')) if not declname: declname = 'arg' + str(param_id) defval = self.extract_text(self.get_specific_subnodes(n_param, 'defval')) if defval: defval = '=' + defval argsstring.append(declname + defval) param_id = param_id + 1 argsstring = '(' + ', '.join(argsstring) + ')' type = self.extract_text(self.get_specific_subnodes(node, 'type')) function_definition = name + argsstring if type != '' and type != 'void': function_definition = function_definition + ' -> ' + type return '`' + function_definition + '` ' # MARK: Special parsing tasks (need to be called manually) def make_constructor_list(self, constructor_nodes, classname): """Produces the "Constructors" section and the constructor signatures (since swig does not do so for classes) for class docstrings.""" if constructor_nodes == []: return self.add_text(['\n', 'Constructors', '\n', '------------']) for n in constructor_nodes: self.add_text('\n') self.add_line_with_subsequent_indent('* ' + self.get_function_signature(n)) self.subnode_parse(n, pieces = [], indent=4, ignore=['definition', 'name']) def make_attribute_list(self, node): """Produces the "Attributes" section in class docstrings for public member variables (attributes). """ atr_nodes = [] for n in self.get_specific_subnodes(node, 'memberdef', recursive=2): if n.attributes['kind'].value == 'variable' and n.attributes['prot'].value == 'public': atr_nodes.append(n) if not atr_nodes: return self.add_text(['\n', 'Attributes', '\n', '----------']) for n in atr_nodes: name = self.extract_text(self.get_specific_subnodes(n, 'name')) self.add_text(['\n* ', '`', name, '`', ' : ']) self.add_text(['`', self.extract_text(self.get_specific_subnodes(n, 'type')), '`']) self.add_text(' \n') restrict = ['briefdescription', 'detaileddescription'] self.subnode_parse(n, pieces=[''], indent=4, restrict=restrict) def get_memberdef_nodes_and_signatures(self, node, kind): """Collects the memberdef nodes and corresponding signatures that correspond to public function entries that are at most depth 2 deeper than the current (compounddef) node. Returns a dictionary with function signatures (what swig expects after the %feature directive) as keys, and a list of corresponding memberdef nodes as values.""" sig_dict = {} sig_prefix = '' if kind in ('file', 'namespace'): ns_node = node.getElementsByTagName('innernamespace') if not ns_node and kind == 'namespace': ns_node = node.getElementsByTagName('compoundname') if ns_node: sig_prefix = self.extract_text(ns_node[0]) + '::' elif kind in ('class', 'struct'): # Get the full function name. cn_node = node.getElementsByTagName('compoundname') sig_prefix = self.extract_text(cn_node[0]) + '::' md_nodes = self.get_specific_subnodes(node, 'memberdef', recursive=2) for n in md_nodes: if n.attributes['prot'].value != 'public': continue if n.attributes['kind'].value in ['variable', 'typedef']: continue if not self.get_specific_subnodes(n, 'definition'): continue name = self.extract_text(self.get_specific_subnodes(n, 'name')) if name[:8] == 'operator': continue sig = sig_prefix + name if sig in sig_dict: sig_dict[sig].append(n) else: sig_dict[sig] = [n] return sig_dict def handle_typical_memberdefs_no_overload(self, signature, memberdef_nodes): """Produce standard documentation for memberdef_nodes.""" for n in memberdef_nodes: self.add_text(['\n', '%feature("docstring") ', signature, ' "', '\n']) if self.with_function_signature: self.add_line_with_subsequent_indent(self.get_function_signature(n)) self.subnode_parse(n, pieces=[], ignore=['definition', 'name']) self.add_text(['";', '\n']) def handle_typical_memberdefs(self, signature, memberdef_nodes): """Produces docstring entries containing an "Overloaded function" section with the documentation for each overload, if the function is overloaded and self.with_overloaded_functions is set. Else, produce normal documentation. """ if len(memberdef_nodes) == 1 or not self.with_overloaded_functions: self.handle_typical_memberdefs_no_overload(signature, memberdef_nodes) return self.add_text(['\n', '%feature("docstring") ', signature, ' "', '\n']) if self.with_function_signature: for n in memberdef_nodes: self.add_line_with_subsequent_indent(self.get_function_signature(n)) self.add_text('\n') self.add_text(['Overloaded function', '\n', '-------------------']) for n in memberdef_nodes: self.add_text('\n') self.add_line_with_subsequent_indent('* ' + self.get_function_signature(n)) self.subnode_parse(n, pieces=[], indent=4, ignore=['definition', 'name']) self.add_text(['";', '\n']) # MARK: Tag handlers def do_linebreak(self, node): self.add_text(' ') def do_ndash(self, node): self.add_text('--') def do_mdash(self, node): self.add_text('---') def do_emphasis(self, node): self.surround_parse(node, '*', '*') def do_bold(self, node): self.surround_parse(node, '**', '**') def do_computeroutput(self, node): self.surround_parse(node, '`', '`') def do_heading(self, node): self.start_new_paragraph() pieces, self.pieces = self.pieces, [''] level = int(node.attributes['level'].value) self.subnode_parse(node) if level == 1: self.pieces.insert(0, '\n') self.add_text(['\n', len(''.join(self.pieces).strip()) * '=']) elif level == 2: self.add_text(['\n', len(''.join(self.pieces).strip()) * '-']) elif level >= 3: self.pieces.insert(0, level * '#' + ' ') # make following text have no gap to the heading: pieces.extend([''.join(self.pieces) + ' \n', '']) self.pieces = pieces def do_verbatim(self, node): self.start_new_paragraph() self.subnode_parse(node, pieces=[''], indent=4) def do_blockquote(self, node): self.start_new_paragraph() self.subnode_parse(node, pieces=[''], indent='> ') def do_hruler(self, node): self.start_new_paragraph() self.add_text('* * * * * \n') def do_includes(self, node): self.add_text('\nC++ includes: ') self.subnode_parse(node) self.add_text('\n') # MARK: Para tag handler def do_para(self, node): """This is the only place where text wrapping is automatically performed. Generally, this function parses the node (locally), wraps the text, and then adds the result to self.pieces. However, it may be convenient to allow the previous content of self.pieces to be included in the text wrapping. For this, use the following *convention*: If self.pieces ends with '', treat the _previous_ entry as part of the current paragraph. Else, insert new-line and start a new paragraph and "wrapping context". Paragraphs always end with ' \n', but if the parsed content ends with the special symbol '', this is passed on. """ if self.pieces[-1:] == ['']: pieces, self.pieces = self.pieces[:-2], self.pieces[-2:-1] else: self.add_text('\n') pieces, self.pieces = self.pieces, [''] self.subnode_parse(node) dont_end_paragraph = self.pieces[-1:] == [''] # Now do the text wrapping: width = self.textwidth - self.indent wrapped_para = [] for line in ''.join(self.pieces).splitlines(): keep_markdown_newline = line[-2:] == ' ' w_line = textwrap.wrap(line, width=width, break_long_words=False) if w_line == []: w_line = [''] if keep_markdown_newline: w_line[-1] = w_line[-1] + ' ' for wl in w_line: wrapped_para.append(wl + '\n') if wrapped_para: if wrapped_para[-1][-3:] != ' \n': wrapped_para[-1] = wrapped_para[-1][:-1] + ' \n' if dont_end_paragraph: wrapped_para.append('') pieces.extend(wrapped_para) self.pieces = pieces # MARK: List tag handlers def do_itemizedlist(self, node): if self.listitem == '': self.start_new_paragraph() elif self.pieces != [] and self.pieces[-1:] != ['']: self.add_text('\n') listitem = self.listitem if self.listitem in ['*', '-']: self.listitem = '-' else: self.listitem = '*' self.subnode_parse(node) self.listitem = listitem def do_orderedlist(self, node): if self.listitem == '': self.start_new_paragraph() elif self.pieces != [] and self.pieces[-1:] != ['']: self.add_text('\n') listitem = self.listitem self.listitem = 0 self.subnode_parse(node) self.listitem = listitem def do_listitem(self, node): try: self.listitem = int(self.listitem) + 1 item = str(self.listitem) + '. ' except: item = str(self.listitem) + ' ' self.subnode_parse(node, item, indent=4) # MARK: Parameter list tag handlers def do_parameterlist(self, node): self.start_new_paragraph() text = 'unknown' for key, val in node.attributes.items(): if key == 'kind': if val == 'param': text = 'Parameters' elif val == 'exception': text = 'Exceptions' elif val == 'retval': text = 'Returns' else: text = val break if self.indent == 0: self.add_text([text, '\n', len(text) * '-', '\n']) else: self.add_text([text, ': \n']) self.subnode_parse(node) def do_parameteritem(self, node): self.subnode_parse(node, pieces=['* ', '']) def do_parameternamelist(self, node): self.subnode_parse(node) self.add_text([' :', ' \n']) def do_parametername(self, node): if self.pieces != [] and self.pieces != ['* ', '']: self.add_text(', ') data = self.extract_text(node) self.add_text(['`', data, '`']) def do_parameterdescription(self, node): self.subnode_parse(node, pieces=[''], indent=4) # MARK: Section tag handler def do_simplesect(self, node): kind = node.attributes['kind'].value if kind in ('date', 'rcs', 'version'): return self.start_new_paragraph() if kind == 'warning': self.subnode_parse(node, pieces=['**Warning**: ',''], indent=4) elif kind == 'see': self.subnode_parse(node, pieces=['See also: ',''], indent=4) elif kind == 'return': if self.indent == 0: pieces = ['Returns', '\n', len('Returns') * '-', '\n', ''] else: pieces = ['Returns:', '\n', ''] self.subnode_parse(node, pieces=pieces) else: self.subnode_parse(node, pieces=[kind + ': ',''], indent=4) # MARK: %feature("docstring") producing tag handlers def do_compounddef(self, node): """This produces %feature("docstring") entries for classes, and handles class, namespace and file memberdef entries specially to allow for overloaded functions. For other cases, passes parsing on to standard handlers (which may produce unexpected results). """ kind = node.attributes['kind'].value if kind in ('class', 'struct'): prot = node.attributes['prot'].value if prot != 'public': return self.add_text('\n\n') classdefn = self.extract_text(self.get_specific_subnodes(node, 'compoundname')) classname = classdefn.split('::')[-1] self.add_text('%%feature("docstring") %s "\n' % classdefn) if self.with_constructor_list: constructor_nodes = [] for n in self.get_specific_subnodes(node, 'memberdef', recursive=2): if n.attributes['prot'].value == 'public': if self.extract_text(self.get_specific_subnodes(n, 'definition')) == classdefn + '::' + classname: constructor_nodes.append(n) for n in constructor_nodes: self.add_line_with_subsequent_indent(self.get_function_signature(n)) names = ('briefdescription','detaileddescription') sub_dict = self.get_specific_nodes(node, names) for n in ('briefdescription','detaileddescription'): if n in sub_dict: self.parse(sub_dict[n]) if self.with_constructor_list: self.make_constructor_list(constructor_nodes, classname) if self.with_attribute_list: self.make_attribute_list(node) sub_list = self.get_specific_subnodes(node, 'includes') if sub_list: self.parse(sub_list[0]) self.add_text(['";', '\n']) names = ['compoundname', 'briefdescription','detaileddescription', 'includes'] self.subnode_parse(node, ignore = names) elif kind in ('file', 'namespace'): nodes = node.getElementsByTagName('sectiondef') for n in nodes: self.parse(n) # now explicitely handle possibly overloaded member functions. if kind in ['class', 'struct','file', 'namespace']: md_nodes = self.get_memberdef_nodes_and_signatures(node, kind) for sig in md_nodes: self.handle_typical_memberdefs(sig, md_nodes[sig]) def do_memberdef(self, node): """Handle cases outside of class, struct, file or namespace. These are now dealt with by `handle_overloaded_memberfunction`. Do these even exist??? """ prot = node.attributes['prot'].value id = node.attributes['id'].value kind = node.attributes['kind'].value tmp = node.parentNode.parentNode.parentNode compdef = tmp.getElementsByTagName('compounddef')[0] cdef_kind = compdef.attributes['kind'].value if cdef_kind in ('file', 'namespace', 'class', 'struct'): # These cases are now handled by `handle_typical_memberdefs` return if prot != 'public': return first = self.get_specific_nodes(node, ('definition', 'name')) name = self.extract_text(first['name']) if name[:8] == 'operator': # Don't handle operators yet. return if not 'definition' in first or kind in ['variable', 'typedef']: return data = self.extract_text(first['definition']) self.add_text('\n') self.add_text(['/* where did this entry come from??? */', '\n']) self.add_text('%feature("docstring") %s "\n%s' % (data, data)) for n in node.childNodes: if n not in first.values(): self.parse(n) self.add_text(['";', '\n']) # MARK: Entry tag handlers (dont print anything meaningful) def do_sectiondef(self, node): kind = node.attributes['kind'].value if kind in ('public-func', 'func', 'user-defined', ''): self.subnode_parse(node) def do_header(self, node): """For a user defined section def a header field is present which should not be printed as such, so we comment it in the output.""" data = self.extract_text(node) self.add_text('\n/*\n %s \n*/\n' % data) # If our immediate sibling is a 'description' node then we # should comment that out also and remove it from the parent # node's children. parent = node.parentNode idx = parent.childNodes.index(node) if len(parent.childNodes) >= idx + 2: nd = parent.childNodes[idx + 2] if nd.nodeName == 'description': nd = parent.removeChild(nd) self.add_text('\n/*') self.subnode_parse(nd) self.add_text('\n*/\n') def do_member(self, node): kind = node.attributes['kind'].value refid = node.attributes['refid'].value if kind == 'function' and refid[:9] == 'namespace': self.subnode_parse(node) def do_doxygenindex(self, node): self.multi = 1 comps = node.getElementsByTagName('compound') for c in comps: refid = c.attributes['refid'].value fname = refid + '.xml' if not os.path.exists(fname): fname = os.path.join(self.my_dir, fname) if not self.quiet: print("parsing file: %s" % fname) p = Doxy2SWIG(fname, with_function_signature = self.with_function_signature, with_type_info = self.with_type_info, with_constructor_list = self.with_constructor_list, with_attribute_list = self.with_attribute_list, with_overloaded_functions = self.with_overloaded_functions, textwidth = self.textwidth, quiet = self.quiet) p.generate() self.pieces.extend(p.pieces)
basler/pypylon
scripts/builddoxy2swig/doxy2swig/doxy2swig.py
Doxy2SWIG.add_text
python
def add_text(self, value): if isinstance(value, (list, tuple)): self.pieces.extend(value) else: self.pieces.append(value)
Adds text corresponding to `value` into `self.pieces`.
train
https://github.com/basler/pypylon/blob/d3510fa419b1c2b17f3f0b80a5fbb720c7b84008/scripts/builddoxy2swig/doxy2swig/doxy2swig.py#L288-L293
null
class Doxy2SWIG: """Converts Doxygen generated XML files into a file containing docstrings that can be used by SWIG-1.3.x that have support for feature("docstring"). Once the data is parsed it is stored in self.pieces. """ def __init__(self, src, with_function_signature = False, with_type_info = False, with_constructor_list = False, with_attribute_list = False, with_overloaded_functions = False, textwidth = 80, quiet = False): """Initialize the instance given a source object. `src` can be a file or filename. If you do not want to include function definitions from doxygen then set `include_function_definition` to `False`. This is handy since this allows you to use the swig generated function definition using %feature("autodoc", [0,1]). """ # options: self.with_function_signature = with_function_signature self.with_type_info = with_type_info self.with_constructor_list = with_constructor_list self.with_attribute_list = with_attribute_list self.with_overloaded_functions = with_overloaded_functions self.textwidth = textwidth self.quiet = quiet # state: self.indent = 0 self.listitem = '' self.pieces = [] f = my_open_read(src) self.my_dir = os.path.dirname(f.name) self.xmldoc = minidom.parse(f).documentElement f.close() self.pieces.append('\n// File: %s\n' % os.path.basename(f.name)) self.space_re = re.compile(r'\s+') self.lead_spc = re.compile(r'^(%feature\S+\s+\S+\s*?)"\s+(\S)') self.multi = 0 self.ignores = ['inheritancegraph', 'param', 'listofallmembers', 'innerclass', 'name', 'declname', 'incdepgraph', 'invincdepgraph', 'programlisting', 'type', 'references', 'referencedby', 'location', 'collaborationgraph', 'reimplements', 'reimplementedby', 'derivedcompoundref', 'basecompoundref', 'argsstring', 'definition', 'exceptions'] #self.generics = [] def generate(self): """Parses the file set in the initialization. The resulting data is stored in `self.pieces`. """ self.parse(self.xmldoc) def write(self, fname): o = my_open_write(fname) o.write(''.join(self.pieces)) o.write('\n') o.close() def parse(self, node): """Parse a given node. This function in turn calls the `parse_<nodeType>` functions which handle the respective nodes. """ pm = getattr(self, "parse_%s" % node.__class__.__name__) pm(node) def parse_Document(self, node): self.parse(node.documentElement) def parse_Text(self, node): txt = node.data if txt == ' ': # this can happen when two tags follow in a text, e.g., # " ...</emph> <formaula>$..." etc. # here we want to keep the space. self.add_text(txt) return txt = txt.replace('\\', r'\\') txt = txt.replace('"', r'\"') # ignore pure whitespace m = self.space_re.match(txt) if m and len(m.group()) == len(txt): pass else: self.add_text(txt) def parse_Comment(self, node): """Parse a `COMMENT_NODE`. This does nothing for now.""" return def parse_Element(self, node): """Parse an `ELEMENT_NODE`. This calls specific `do_<tagName>` handers for different elements. If no handler is available the `subnode_parse` method is called. All tagNames specified in `self.ignores` are simply ignored. """ name = node.tagName ignores = self.ignores if name in ignores: return attr = "do_%s" % name if hasattr(self, attr): handlerMethod = getattr(self, attr) handlerMethod(node) else: self.subnode_parse(node) #if name not in self.generics: self.generics.append(name) # MARK: Special format parsing def subnode_parse(self, node, pieces=None, indent=0, ignore=[], restrict=None): """Parse the subnodes of a given node. Subnodes with tags in the `ignore` list are ignored. If pieces is given, use this as target for the parse results instead of self.pieces. Indent all lines by the amount given in `indent`. Note that the initial content in `pieces` is not indented. The final result is in any case added to self.pieces.""" if pieces is not None: old_pieces, self.pieces = self.pieces, pieces else: old_pieces = [] if type(indent) is int: indent = indent * ' ' if len(indent) > 0: pieces = ''.join(self.pieces) i_piece = pieces[:len(indent)] if self.pieces[-1:] == ['']: self.pieces = [pieces[len(indent):]] + [''] elif self.pieces != []: self.pieces = [pieces[len(indent):]] self.indent += len(indent) for n in node.childNodes: if restrict is not None: if n.nodeType == n.ELEMENT_NODE and n.tagName in restrict: self.parse(n) elif n.nodeType != n.ELEMENT_NODE or n.tagName not in ignore: self.parse(n) if len(indent) > 0: self.pieces = shift(self.pieces, indent, i_piece) self.indent -= len(indent) old_pieces.extend(self.pieces) self.pieces = old_pieces def surround_parse(self, node, pre_char, post_char): """Parse the subnodes of a given node. Subnodes with tags in the `ignore` list are ignored. Prepend `pre_char` and append `post_char` to the output in self.pieces.""" self.add_text(pre_char) self.subnode_parse(node) self.add_text(post_char) # MARK: Helper functions def get_specific_subnodes(self, node, name, recursive=0): """Given a node and a name, return a list of child `ELEMENT_NODEs`, that have a `tagName` matching the `name`. Search recursively for `recursive` levels. """ children = [x for x in node.childNodes if x.nodeType == x.ELEMENT_NODE] ret = [x for x in children if x.tagName == name] if recursive > 0: for x in children: ret.extend(self.get_specific_subnodes(x, name, recursive-1)) return ret def get_specific_nodes(self, node, names): """Given a node and a sequence of strings in `names`, return a dictionary containing the names as keys and child `ELEMENT_NODEs`, that have a `tagName` equal to the name. """ nodes = [(x.tagName, x) for x in node.childNodes if x.nodeType == x.ELEMENT_NODE and x.tagName in names] return dict(nodes) def start_new_paragraph(self): """Make sure to create an empty line. This is overridden, if the previous text ends with the special marker ''. In that case, nothing is done. """ if self.pieces[-1:] == ['']: # respect special marker return elif self.pieces == []: # first paragraph, add '\n', override with '' self.pieces = ['\n'] elif self.pieces[-1][-1:] != '\n': # previous line not ended self.pieces.extend([' \n' ,'\n']) else: #default self.pieces.append('\n') def add_line_with_subsequent_indent(self, line, indent=4): """Add line of text and wrap such that subsequent lines are indented by `indent` spaces. """ if isinstance(line, (list, tuple)): line = ''.join(line) line = line.strip() width = self.textwidth-self.indent-indent wrapped_lines = textwrap.wrap(line[indent:], width=width) for i in range(len(wrapped_lines)): if wrapped_lines[i] != '': wrapped_lines[i] = indent * ' ' + wrapped_lines[i] self.pieces.append(line[:indent] + '\n'.join(wrapped_lines)[indent:] + ' \n') def extract_text(self, node): """Return the string representation of the node or list of nodes by parsing the subnodes, but returning the result as a string instead of adding it to `self.pieces`. Note that this allows extracting text even if the node is in the ignore list. """ if not isinstance(node, (list, tuple)): node = [node] pieces, self.pieces = self.pieces, [''] for n in node: for sn in n.childNodes: self.parse(sn) ret = ''.join(self.pieces) self.pieces = pieces return ret def get_function_signature(self, node): """Returns the function signature string for memberdef nodes.""" name = self.extract_text(self.get_specific_subnodes(node, 'name')) if self.with_type_info: argsstring = self.extract_text(self.get_specific_subnodes(node, 'argsstring')) else: argsstring = [] param_id = 1 for n_param in self.get_specific_subnodes(node, 'param'): declname = self.extract_text(self.get_specific_subnodes(n_param, 'declname')) if not declname: declname = 'arg' + str(param_id) defval = self.extract_text(self.get_specific_subnodes(n_param, 'defval')) if defval: defval = '=' + defval argsstring.append(declname + defval) param_id = param_id + 1 argsstring = '(' + ', '.join(argsstring) + ')' type = self.extract_text(self.get_specific_subnodes(node, 'type')) function_definition = name + argsstring if type != '' and type != 'void': function_definition = function_definition + ' -> ' + type return '`' + function_definition + '` ' # MARK: Special parsing tasks (need to be called manually) def make_constructor_list(self, constructor_nodes, classname): """Produces the "Constructors" section and the constructor signatures (since swig does not do so for classes) for class docstrings.""" if constructor_nodes == []: return self.add_text(['\n', 'Constructors', '\n', '------------']) for n in constructor_nodes: self.add_text('\n') self.add_line_with_subsequent_indent('* ' + self.get_function_signature(n)) self.subnode_parse(n, pieces = [], indent=4, ignore=['definition', 'name']) def make_attribute_list(self, node): """Produces the "Attributes" section in class docstrings for public member variables (attributes). """ atr_nodes = [] for n in self.get_specific_subnodes(node, 'memberdef', recursive=2): if n.attributes['kind'].value == 'variable' and n.attributes['prot'].value == 'public': atr_nodes.append(n) if not atr_nodes: return self.add_text(['\n', 'Attributes', '\n', '----------']) for n in atr_nodes: name = self.extract_text(self.get_specific_subnodes(n, 'name')) self.add_text(['\n* ', '`', name, '`', ' : ']) self.add_text(['`', self.extract_text(self.get_specific_subnodes(n, 'type')), '`']) self.add_text(' \n') restrict = ['briefdescription', 'detaileddescription'] self.subnode_parse(n, pieces=[''], indent=4, restrict=restrict) def get_memberdef_nodes_and_signatures(self, node, kind): """Collects the memberdef nodes and corresponding signatures that correspond to public function entries that are at most depth 2 deeper than the current (compounddef) node. Returns a dictionary with function signatures (what swig expects after the %feature directive) as keys, and a list of corresponding memberdef nodes as values.""" sig_dict = {} sig_prefix = '' if kind in ('file', 'namespace'): ns_node = node.getElementsByTagName('innernamespace') if not ns_node and kind == 'namespace': ns_node = node.getElementsByTagName('compoundname') if ns_node: sig_prefix = self.extract_text(ns_node[0]) + '::' elif kind in ('class', 'struct'): # Get the full function name. cn_node = node.getElementsByTagName('compoundname') sig_prefix = self.extract_text(cn_node[0]) + '::' md_nodes = self.get_specific_subnodes(node, 'memberdef', recursive=2) for n in md_nodes: if n.attributes['prot'].value != 'public': continue if n.attributes['kind'].value in ['variable', 'typedef']: continue if not self.get_specific_subnodes(n, 'definition'): continue name = self.extract_text(self.get_specific_subnodes(n, 'name')) if name[:8] == 'operator': continue sig = sig_prefix + name if sig in sig_dict: sig_dict[sig].append(n) else: sig_dict[sig] = [n] return sig_dict def handle_typical_memberdefs_no_overload(self, signature, memberdef_nodes): """Produce standard documentation for memberdef_nodes.""" for n in memberdef_nodes: self.add_text(['\n', '%feature("docstring") ', signature, ' "', '\n']) if self.with_function_signature: self.add_line_with_subsequent_indent(self.get_function_signature(n)) self.subnode_parse(n, pieces=[], ignore=['definition', 'name']) self.add_text(['";', '\n']) def handle_typical_memberdefs(self, signature, memberdef_nodes): """Produces docstring entries containing an "Overloaded function" section with the documentation for each overload, if the function is overloaded and self.with_overloaded_functions is set. Else, produce normal documentation. """ if len(memberdef_nodes) == 1 or not self.with_overloaded_functions: self.handle_typical_memberdefs_no_overload(signature, memberdef_nodes) return self.add_text(['\n', '%feature("docstring") ', signature, ' "', '\n']) if self.with_function_signature: for n in memberdef_nodes: self.add_line_with_subsequent_indent(self.get_function_signature(n)) self.add_text('\n') self.add_text(['Overloaded function', '\n', '-------------------']) for n in memberdef_nodes: self.add_text('\n') self.add_line_with_subsequent_indent('* ' + self.get_function_signature(n)) self.subnode_parse(n, pieces=[], indent=4, ignore=['definition', 'name']) self.add_text(['";', '\n']) # MARK: Tag handlers def do_linebreak(self, node): self.add_text(' ') def do_ndash(self, node): self.add_text('--') def do_mdash(self, node): self.add_text('---') def do_emphasis(self, node): self.surround_parse(node, '*', '*') def do_bold(self, node): self.surround_parse(node, '**', '**') def do_computeroutput(self, node): self.surround_parse(node, '`', '`') def do_heading(self, node): self.start_new_paragraph() pieces, self.pieces = self.pieces, [''] level = int(node.attributes['level'].value) self.subnode_parse(node) if level == 1: self.pieces.insert(0, '\n') self.add_text(['\n', len(''.join(self.pieces).strip()) * '=']) elif level == 2: self.add_text(['\n', len(''.join(self.pieces).strip()) * '-']) elif level >= 3: self.pieces.insert(0, level * '#' + ' ') # make following text have no gap to the heading: pieces.extend([''.join(self.pieces) + ' \n', '']) self.pieces = pieces def do_verbatim(self, node): self.start_new_paragraph() self.subnode_parse(node, pieces=[''], indent=4) def do_blockquote(self, node): self.start_new_paragraph() self.subnode_parse(node, pieces=[''], indent='> ') def do_hruler(self, node): self.start_new_paragraph() self.add_text('* * * * * \n') def do_includes(self, node): self.add_text('\nC++ includes: ') self.subnode_parse(node) self.add_text('\n') # MARK: Para tag handler def do_para(self, node): """This is the only place where text wrapping is automatically performed. Generally, this function parses the node (locally), wraps the text, and then adds the result to self.pieces. However, it may be convenient to allow the previous content of self.pieces to be included in the text wrapping. For this, use the following *convention*: If self.pieces ends with '', treat the _previous_ entry as part of the current paragraph. Else, insert new-line and start a new paragraph and "wrapping context". Paragraphs always end with ' \n', but if the parsed content ends with the special symbol '', this is passed on. """ if self.pieces[-1:] == ['']: pieces, self.pieces = self.pieces[:-2], self.pieces[-2:-1] else: self.add_text('\n') pieces, self.pieces = self.pieces, [''] self.subnode_parse(node) dont_end_paragraph = self.pieces[-1:] == [''] # Now do the text wrapping: width = self.textwidth - self.indent wrapped_para = [] for line in ''.join(self.pieces).splitlines(): keep_markdown_newline = line[-2:] == ' ' w_line = textwrap.wrap(line, width=width, break_long_words=False) if w_line == []: w_line = [''] if keep_markdown_newline: w_line[-1] = w_line[-1] + ' ' for wl in w_line: wrapped_para.append(wl + '\n') if wrapped_para: if wrapped_para[-1][-3:] != ' \n': wrapped_para[-1] = wrapped_para[-1][:-1] + ' \n' if dont_end_paragraph: wrapped_para.append('') pieces.extend(wrapped_para) self.pieces = pieces # MARK: List tag handlers def do_itemizedlist(self, node): if self.listitem == '': self.start_new_paragraph() elif self.pieces != [] and self.pieces[-1:] != ['']: self.add_text('\n') listitem = self.listitem if self.listitem in ['*', '-']: self.listitem = '-' else: self.listitem = '*' self.subnode_parse(node) self.listitem = listitem def do_orderedlist(self, node): if self.listitem == '': self.start_new_paragraph() elif self.pieces != [] and self.pieces[-1:] != ['']: self.add_text('\n') listitem = self.listitem self.listitem = 0 self.subnode_parse(node) self.listitem = listitem def do_listitem(self, node): try: self.listitem = int(self.listitem) + 1 item = str(self.listitem) + '. ' except: item = str(self.listitem) + ' ' self.subnode_parse(node, item, indent=4) # MARK: Parameter list tag handlers def do_parameterlist(self, node): self.start_new_paragraph() text = 'unknown' for key, val in node.attributes.items(): if key == 'kind': if val == 'param': text = 'Parameters' elif val == 'exception': text = 'Exceptions' elif val == 'retval': text = 'Returns' else: text = val break if self.indent == 0: self.add_text([text, '\n', len(text) * '-', '\n']) else: self.add_text([text, ': \n']) self.subnode_parse(node) def do_parameteritem(self, node): self.subnode_parse(node, pieces=['* ', '']) def do_parameternamelist(self, node): self.subnode_parse(node) self.add_text([' :', ' \n']) def do_parametername(self, node): if self.pieces != [] and self.pieces != ['* ', '']: self.add_text(', ') data = self.extract_text(node) self.add_text(['`', data, '`']) def do_parameterdescription(self, node): self.subnode_parse(node, pieces=[''], indent=4) # MARK: Section tag handler def do_simplesect(self, node): kind = node.attributes['kind'].value if kind in ('date', 'rcs', 'version'): return self.start_new_paragraph() if kind == 'warning': self.subnode_parse(node, pieces=['**Warning**: ',''], indent=4) elif kind == 'see': self.subnode_parse(node, pieces=['See also: ',''], indent=4) elif kind == 'return': if self.indent == 0: pieces = ['Returns', '\n', len('Returns') * '-', '\n', ''] else: pieces = ['Returns:', '\n', ''] self.subnode_parse(node, pieces=pieces) else: self.subnode_parse(node, pieces=[kind + ': ',''], indent=4) # MARK: %feature("docstring") producing tag handlers def do_compounddef(self, node): """This produces %feature("docstring") entries for classes, and handles class, namespace and file memberdef entries specially to allow for overloaded functions. For other cases, passes parsing on to standard handlers (which may produce unexpected results). """ kind = node.attributes['kind'].value if kind in ('class', 'struct'): prot = node.attributes['prot'].value if prot != 'public': return self.add_text('\n\n') classdefn = self.extract_text(self.get_specific_subnodes(node, 'compoundname')) classname = classdefn.split('::')[-1] self.add_text('%%feature("docstring") %s "\n' % classdefn) if self.with_constructor_list: constructor_nodes = [] for n in self.get_specific_subnodes(node, 'memberdef', recursive=2): if n.attributes['prot'].value == 'public': if self.extract_text(self.get_specific_subnodes(n, 'definition')) == classdefn + '::' + classname: constructor_nodes.append(n) for n in constructor_nodes: self.add_line_with_subsequent_indent(self.get_function_signature(n)) names = ('briefdescription','detaileddescription') sub_dict = self.get_specific_nodes(node, names) for n in ('briefdescription','detaileddescription'): if n in sub_dict: self.parse(sub_dict[n]) if self.with_constructor_list: self.make_constructor_list(constructor_nodes, classname) if self.with_attribute_list: self.make_attribute_list(node) sub_list = self.get_specific_subnodes(node, 'includes') if sub_list: self.parse(sub_list[0]) self.add_text(['";', '\n']) names = ['compoundname', 'briefdescription','detaileddescription', 'includes'] self.subnode_parse(node, ignore = names) elif kind in ('file', 'namespace'): nodes = node.getElementsByTagName('sectiondef') for n in nodes: self.parse(n) # now explicitely handle possibly overloaded member functions. if kind in ['class', 'struct','file', 'namespace']: md_nodes = self.get_memberdef_nodes_and_signatures(node, kind) for sig in md_nodes: self.handle_typical_memberdefs(sig, md_nodes[sig]) def do_memberdef(self, node): """Handle cases outside of class, struct, file or namespace. These are now dealt with by `handle_overloaded_memberfunction`. Do these even exist??? """ prot = node.attributes['prot'].value id = node.attributes['id'].value kind = node.attributes['kind'].value tmp = node.parentNode.parentNode.parentNode compdef = tmp.getElementsByTagName('compounddef')[0] cdef_kind = compdef.attributes['kind'].value if cdef_kind in ('file', 'namespace', 'class', 'struct'): # These cases are now handled by `handle_typical_memberdefs` return if prot != 'public': return first = self.get_specific_nodes(node, ('definition', 'name')) name = self.extract_text(first['name']) if name[:8] == 'operator': # Don't handle operators yet. return if not 'definition' in first or kind in ['variable', 'typedef']: return data = self.extract_text(first['definition']) self.add_text('\n') self.add_text(['/* where did this entry come from??? */', '\n']) self.add_text('%feature("docstring") %s "\n%s' % (data, data)) for n in node.childNodes: if n not in first.values(): self.parse(n) self.add_text(['";', '\n']) # MARK: Entry tag handlers (dont print anything meaningful) def do_sectiondef(self, node): kind = node.attributes['kind'].value if kind in ('public-func', 'func', 'user-defined', ''): self.subnode_parse(node) def do_header(self, node): """For a user defined section def a header field is present which should not be printed as such, so we comment it in the output.""" data = self.extract_text(node) self.add_text('\n/*\n %s \n*/\n' % data) # If our immediate sibling is a 'description' node then we # should comment that out also and remove it from the parent # node's children. parent = node.parentNode idx = parent.childNodes.index(node) if len(parent.childNodes) >= idx + 2: nd = parent.childNodes[idx + 2] if nd.nodeName == 'description': nd = parent.removeChild(nd) self.add_text('\n/*') self.subnode_parse(nd) self.add_text('\n*/\n') def do_member(self, node): kind = node.attributes['kind'].value refid = node.attributes['refid'].value if kind == 'function' and refid[:9] == 'namespace': self.subnode_parse(node) def do_doxygenindex(self, node): self.multi = 1 comps = node.getElementsByTagName('compound') for c in comps: refid = c.attributes['refid'].value fname = refid + '.xml' if not os.path.exists(fname): fname = os.path.join(self.my_dir, fname) if not self.quiet: print("parsing file: %s" % fname) p = Doxy2SWIG(fname, with_function_signature = self.with_function_signature, with_type_info = self.with_type_info, with_constructor_list = self.with_constructor_list, with_attribute_list = self.with_attribute_list, with_overloaded_functions = self.with_overloaded_functions, textwidth = self.textwidth, quiet = self.quiet) p.generate() self.pieces.extend(p.pieces)
basler/pypylon
scripts/builddoxy2swig/doxy2swig/doxy2swig.py
Doxy2SWIG.start_new_paragraph
python
def start_new_paragraph(self): if self.pieces[-1:] == ['']: # respect special marker return elif self.pieces == []: # first paragraph, add '\n', override with '' self.pieces = ['\n'] elif self.pieces[-1][-1:] != '\n': # previous line not ended self.pieces.extend([' \n' ,'\n']) else: #default self.pieces.append('\n')
Make sure to create an empty line. This is overridden, if the previous text ends with the special marker ''. In that case, nothing is done.
train
https://github.com/basler/pypylon/blob/d3510fa419b1c2b17f3f0b80a5fbb720c7b84008/scripts/builddoxy2swig/doxy2swig/doxy2swig.py#L295-L306
null
class Doxy2SWIG: """Converts Doxygen generated XML files into a file containing docstrings that can be used by SWIG-1.3.x that have support for feature("docstring"). Once the data is parsed it is stored in self.pieces. """ def __init__(self, src, with_function_signature = False, with_type_info = False, with_constructor_list = False, with_attribute_list = False, with_overloaded_functions = False, textwidth = 80, quiet = False): """Initialize the instance given a source object. `src` can be a file or filename. If you do not want to include function definitions from doxygen then set `include_function_definition` to `False`. This is handy since this allows you to use the swig generated function definition using %feature("autodoc", [0,1]). """ # options: self.with_function_signature = with_function_signature self.with_type_info = with_type_info self.with_constructor_list = with_constructor_list self.with_attribute_list = with_attribute_list self.with_overloaded_functions = with_overloaded_functions self.textwidth = textwidth self.quiet = quiet # state: self.indent = 0 self.listitem = '' self.pieces = [] f = my_open_read(src) self.my_dir = os.path.dirname(f.name) self.xmldoc = minidom.parse(f).documentElement f.close() self.pieces.append('\n// File: %s\n' % os.path.basename(f.name)) self.space_re = re.compile(r'\s+') self.lead_spc = re.compile(r'^(%feature\S+\s+\S+\s*?)"\s+(\S)') self.multi = 0 self.ignores = ['inheritancegraph', 'param', 'listofallmembers', 'innerclass', 'name', 'declname', 'incdepgraph', 'invincdepgraph', 'programlisting', 'type', 'references', 'referencedby', 'location', 'collaborationgraph', 'reimplements', 'reimplementedby', 'derivedcompoundref', 'basecompoundref', 'argsstring', 'definition', 'exceptions'] #self.generics = [] def generate(self): """Parses the file set in the initialization. The resulting data is stored in `self.pieces`. """ self.parse(self.xmldoc) def write(self, fname): o = my_open_write(fname) o.write(''.join(self.pieces)) o.write('\n') o.close() def parse(self, node): """Parse a given node. This function in turn calls the `parse_<nodeType>` functions which handle the respective nodes. """ pm = getattr(self, "parse_%s" % node.__class__.__name__) pm(node) def parse_Document(self, node): self.parse(node.documentElement) def parse_Text(self, node): txt = node.data if txt == ' ': # this can happen when two tags follow in a text, e.g., # " ...</emph> <formaula>$..." etc. # here we want to keep the space. self.add_text(txt) return txt = txt.replace('\\', r'\\') txt = txt.replace('"', r'\"') # ignore pure whitespace m = self.space_re.match(txt) if m and len(m.group()) == len(txt): pass else: self.add_text(txt) def parse_Comment(self, node): """Parse a `COMMENT_NODE`. This does nothing for now.""" return def parse_Element(self, node): """Parse an `ELEMENT_NODE`. This calls specific `do_<tagName>` handers for different elements. If no handler is available the `subnode_parse` method is called. All tagNames specified in `self.ignores` are simply ignored. """ name = node.tagName ignores = self.ignores if name in ignores: return attr = "do_%s" % name if hasattr(self, attr): handlerMethod = getattr(self, attr) handlerMethod(node) else: self.subnode_parse(node) #if name not in self.generics: self.generics.append(name) # MARK: Special format parsing def subnode_parse(self, node, pieces=None, indent=0, ignore=[], restrict=None): """Parse the subnodes of a given node. Subnodes with tags in the `ignore` list are ignored. If pieces is given, use this as target for the parse results instead of self.pieces. Indent all lines by the amount given in `indent`. Note that the initial content in `pieces` is not indented. The final result is in any case added to self.pieces.""" if pieces is not None: old_pieces, self.pieces = self.pieces, pieces else: old_pieces = [] if type(indent) is int: indent = indent * ' ' if len(indent) > 0: pieces = ''.join(self.pieces) i_piece = pieces[:len(indent)] if self.pieces[-1:] == ['']: self.pieces = [pieces[len(indent):]] + [''] elif self.pieces != []: self.pieces = [pieces[len(indent):]] self.indent += len(indent) for n in node.childNodes: if restrict is not None: if n.nodeType == n.ELEMENT_NODE and n.tagName in restrict: self.parse(n) elif n.nodeType != n.ELEMENT_NODE or n.tagName not in ignore: self.parse(n) if len(indent) > 0: self.pieces = shift(self.pieces, indent, i_piece) self.indent -= len(indent) old_pieces.extend(self.pieces) self.pieces = old_pieces def surround_parse(self, node, pre_char, post_char): """Parse the subnodes of a given node. Subnodes with tags in the `ignore` list are ignored. Prepend `pre_char` and append `post_char` to the output in self.pieces.""" self.add_text(pre_char) self.subnode_parse(node) self.add_text(post_char) # MARK: Helper functions def get_specific_subnodes(self, node, name, recursive=0): """Given a node and a name, return a list of child `ELEMENT_NODEs`, that have a `tagName` matching the `name`. Search recursively for `recursive` levels. """ children = [x for x in node.childNodes if x.nodeType == x.ELEMENT_NODE] ret = [x for x in children if x.tagName == name] if recursive > 0: for x in children: ret.extend(self.get_specific_subnodes(x, name, recursive-1)) return ret def get_specific_nodes(self, node, names): """Given a node and a sequence of strings in `names`, return a dictionary containing the names as keys and child `ELEMENT_NODEs`, that have a `tagName` equal to the name. """ nodes = [(x.tagName, x) for x in node.childNodes if x.nodeType == x.ELEMENT_NODE and x.tagName in names] return dict(nodes) def add_text(self, value): """Adds text corresponding to `value` into `self.pieces`.""" if isinstance(value, (list, tuple)): self.pieces.extend(value) else: self.pieces.append(value) def add_line_with_subsequent_indent(self, line, indent=4): """Add line of text and wrap such that subsequent lines are indented by `indent` spaces. """ if isinstance(line, (list, tuple)): line = ''.join(line) line = line.strip() width = self.textwidth-self.indent-indent wrapped_lines = textwrap.wrap(line[indent:], width=width) for i in range(len(wrapped_lines)): if wrapped_lines[i] != '': wrapped_lines[i] = indent * ' ' + wrapped_lines[i] self.pieces.append(line[:indent] + '\n'.join(wrapped_lines)[indent:] + ' \n') def extract_text(self, node): """Return the string representation of the node or list of nodes by parsing the subnodes, but returning the result as a string instead of adding it to `self.pieces`. Note that this allows extracting text even if the node is in the ignore list. """ if not isinstance(node, (list, tuple)): node = [node] pieces, self.pieces = self.pieces, [''] for n in node: for sn in n.childNodes: self.parse(sn) ret = ''.join(self.pieces) self.pieces = pieces return ret def get_function_signature(self, node): """Returns the function signature string for memberdef nodes.""" name = self.extract_text(self.get_specific_subnodes(node, 'name')) if self.with_type_info: argsstring = self.extract_text(self.get_specific_subnodes(node, 'argsstring')) else: argsstring = [] param_id = 1 for n_param in self.get_specific_subnodes(node, 'param'): declname = self.extract_text(self.get_specific_subnodes(n_param, 'declname')) if not declname: declname = 'arg' + str(param_id) defval = self.extract_text(self.get_specific_subnodes(n_param, 'defval')) if defval: defval = '=' + defval argsstring.append(declname + defval) param_id = param_id + 1 argsstring = '(' + ', '.join(argsstring) + ')' type = self.extract_text(self.get_specific_subnodes(node, 'type')) function_definition = name + argsstring if type != '' and type != 'void': function_definition = function_definition + ' -> ' + type return '`' + function_definition + '` ' # MARK: Special parsing tasks (need to be called manually) def make_constructor_list(self, constructor_nodes, classname): """Produces the "Constructors" section and the constructor signatures (since swig does not do so for classes) for class docstrings.""" if constructor_nodes == []: return self.add_text(['\n', 'Constructors', '\n', '------------']) for n in constructor_nodes: self.add_text('\n') self.add_line_with_subsequent_indent('* ' + self.get_function_signature(n)) self.subnode_parse(n, pieces = [], indent=4, ignore=['definition', 'name']) def make_attribute_list(self, node): """Produces the "Attributes" section in class docstrings for public member variables (attributes). """ atr_nodes = [] for n in self.get_specific_subnodes(node, 'memberdef', recursive=2): if n.attributes['kind'].value == 'variable' and n.attributes['prot'].value == 'public': atr_nodes.append(n) if not atr_nodes: return self.add_text(['\n', 'Attributes', '\n', '----------']) for n in atr_nodes: name = self.extract_text(self.get_specific_subnodes(n, 'name')) self.add_text(['\n* ', '`', name, '`', ' : ']) self.add_text(['`', self.extract_text(self.get_specific_subnodes(n, 'type')), '`']) self.add_text(' \n') restrict = ['briefdescription', 'detaileddescription'] self.subnode_parse(n, pieces=[''], indent=4, restrict=restrict) def get_memberdef_nodes_and_signatures(self, node, kind): """Collects the memberdef nodes and corresponding signatures that correspond to public function entries that are at most depth 2 deeper than the current (compounddef) node. Returns a dictionary with function signatures (what swig expects after the %feature directive) as keys, and a list of corresponding memberdef nodes as values.""" sig_dict = {} sig_prefix = '' if kind in ('file', 'namespace'): ns_node = node.getElementsByTagName('innernamespace') if not ns_node and kind == 'namespace': ns_node = node.getElementsByTagName('compoundname') if ns_node: sig_prefix = self.extract_text(ns_node[0]) + '::' elif kind in ('class', 'struct'): # Get the full function name. cn_node = node.getElementsByTagName('compoundname') sig_prefix = self.extract_text(cn_node[0]) + '::' md_nodes = self.get_specific_subnodes(node, 'memberdef', recursive=2) for n in md_nodes: if n.attributes['prot'].value != 'public': continue if n.attributes['kind'].value in ['variable', 'typedef']: continue if not self.get_specific_subnodes(n, 'definition'): continue name = self.extract_text(self.get_specific_subnodes(n, 'name')) if name[:8] == 'operator': continue sig = sig_prefix + name if sig in sig_dict: sig_dict[sig].append(n) else: sig_dict[sig] = [n] return sig_dict def handle_typical_memberdefs_no_overload(self, signature, memberdef_nodes): """Produce standard documentation for memberdef_nodes.""" for n in memberdef_nodes: self.add_text(['\n', '%feature("docstring") ', signature, ' "', '\n']) if self.with_function_signature: self.add_line_with_subsequent_indent(self.get_function_signature(n)) self.subnode_parse(n, pieces=[], ignore=['definition', 'name']) self.add_text(['";', '\n']) def handle_typical_memberdefs(self, signature, memberdef_nodes): """Produces docstring entries containing an "Overloaded function" section with the documentation for each overload, if the function is overloaded and self.with_overloaded_functions is set. Else, produce normal documentation. """ if len(memberdef_nodes) == 1 or not self.with_overloaded_functions: self.handle_typical_memberdefs_no_overload(signature, memberdef_nodes) return self.add_text(['\n', '%feature("docstring") ', signature, ' "', '\n']) if self.with_function_signature: for n in memberdef_nodes: self.add_line_with_subsequent_indent(self.get_function_signature(n)) self.add_text('\n') self.add_text(['Overloaded function', '\n', '-------------------']) for n in memberdef_nodes: self.add_text('\n') self.add_line_with_subsequent_indent('* ' + self.get_function_signature(n)) self.subnode_parse(n, pieces=[], indent=4, ignore=['definition', 'name']) self.add_text(['";', '\n']) # MARK: Tag handlers def do_linebreak(self, node): self.add_text(' ') def do_ndash(self, node): self.add_text('--') def do_mdash(self, node): self.add_text('---') def do_emphasis(self, node): self.surround_parse(node, '*', '*') def do_bold(self, node): self.surround_parse(node, '**', '**') def do_computeroutput(self, node): self.surround_parse(node, '`', '`') def do_heading(self, node): self.start_new_paragraph() pieces, self.pieces = self.pieces, [''] level = int(node.attributes['level'].value) self.subnode_parse(node) if level == 1: self.pieces.insert(0, '\n') self.add_text(['\n', len(''.join(self.pieces).strip()) * '=']) elif level == 2: self.add_text(['\n', len(''.join(self.pieces).strip()) * '-']) elif level >= 3: self.pieces.insert(0, level * '#' + ' ') # make following text have no gap to the heading: pieces.extend([''.join(self.pieces) + ' \n', '']) self.pieces = pieces def do_verbatim(self, node): self.start_new_paragraph() self.subnode_parse(node, pieces=[''], indent=4) def do_blockquote(self, node): self.start_new_paragraph() self.subnode_parse(node, pieces=[''], indent='> ') def do_hruler(self, node): self.start_new_paragraph() self.add_text('* * * * * \n') def do_includes(self, node): self.add_text('\nC++ includes: ') self.subnode_parse(node) self.add_text('\n') # MARK: Para tag handler def do_para(self, node): """This is the only place where text wrapping is automatically performed. Generally, this function parses the node (locally), wraps the text, and then adds the result to self.pieces. However, it may be convenient to allow the previous content of self.pieces to be included in the text wrapping. For this, use the following *convention*: If self.pieces ends with '', treat the _previous_ entry as part of the current paragraph. Else, insert new-line and start a new paragraph and "wrapping context". Paragraphs always end with ' \n', but if the parsed content ends with the special symbol '', this is passed on. """ if self.pieces[-1:] == ['']: pieces, self.pieces = self.pieces[:-2], self.pieces[-2:-1] else: self.add_text('\n') pieces, self.pieces = self.pieces, [''] self.subnode_parse(node) dont_end_paragraph = self.pieces[-1:] == [''] # Now do the text wrapping: width = self.textwidth - self.indent wrapped_para = [] for line in ''.join(self.pieces).splitlines(): keep_markdown_newline = line[-2:] == ' ' w_line = textwrap.wrap(line, width=width, break_long_words=False) if w_line == []: w_line = [''] if keep_markdown_newline: w_line[-1] = w_line[-1] + ' ' for wl in w_line: wrapped_para.append(wl + '\n') if wrapped_para: if wrapped_para[-1][-3:] != ' \n': wrapped_para[-1] = wrapped_para[-1][:-1] + ' \n' if dont_end_paragraph: wrapped_para.append('') pieces.extend(wrapped_para) self.pieces = pieces # MARK: List tag handlers def do_itemizedlist(self, node): if self.listitem == '': self.start_new_paragraph() elif self.pieces != [] and self.pieces[-1:] != ['']: self.add_text('\n') listitem = self.listitem if self.listitem in ['*', '-']: self.listitem = '-' else: self.listitem = '*' self.subnode_parse(node) self.listitem = listitem def do_orderedlist(self, node): if self.listitem == '': self.start_new_paragraph() elif self.pieces != [] and self.pieces[-1:] != ['']: self.add_text('\n') listitem = self.listitem self.listitem = 0 self.subnode_parse(node) self.listitem = listitem def do_listitem(self, node): try: self.listitem = int(self.listitem) + 1 item = str(self.listitem) + '. ' except: item = str(self.listitem) + ' ' self.subnode_parse(node, item, indent=4) # MARK: Parameter list tag handlers def do_parameterlist(self, node): self.start_new_paragraph() text = 'unknown' for key, val in node.attributes.items(): if key == 'kind': if val == 'param': text = 'Parameters' elif val == 'exception': text = 'Exceptions' elif val == 'retval': text = 'Returns' else: text = val break if self.indent == 0: self.add_text([text, '\n', len(text) * '-', '\n']) else: self.add_text([text, ': \n']) self.subnode_parse(node) def do_parameteritem(self, node): self.subnode_parse(node, pieces=['* ', '']) def do_parameternamelist(self, node): self.subnode_parse(node) self.add_text([' :', ' \n']) def do_parametername(self, node): if self.pieces != [] and self.pieces != ['* ', '']: self.add_text(', ') data = self.extract_text(node) self.add_text(['`', data, '`']) def do_parameterdescription(self, node): self.subnode_parse(node, pieces=[''], indent=4) # MARK: Section tag handler def do_simplesect(self, node): kind = node.attributes['kind'].value if kind in ('date', 'rcs', 'version'): return self.start_new_paragraph() if kind == 'warning': self.subnode_parse(node, pieces=['**Warning**: ',''], indent=4) elif kind == 'see': self.subnode_parse(node, pieces=['See also: ',''], indent=4) elif kind == 'return': if self.indent == 0: pieces = ['Returns', '\n', len('Returns') * '-', '\n', ''] else: pieces = ['Returns:', '\n', ''] self.subnode_parse(node, pieces=pieces) else: self.subnode_parse(node, pieces=[kind + ': ',''], indent=4) # MARK: %feature("docstring") producing tag handlers def do_compounddef(self, node): """This produces %feature("docstring") entries for classes, and handles class, namespace and file memberdef entries specially to allow for overloaded functions. For other cases, passes parsing on to standard handlers (which may produce unexpected results). """ kind = node.attributes['kind'].value if kind in ('class', 'struct'): prot = node.attributes['prot'].value if prot != 'public': return self.add_text('\n\n') classdefn = self.extract_text(self.get_specific_subnodes(node, 'compoundname')) classname = classdefn.split('::')[-1] self.add_text('%%feature("docstring") %s "\n' % classdefn) if self.with_constructor_list: constructor_nodes = [] for n in self.get_specific_subnodes(node, 'memberdef', recursive=2): if n.attributes['prot'].value == 'public': if self.extract_text(self.get_specific_subnodes(n, 'definition')) == classdefn + '::' + classname: constructor_nodes.append(n) for n in constructor_nodes: self.add_line_with_subsequent_indent(self.get_function_signature(n)) names = ('briefdescription','detaileddescription') sub_dict = self.get_specific_nodes(node, names) for n in ('briefdescription','detaileddescription'): if n in sub_dict: self.parse(sub_dict[n]) if self.with_constructor_list: self.make_constructor_list(constructor_nodes, classname) if self.with_attribute_list: self.make_attribute_list(node) sub_list = self.get_specific_subnodes(node, 'includes') if sub_list: self.parse(sub_list[0]) self.add_text(['";', '\n']) names = ['compoundname', 'briefdescription','detaileddescription', 'includes'] self.subnode_parse(node, ignore = names) elif kind in ('file', 'namespace'): nodes = node.getElementsByTagName('sectiondef') for n in nodes: self.parse(n) # now explicitely handle possibly overloaded member functions. if kind in ['class', 'struct','file', 'namespace']: md_nodes = self.get_memberdef_nodes_and_signatures(node, kind) for sig in md_nodes: self.handle_typical_memberdefs(sig, md_nodes[sig]) def do_memberdef(self, node): """Handle cases outside of class, struct, file or namespace. These are now dealt with by `handle_overloaded_memberfunction`. Do these even exist??? """ prot = node.attributes['prot'].value id = node.attributes['id'].value kind = node.attributes['kind'].value tmp = node.parentNode.parentNode.parentNode compdef = tmp.getElementsByTagName('compounddef')[0] cdef_kind = compdef.attributes['kind'].value if cdef_kind in ('file', 'namespace', 'class', 'struct'): # These cases are now handled by `handle_typical_memberdefs` return if prot != 'public': return first = self.get_specific_nodes(node, ('definition', 'name')) name = self.extract_text(first['name']) if name[:8] == 'operator': # Don't handle operators yet. return if not 'definition' in first or kind in ['variable', 'typedef']: return data = self.extract_text(first['definition']) self.add_text('\n') self.add_text(['/* where did this entry come from??? */', '\n']) self.add_text('%feature("docstring") %s "\n%s' % (data, data)) for n in node.childNodes: if n not in first.values(): self.parse(n) self.add_text(['";', '\n']) # MARK: Entry tag handlers (dont print anything meaningful) def do_sectiondef(self, node): kind = node.attributes['kind'].value if kind in ('public-func', 'func', 'user-defined', ''): self.subnode_parse(node) def do_header(self, node): """For a user defined section def a header field is present which should not be printed as such, so we comment it in the output.""" data = self.extract_text(node) self.add_text('\n/*\n %s \n*/\n' % data) # If our immediate sibling is a 'description' node then we # should comment that out also and remove it from the parent # node's children. parent = node.parentNode idx = parent.childNodes.index(node) if len(parent.childNodes) >= idx + 2: nd = parent.childNodes[idx + 2] if nd.nodeName == 'description': nd = parent.removeChild(nd) self.add_text('\n/*') self.subnode_parse(nd) self.add_text('\n*/\n') def do_member(self, node): kind = node.attributes['kind'].value refid = node.attributes['refid'].value if kind == 'function' and refid[:9] == 'namespace': self.subnode_parse(node) def do_doxygenindex(self, node): self.multi = 1 comps = node.getElementsByTagName('compound') for c in comps: refid = c.attributes['refid'].value fname = refid + '.xml' if not os.path.exists(fname): fname = os.path.join(self.my_dir, fname) if not self.quiet: print("parsing file: %s" % fname) p = Doxy2SWIG(fname, with_function_signature = self.with_function_signature, with_type_info = self.with_type_info, with_constructor_list = self.with_constructor_list, with_attribute_list = self.with_attribute_list, with_overloaded_functions = self.with_overloaded_functions, textwidth = self.textwidth, quiet = self.quiet) p.generate() self.pieces.extend(p.pieces)
basler/pypylon
scripts/builddoxy2swig/doxy2swig/doxy2swig.py
Doxy2SWIG.add_line_with_subsequent_indent
python
def add_line_with_subsequent_indent(self, line, indent=4): if isinstance(line, (list, tuple)): line = ''.join(line) line = line.strip() width = self.textwidth-self.indent-indent wrapped_lines = textwrap.wrap(line[indent:], width=width) for i in range(len(wrapped_lines)): if wrapped_lines[i] != '': wrapped_lines[i] = indent * ' ' + wrapped_lines[i] self.pieces.append(line[:indent] + '\n'.join(wrapped_lines)[indent:] + ' \n')
Add line of text and wrap such that subsequent lines are indented by `indent` spaces.
train
https://github.com/basler/pypylon/blob/d3510fa419b1c2b17f3f0b80a5fbb720c7b84008/scripts/builddoxy2swig/doxy2swig/doxy2swig.py#L308-L320
null
class Doxy2SWIG: """Converts Doxygen generated XML files into a file containing docstrings that can be used by SWIG-1.3.x that have support for feature("docstring"). Once the data is parsed it is stored in self.pieces. """ def __init__(self, src, with_function_signature = False, with_type_info = False, with_constructor_list = False, with_attribute_list = False, with_overloaded_functions = False, textwidth = 80, quiet = False): """Initialize the instance given a source object. `src` can be a file or filename. If you do not want to include function definitions from doxygen then set `include_function_definition` to `False`. This is handy since this allows you to use the swig generated function definition using %feature("autodoc", [0,1]). """ # options: self.with_function_signature = with_function_signature self.with_type_info = with_type_info self.with_constructor_list = with_constructor_list self.with_attribute_list = with_attribute_list self.with_overloaded_functions = with_overloaded_functions self.textwidth = textwidth self.quiet = quiet # state: self.indent = 0 self.listitem = '' self.pieces = [] f = my_open_read(src) self.my_dir = os.path.dirname(f.name) self.xmldoc = minidom.parse(f).documentElement f.close() self.pieces.append('\n// File: %s\n' % os.path.basename(f.name)) self.space_re = re.compile(r'\s+') self.lead_spc = re.compile(r'^(%feature\S+\s+\S+\s*?)"\s+(\S)') self.multi = 0 self.ignores = ['inheritancegraph', 'param', 'listofallmembers', 'innerclass', 'name', 'declname', 'incdepgraph', 'invincdepgraph', 'programlisting', 'type', 'references', 'referencedby', 'location', 'collaborationgraph', 'reimplements', 'reimplementedby', 'derivedcompoundref', 'basecompoundref', 'argsstring', 'definition', 'exceptions'] #self.generics = [] def generate(self): """Parses the file set in the initialization. The resulting data is stored in `self.pieces`. """ self.parse(self.xmldoc) def write(self, fname): o = my_open_write(fname) o.write(''.join(self.pieces)) o.write('\n') o.close() def parse(self, node): """Parse a given node. This function in turn calls the `parse_<nodeType>` functions which handle the respective nodes. """ pm = getattr(self, "parse_%s" % node.__class__.__name__) pm(node) def parse_Document(self, node): self.parse(node.documentElement) def parse_Text(self, node): txt = node.data if txt == ' ': # this can happen when two tags follow in a text, e.g., # " ...</emph> <formaula>$..." etc. # here we want to keep the space. self.add_text(txt) return txt = txt.replace('\\', r'\\') txt = txt.replace('"', r'\"') # ignore pure whitespace m = self.space_re.match(txt) if m and len(m.group()) == len(txt): pass else: self.add_text(txt) def parse_Comment(self, node): """Parse a `COMMENT_NODE`. This does nothing for now.""" return def parse_Element(self, node): """Parse an `ELEMENT_NODE`. This calls specific `do_<tagName>` handers for different elements. If no handler is available the `subnode_parse` method is called. All tagNames specified in `self.ignores` are simply ignored. """ name = node.tagName ignores = self.ignores if name in ignores: return attr = "do_%s" % name if hasattr(self, attr): handlerMethod = getattr(self, attr) handlerMethod(node) else: self.subnode_parse(node) #if name not in self.generics: self.generics.append(name) # MARK: Special format parsing def subnode_parse(self, node, pieces=None, indent=0, ignore=[], restrict=None): """Parse the subnodes of a given node. Subnodes with tags in the `ignore` list are ignored. If pieces is given, use this as target for the parse results instead of self.pieces. Indent all lines by the amount given in `indent`. Note that the initial content in `pieces` is not indented. The final result is in any case added to self.pieces.""" if pieces is not None: old_pieces, self.pieces = self.pieces, pieces else: old_pieces = [] if type(indent) is int: indent = indent * ' ' if len(indent) > 0: pieces = ''.join(self.pieces) i_piece = pieces[:len(indent)] if self.pieces[-1:] == ['']: self.pieces = [pieces[len(indent):]] + [''] elif self.pieces != []: self.pieces = [pieces[len(indent):]] self.indent += len(indent) for n in node.childNodes: if restrict is not None: if n.nodeType == n.ELEMENT_NODE and n.tagName in restrict: self.parse(n) elif n.nodeType != n.ELEMENT_NODE or n.tagName not in ignore: self.parse(n) if len(indent) > 0: self.pieces = shift(self.pieces, indent, i_piece) self.indent -= len(indent) old_pieces.extend(self.pieces) self.pieces = old_pieces def surround_parse(self, node, pre_char, post_char): """Parse the subnodes of a given node. Subnodes with tags in the `ignore` list are ignored. Prepend `pre_char` and append `post_char` to the output in self.pieces.""" self.add_text(pre_char) self.subnode_parse(node) self.add_text(post_char) # MARK: Helper functions def get_specific_subnodes(self, node, name, recursive=0): """Given a node and a name, return a list of child `ELEMENT_NODEs`, that have a `tagName` matching the `name`. Search recursively for `recursive` levels. """ children = [x for x in node.childNodes if x.nodeType == x.ELEMENT_NODE] ret = [x for x in children if x.tagName == name] if recursive > 0: for x in children: ret.extend(self.get_specific_subnodes(x, name, recursive-1)) return ret def get_specific_nodes(self, node, names): """Given a node and a sequence of strings in `names`, return a dictionary containing the names as keys and child `ELEMENT_NODEs`, that have a `tagName` equal to the name. """ nodes = [(x.tagName, x) for x in node.childNodes if x.nodeType == x.ELEMENT_NODE and x.tagName in names] return dict(nodes) def add_text(self, value): """Adds text corresponding to `value` into `self.pieces`.""" if isinstance(value, (list, tuple)): self.pieces.extend(value) else: self.pieces.append(value) def start_new_paragraph(self): """Make sure to create an empty line. This is overridden, if the previous text ends with the special marker ''. In that case, nothing is done. """ if self.pieces[-1:] == ['']: # respect special marker return elif self.pieces == []: # first paragraph, add '\n', override with '' self.pieces = ['\n'] elif self.pieces[-1][-1:] != '\n': # previous line not ended self.pieces.extend([' \n' ,'\n']) else: #default self.pieces.append('\n') def extract_text(self, node): """Return the string representation of the node or list of nodes by parsing the subnodes, but returning the result as a string instead of adding it to `self.pieces`. Note that this allows extracting text even if the node is in the ignore list. """ if not isinstance(node, (list, tuple)): node = [node] pieces, self.pieces = self.pieces, [''] for n in node: for sn in n.childNodes: self.parse(sn) ret = ''.join(self.pieces) self.pieces = pieces return ret def get_function_signature(self, node): """Returns the function signature string for memberdef nodes.""" name = self.extract_text(self.get_specific_subnodes(node, 'name')) if self.with_type_info: argsstring = self.extract_text(self.get_specific_subnodes(node, 'argsstring')) else: argsstring = [] param_id = 1 for n_param in self.get_specific_subnodes(node, 'param'): declname = self.extract_text(self.get_specific_subnodes(n_param, 'declname')) if not declname: declname = 'arg' + str(param_id) defval = self.extract_text(self.get_specific_subnodes(n_param, 'defval')) if defval: defval = '=' + defval argsstring.append(declname + defval) param_id = param_id + 1 argsstring = '(' + ', '.join(argsstring) + ')' type = self.extract_text(self.get_specific_subnodes(node, 'type')) function_definition = name + argsstring if type != '' and type != 'void': function_definition = function_definition + ' -> ' + type return '`' + function_definition + '` ' # MARK: Special parsing tasks (need to be called manually) def make_constructor_list(self, constructor_nodes, classname): """Produces the "Constructors" section and the constructor signatures (since swig does not do so for classes) for class docstrings.""" if constructor_nodes == []: return self.add_text(['\n', 'Constructors', '\n', '------------']) for n in constructor_nodes: self.add_text('\n') self.add_line_with_subsequent_indent('* ' + self.get_function_signature(n)) self.subnode_parse(n, pieces = [], indent=4, ignore=['definition', 'name']) def make_attribute_list(self, node): """Produces the "Attributes" section in class docstrings for public member variables (attributes). """ atr_nodes = [] for n in self.get_specific_subnodes(node, 'memberdef', recursive=2): if n.attributes['kind'].value == 'variable' and n.attributes['prot'].value == 'public': atr_nodes.append(n) if not atr_nodes: return self.add_text(['\n', 'Attributes', '\n', '----------']) for n in atr_nodes: name = self.extract_text(self.get_specific_subnodes(n, 'name')) self.add_text(['\n* ', '`', name, '`', ' : ']) self.add_text(['`', self.extract_text(self.get_specific_subnodes(n, 'type')), '`']) self.add_text(' \n') restrict = ['briefdescription', 'detaileddescription'] self.subnode_parse(n, pieces=[''], indent=4, restrict=restrict) def get_memberdef_nodes_and_signatures(self, node, kind): """Collects the memberdef nodes and corresponding signatures that correspond to public function entries that are at most depth 2 deeper than the current (compounddef) node. Returns a dictionary with function signatures (what swig expects after the %feature directive) as keys, and a list of corresponding memberdef nodes as values.""" sig_dict = {} sig_prefix = '' if kind in ('file', 'namespace'): ns_node = node.getElementsByTagName('innernamespace') if not ns_node and kind == 'namespace': ns_node = node.getElementsByTagName('compoundname') if ns_node: sig_prefix = self.extract_text(ns_node[0]) + '::' elif kind in ('class', 'struct'): # Get the full function name. cn_node = node.getElementsByTagName('compoundname') sig_prefix = self.extract_text(cn_node[0]) + '::' md_nodes = self.get_specific_subnodes(node, 'memberdef', recursive=2) for n in md_nodes: if n.attributes['prot'].value != 'public': continue if n.attributes['kind'].value in ['variable', 'typedef']: continue if not self.get_specific_subnodes(n, 'definition'): continue name = self.extract_text(self.get_specific_subnodes(n, 'name')) if name[:8] == 'operator': continue sig = sig_prefix + name if sig in sig_dict: sig_dict[sig].append(n) else: sig_dict[sig] = [n] return sig_dict def handle_typical_memberdefs_no_overload(self, signature, memberdef_nodes): """Produce standard documentation for memberdef_nodes.""" for n in memberdef_nodes: self.add_text(['\n', '%feature("docstring") ', signature, ' "', '\n']) if self.with_function_signature: self.add_line_with_subsequent_indent(self.get_function_signature(n)) self.subnode_parse(n, pieces=[], ignore=['definition', 'name']) self.add_text(['";', '\n']) def handle_typical_memberdefs(self, signature, memberdef_nodes): """Produces docstring entries containing an "Overloaded function" section with the documentation for each overload, if the function is overloaded and self.with_overloaded_functions is set. Else, produce normal documentation. """ if len(memberdef_nodes) == 1 or not self.with_overloaded_functions: self.handle_typical_memberdefs_no_overload(signature, memberdef_nodes) return self.add_text(['\n', '%feature("docstring") ', signature, ' "', '\n']) if self.with_function_signature: for n in memberdef_nodes: self.add_line_with_subsequent_indent(self.get_function_signature(n)) self.add_text('\n') self.add_text(['Overloaded function', '\n', '-------------------']) for n in memberdef_nodes: self.add_text('\n') self.add_line_with_subsequent_indent('* ' + self.get_function_signature(n)) self.subnode_parse(n, pieces=[], indent=4, ignore=['definition', 'name']) self.add_text(['";', '\n']) # MARK: Tag handlers def do_linebreak(self, node): self.add_text(' ') def do_ndash(self, node): self.add_text('--') def do_mdash(self, node): self.add_text('---') def do_emphasis(self, node): self.surround_parse(node, '*', '*') def do_bold(self, node): self.surround_parse(node, '**', '**') def do_computeroutput(self, node): self.surround_parse(node, '`', '`') def do_heading(self, node): self.start_new_paragraph() pieces, self.pieces = self.pieces, [''] level = int(node.attributes['level'].value) self.subnode_parse(node) if level == 1: self.pieces.insert(0, '\n') self.add_text(['\n', len(''.join(self.pieces).strip()) * '=']) elif level == 2: self.add_text(['\n', len(''.join(self.pieces).strip()) * '-']) elif level >= 3: self.pieces.insert(0, level * '#' + ' ') # make following text have no gap to the heading: pieces.extend([''.join(self.pieces) + ' \n', '']) self.pieces = pieces def do_verbatim(self, node): self.start_new_paragraph() self.subnode_parse(node, pieces=[''], indent=4) def do_blockquote(self, node): self.start_new_paragraph() self.subnode_parse(node, pieces=[''], indent='> ') def do_hruler(self, node): self.start_new_paragraph() self.add_text('* * * * * \n') def do_includes(self, node): self.add_text('\nC++ includes: ') self.subnode_parse(node) self.add_text('\n') # MARK: Para tag handler def do_para(self, node): """This is the only place where text wrapping is automatically performed. Generally, this function parses the node (locally), wraps the text, and then adds the result to self.pieces. However, it may be convenient to allow the previous content of self.pieces to be included in the text wrapping. For this, use the following *convention*: If self.pieces ends with '', treat the _previous_ entry as part of the current paragraph. Else, insert new-line and start a new paragraph and "wrapping context". Paragraphs always end with ' \n', but if the parsed content ends with the special symbol '', this is passed on. """ if self.pieces[-1:] == ['']: pieces, self.pieces = self.pieces[:-2], self.pieces[-2:-1] else: self.add_text('\n') pieces, self.pieces = self.pieces, [''] self.subnode_parse(node) dont_end_paragraph = self.pieces[-1:] == [''] # Now do the text wrapping: width = self.textwidth - self.indent wrapped_para = [] for line in ''.join(self.pieces).splitlines(): keep_markdown_newline = line[-2:] == ' ' w_line = textwrap.wrap(line, width=width, break_long_words=False) if w_line == []: w_line = [''] if keep_markdown_newline: w_line[-1] = w_line[-1] + ' ' for wl in w_line: wrapped_para.append(wl + '\n') if wrapped_para: if wrapped_para[-1][-3:] != ' \n': wrapped_para[-1] = wrapped_para[-1][:-1] + ' \n' if dont_end_paragraph: wrapped_para.append('') pieces.extend(wrapped_para) self.pieces = pieces # MARK: List tag handlers def do_itemizedlist(self, node): if self.listitem == '': self.start_new_paragraph() elif self.pieces != [] and self.pieces[-1:] != ['']: self.add_text('\n') listitem = self.listitem if self.listitem in ['*', '-']: self.listitem = '-' else: self.listitem = '*' self.subnode_parse(node) self.listitem = listitem def do_orderedlist(self, node): if self.listitem == '': self.start_new_paragraph() elif self.pieces != [] and self.pieces[-1:] != ['']: self.add_text('\n') listitem = self.listitem self.listitem = 0 self.subnode_parse(node) self.listitem = listitem def do_listitem(self, node): try: self.listitem = int(self.listitem) + 1 item = str(self.listitem) + '. ' except: item = str(self.listitem) + ' ' self.subnode_parse(node, item, indent=4) # MARK: Parameter list tag handlers def do_parameterlist(self, node): self.start_new_paragraph() text = 'unknown' for key, val in node.attributes.items(): if key == 'kind': if val == 'param': text = 'Parameters' elif val == 'exception': text = 'Exceptions' elif val == 'retval': text = 'Returns' else: text = val break if self.indent == 0: self.add_text([text, '\n', len(text) * '-', '\n']) else: self.add_text([text, ': \n']) self.subnode_parse(node) def do_parameteritem(self, node): self.subnode_parse(node, pieces=['* ', '']) def do_parameternamelist(self, node): self.subnode_parse(node) self.add_text([' :', ' \n']) def do_parametername(self, node): if self.pieces != [] and self.pieces != ['* ', '']: self.add_text(', ') data = self.extract_text(node) self.add_text(['`', data, '`']) def do_parameterdescription(self, node): self.subnode_parse(node, pieces=[''], indent=4) # MARK: Section tag handler def do_simplesect(self, node): kind = node.attributes['kind'].value if kind in ('date', 'rcs', 'version'): return self.start_new_paragraph() if kind == 'warning': self.subnode_parse(node, pieces=['**Warning**: ',''], indent=4) elif kind == 'see': self.subnode_parse(node, pieces=['See also: ',''], indent=4) elif kind == 'return': if self.indent == 0: pieces = ['Returns', '\n', len('Returns') * '-', '\n', ''] else: pieces = ['Returns:', '\n', ''] self.subnode_parse(node, pieces=pieces) else: self.subnode_parse(node, pieces=[kind + ': ',''], indent=4) # MARK: %feature("docstring") producing tag handlers def do_compounddef(self, node): """This produces %feature("docstring") entries for classes, and handles class, namespace and file memberdef entries specially to allow for overloaded functions. For other cases, passes parsing on to standard handlers (which may produce unexpected results). """ kind = node.attributes['kind'].value if kind in ('class', 'struct'): prot = node.attributes['prot'].value if prot != 'public': return self.add_text('\n\n') classdefn = self.extract_text(self.get_specific_subnodes(node, 'compoundname')) classname = classdefn.split('::')[-1] self.add_text('%%feature("docstring") %s "\n' % classdefn) if self.with_constructor_list: constructor_nodes = [] for n in self.get_specific_subnodes(node, 'memberdef', recursive=2): if n.attributes['prot'].value == 'public': if self.extract_text(self.get_specific_subnodes(n, 'definition')) == classdefn + '::' + classname: constructor_nodes.append(n) for n in constructor_nodes: self.add_line_with_subsequent_indent(self.get_function_signature(n)) names = ('briefdescription','detaileddescription') sub_dict = self.get_specific_nodes(node, names) for n in ('briefdescription','detaileddescription'): if n in sub_dict: self.parse(sub_dict[n]) if self.with_constructor_list: self.make_constructor_list(constructor_nodes, classname) if self.with_attribute_list: self.make_attribute_list(node) sub_list = self.get_specific_subnodes(node, 'includes') if sub_list: self.parse(sub_list[0]) self.add_text(['";', '\n']) names = ['compoundname', 'briefdescription','detaileddescription', 'includes'] self.subnode_parse(node, ignore = names) elif kind in ('file', 'namespace'): nodes = node.getElementsByTagName('sectiondef') for n in nodes: self.parse(n) # now explicitely handle possibly overloaded member functions. if kind in ['class', 'struct','file', 'namespace']: md_nodes = self.get_memberdef_nodes_and_signatures(node, kind) for sig in md_nodes: self.handle_typical_memberdefs(sig, md_nodes[sig]) def do_memberdef(self, node): """Handle cases outside of class, struct, file or namespace. These are now dealt with by `handle_overloaded_memberfunction`. Do these even exist??? """ prot = node.attributes['prot'].value id = node.attributes['id'].value kind = node.attributes['kind'].value tmp = node.parentNode.parentNode.parentNode compdef = tmp.getElementsByTagName('compounddef')[0] cdef_kind = compdef.attributes['kind'].value if cdef_kind in ('file', 'namespace', 'class', 'struct'): # These cases are now handled by `handle_typical_memberdefs` return if prot != 'public': return first = self.get_specific_nodes(node, ('definition', 'name')) name = self.extract_text(first['name']) if name[:8] == 'operator': # Don't handle operators yet. return if not 'definition' in first or kind in ['variable', 'typedef']: return data = self.extract_text(first['definition']) self.add_text('\n') self.add_text(['/* where did this entry come from??? */', '\n']) self.add_text('%feature("docstring") %s "\n%s' % (data, data)) for n in node.childNodes: if n not in first.values(): self.parse(n) self.add_text(['";', '\n']) # MARK: Entry tag handlers (dont print anything meaningful) def do_sectiondef(self, node): kind = node.attributes['kind'].value if kind in ('public-func', 'func', 'user-defined', ''): self.subnode_parse(node) def do_header(self, node): """For a user defined section def a header field is present which should not be printed as such, so we comment it in the output.""" data = self.extract_text(node) self.add_text('\n/*\n %s \n*/\n' % data) # If our immediate sibling is a 'description' node then we # should comment that out also and remove it from the parent # node's children. parent = node.parentNode idx = parent.childNodes.index(node) if len(parent.childNodes) >= idx + 2: nd = parent.childNodes[idx + 2] if nd.nodeName == 'description': nd = parent.removeChild(nd) self.add_text('\n/*') self.subnode_parse(nd) self.add_text('\n*/\n') def do_member(self, node): kind = node.attributes['kind'].value refid = node.attributes['refid'].value if kind == 'function' and refid[:9] == 'namespace': self.subnode_parse(node) def do_doxygenindex(self, node): self.multi = 1 comps = node.getElementsByTagName('compound') for c in comps: refid = c.attributes['refid'].value fname = refid + '.xml' if not os.path.exists(fname): fname = os.path.join(self.my_dir, fname) if not self.quiet: print("parsing file: %s" % fname) p = Doxy2SWIG(fname, with_function_signature = self.with_function_signature, with_type_info = self.with_type_info, with_constructor_list = self.with_constructor_list, with_attribute_list = self.with_attribute_list, with_overloaded_functions = self.with_overloaded_functions, textwidth = self.textwidth, quiet = self.quiet) p.generate() self.pieces.extend(p.pieces)
basler/pypylon
scripts/builddoxy2swig/doxy2swig/doxy2swig.py
Doxy2SWIG.extract_text
python
def extract_text(self, node): if not isinstance(node, (list, tuple)): node = [node] pieces, self.pieces = self.pieces, [''] for n in node: for sn in n.childNodes: self.parse(sn) ret = ''.join(self.pieces) self.pieces = pieces return ret
Return the string representation of the node or list of nodes by parsing the subnodes, but returning the result as a string instead of adding it to `self.pieces`. Note that this allows extracting text even if the node is in the ignore list.
train
https://github.com/basler/pypylon/blob/d3510fa419b1c2b17f3f0b80a5fbb720c7b84008/scripts/builddoxy2swig/doxy2swig/doxy2swig.py#L322-L335
[ "def parse(self, node):\n \"\"\"Parse a given node. This function in turn calls the\n `parse_<nodeType>` functions which handle the respective\n nodes.\n\n \"\"\"\n pm = getattr(self, \"parse_%s\" % node.__class__.__name__)\n pm(node)\n" ]
class Doxy2SWIG: """Converts Doxygen generated XML files into a file containing docstrings that can be used by SWIG-1.3.x that have support for feature("docstring"). Once the data is parsed it is stored in self.pieces. """ def __init__(self, src, with_function_signature = False, with_type_info = False, with_constructor_list = False, with_attribute_list = False, with_overloaded_functions = False, textwidth = 80, quiet = False): """Initialize the instance given a source object. `src` can be a file or filename. If you do not want to include function definitions from doxygen then set `include_function_definition` to `False`. This is handy since this allows you to use the swig generated function definition using %feature("autodoc", [0,1]). """ # options: self.with_function_signature = with_function_signature self.with_type_info = with_type_info self.with_constructor_list = with_constructor_list self.with_attribute_list = with_attribute_list self.with_overloaded_functions = with_overloaded_functions self.textwidth = textwidth self.quiet = quiet # state: self.indent = 0 self.listitem = '' self.pieces = [] f = my_open_read(src) self.my_dir = os.path.dirname(f.name) self.xmldoc = minidom.parse(f).documentElement f.close() self.pieces.append('\n// File: %s\n' % os.path.basename(f.name)) self.space_re = re.compile(r'\s+') self.lead_spc = re.compile(r'^(%feature\S+\s+\S+\s*?)"\s+(\S)') self.multi = 0 self.ignores = ['inheritancegraph', 'param', 'listofallmembers', 'innerclass', 'name', 'declname', 'incdepgraph', 'invincdepgraph', 'programlisting', 'type', 'references', 'referencedby', 'location', 'collaborationgraph', 'reimplements', 'reimplementedby', 'derivedcompoundref', 'basecompoundref', 'argsstring', 'definition', 'exceptions'] #self.generics = [] def generate(self): """Parses the file set in the initialization. The resulting data is stored in `self.pieces`. """ self.parse(self.xmldoc) def write(self, fname): o = my_open_write(fname) o.write(''.join(self.pieces)) o.write('\n') o.close() def parse(self, node): """Parse a given node. This function in turn calls the `parse_<nodeType>` functions which handle the respective nodes. """ pm = getattr(self, "parse_%s" % node.__class__.__name__) pm(node) def parse_Document(self, node): self.parse(node.documentElement) def parse_Text(self, node): txt = node.data if txt == ' ': # this can happen when two tags follow in a text, e.g., # " ...</emph> <formaula>$..." etc. # here we want to keep the space. self.add_text(txt) return txt = txt.replace('\\', r'\\') txt = txt.replace('"', r'\"') # ignore pure whitespace m = self.space_re.match(txt) if m and len(m.group()) == len(txt): pass else: self.add_text(txt) def parse_Comment(self, node): """Parse a `COMMENT_NODE`. This does nothing for now.""" return def parse_Element(self, node): """Parse an `ELEMENT_NODE`. This calls specific `do_<tagName>` handers for different elements. If no handler is available the `subnode_parse` method is called. All tagNames specified in `self.ignores` are simply ignored. """ name = node.tagName ignores = self.ignores if name in ignores: return attr = "do_%s" % name if hasattr(self, attr): handlerMethod = getattr(self, attr) handlerMethod(node) else: self.subnode_parse(node) #if name not in self.generics: self.generics.append(name) # MARK: Special format parsing def subnode_parse(self, node, pieces=None, indent=0, ignore=[], restrict=None): """Parse the subnodes of a given node. Subnodes with tags in the `ignore` list are ignored. If pieces is given, use this as target for the parse results instead of self.pieces. Indent all lines by the amount given in `indent`. Note that the initial content in `pieces` is not indented. The final result is in any case added to self.pieces.""" if pieces is not None: old_pieces, self.pieces = self.pieces, pieces else: old_pieces = [] if type(indent) is int: indent = indent * ' ' if len(indent) > 0: pieces = ''.join(self.pieces) i_piece = pieces[:len(indent)] if self.pieces[-1:] == ['']: self.pieces = [pieces[len(indent):]] + [''] elif self.pieces != []: self.pieces = [pieces[len(indent):]] self.indent += len(indent) for n in node.childNodes: if restrict is not None: if n.nodeType == n.ELEMENT_NODE and n.tagName in restrict: self.parse(n) elif n.nodeType != n.ELEMENT_NODE or n.tagName not in ignore: self.parse(n) if len(indent) > 0: self.pieces = shift(self.pieces, indent, i_piece) self.indent -= len(indent) old_pieces.extend(self.pieces) self.pieces = old_pieces def surround_parse(self, node, pre_char, post_char): """Parse the subnodes of a given node. Subnodes with tags in the `ignore` list are ignored. Prepend `pre_char` and append `post_char` to the output in self.pieces.""" self.add_text(pre_char) self.subnode_parse(node) self.add_text(post_char) # MARK: Helper functions def get_specific_subnodes(self, node, name, recursive=0): """Given a node and a name, return a list of child `ELEMENT_NODEs`, that have a `tagName` matching the `name`. Search recursively for `recursive` levels. """ children = [x for x in node.childNodes if x.nodeType == x.ELEMENT_NODE] ret = [x for x in children if x.tagName == name] if recursive > 0: for x in children: ret.extend(self.get_specific_subnodes(x, name, recursive-1)) return ret def get_specific_nodes(self, node, names): """Given a node and a sequence of strings in `names`, return a dictionary containing the names as keys and child `ELEMENT_NODEs`, that have a `tagName` equal to the name. """ nodes = [(x.tagName, x) for x in node.childNodes if x.nodeType == x.ELEMENT_NODE and x.tagName in names] return dict(nodes) def add_text(self, value): """Adds text corresponding to `value` into `self.pieces`.""" if isinstance(value, (list, tuple)): self.pieces.extend(value) else: self.pieces.append(value) def start_new_paragraph(self): """Make sure to create an empty line. This is overridden, if the previous text ends with the special marker ''. In that case, nothing is done. """ if self.pieces[-1:] == ['']: # respect special marker return elif self.pieces == []: # first paragraph, add '\n', override with '' self.pieces = ['\n'] elif self.pieces[-1][-1:] != '\n': # previous line not ended self.pieces.extend([' \n' ,'\n']) else: #default self.pieces.append('\n') def add_line_with_subsequent_indent(self, line, indent=4): """Add line of text and wrap such that subsequent lines are indented by `indent` spaces. """ if isinstance(line, (list, tuple)): line = ''.join(line) line = line.strip() width = self.textwidth-self.indent-indent wrapped_lines = textwrap.wrap(line[indent:], width=width) for i in range(len(wrapped_lines)): if wrapped_lines[i] != '': wrapped_lines[i] = indent * ' ' + wrapped_lines[i] self.pieces.append(line[:indent] + '\n'.join(wrapped_lines)[indent:] + ' \n') def get_function_signature(self, node): """Returns the function signature string for memberdef nodes.""" name = self.extract_text(self.get_specific_subnodes(node, 'name')) if self.with_type_info: argsstring = self.extract_text(self.get_specific_subnodes(node, 'argsstring')) else: argsstring = [] param_id = 1 for n_param in self.get_specific_subnodes(node, 'param'): declname = self.extract_text(self.get_specific_subnodes(n_param, 'declname')) if not declname: declname = 'arg' + str(param_id) defval = self.extract_text(self.get_specific_subnodes(n_param, 'defval')) if defval: defval = '=' + defval argsstring.append(declname + defval) param_id = param_id + 1 argsstring = '(' + ', '.join(argsstring) + ')' type = self.extract_text(self.get_specific_subnodes(node, 'type')) function_definition = name + argsstring if type != '' and type != 'void': function_definition = function_definition + ' -> ' + type return '`' + function_definition + '` ' # MARK: Special parsing tasks (need to be called manually) def make_constructor_list(self, constructor_nodes, classname): """Produces the "Constructors" section and the constructor signatures (since swig does not do so for classes) for class docstrings.""" if constructor_nodes == []: return self.add_text(['\n', 'Constructors', '\n', '------------']) for n in constructor_nodes: self.add_text('\n') self.add_line_with_subsequent_indent('* ' + self.get_function_signature(n)) self.subnode_parse(n, pieces = [], indent=4, ignore=['definition', 'name']) def make_attribute_list(self, node): """Produces the "Attributes" section in class docstrings for public member variables (attributes). """ atr_nodes = [] for n in self.get_specific_subnodes(node, 'memberdef', recursive=2): if n.attributes['kind'].value == 'variable' and n.attributes['prot'].value == 'public': atr_nodes.append(n) if not atr_nodes: return self.add_text(['\n', 'Attributes', '\n', '----------']) for n in atr_nodes: name = self.extract_text(self.get_specific_subnodes(n, 'name')) self.add_text(['\n* ', '`', name, '`', ' : ']) self.add_text(['`', self.extract_text(self.get_specific_subnodes(n, 'type')), '`']) self.add_text(' \n') restrict = ['briefdescription', 'detaileddescription'] self.subnode_parse(n, pieces=[''], indent=4, restrict=restrict) def get_memberdef_nodes_and_signatures(self, node, kind): """Collects the memberdef nodes and corresponding signatures that correspond to public function entries that are at most depth 2 deeper than the current (compounddef) node. Returns a dictionary with function signatures (what swig expects after the %feature directive) as keys, and a list of corresponding memberdef nodes as values.""" sig_dict = {} sig_prefix = '' if kind in ('file', 'namespace'): ns_node = node.getElementsByTagName('innernamespace') if not ns_node and kind == 'namespace': ns_node = node.getElementsByTagName('compoundname') if ns_node: sig_prefix = self.extract_text(ns_node[0]) + '::' elif kind in ('class', 'struct'): # Get the full function name. cn_node = node.getElementsByTagName('compoundname') sig_prefix = self.extract_text(cn_node[0]) + '::' md_nodes = self.get_specific_subnodes(node, 'memberdef', recursive=2) for n in md_nodes: if n.attributes['prot'].value != 'public': continue if n.attributes['kind'].value in ['variable', 'typedef']: continue if not self.get_specific_subnodes(n, 'definition'): continue name = self.extract_text(self.get_specific_subnodes(n, 'name')) if name[:8] == 'operator': continue sig = sig_prefix + name if sig in sig_dict: sig_dict[sig].append(n) else: sig_dict[sig] = [n] return sig_dict def handle_typical_memberdefs_no_overload(self, signature, memberdef_nodes): """Produce standard documentation for memberdef_nodes.""" for n in memberdef_nodes: self.add_text(['\n', '%feature("docstring") ', signature, ' "', '\n']) if self.with_function_signature: self.add_line_with_subsequent_indent(self.get_function_signature(n)) self.subnode_parse(n, pieces=[], ignore=['definition', 'name']) self.add_text(['";', '\n']) def handle_typical_memberdefs(self, signature, memberdef_nodes): """Produces docstring entries containing an "Overloaded function" section with the documentation for each overload, if the function is overloaded and self.with_overloaded_functions is set. Else, produce normal documentation. """ if len(memberdef_nodes) == 1 or not self.with_overloaded_functions: self.handle_typical_memberdefs_no_overload(signature, memberdef_nodes) return self.add_text(['\n', '%feature("docstring") ', signature, ' "', '\n']) if self.with_function_signature: for n in memberdef_nodes: self.add_line_with_subsequent_indent(self.get_function_signature(n)) self.add_text('\n') self.add_text(['Overloaded function', '\n', '-------------------']) for n in memberdef_nodes: self.add_text('\n') self.add_line_with_subsequent_indent('* ' + self.get_function_signature(n)) self.subnode_parse(n, pieces=[], indent=4, ignore=['definition', 'name']) self.add_text(['";', '\n']) # MARK: Tag handlers def do_linebreak(self, node): self.add_text(' ') def do_ndash(self, node): self.add_text('--') def do_mdash(self, node): self.add_text('---') def do_emphasis(self, node): self.surround_parse(node, '*', '*') def do_bold(self, node): self.surround_parse(node, '**', '**') def do_computeroutput(self, node): self.surround_parse(node, '`', '`') def do_heading(self, node): self.start_new_paragraph() pieces, self.pieces = self.pieces, [''] level = int(node.attributes['level'].value) self.subnode_parse(node) if level == 1: self.pieces.insert(0, '\n') self.add_text(['\n', len(''.join(self.pieces).strip()) * '=']) elif level == 2: self.add_text(['\n', len(''.join(self.pieces).strip()) * '-']) elif level >= 3: self.pieces.insert(0, level * '#' + ' ') # make following text have no gap to the heading: pieces.extend([''.join(self.pieces) + ' \n', '']) self.pieces = pieces def do_verbatim(self, node): self.start_new_paragraph() self.subnode_parse(node, pieces=[''], indent=4) def do_blockquote(self, node): self.start_new_paragraph() self.subnode_parse(node, pieces=[''], indent='> ') def do_hruler(self, node): self.start_new_paragraph() self.add_text('* * * * * \n') def do_includes(self, node): self.add_text('\nC++ includes: ') self.subnode_parse(node) self.add_text('\n') # MARK: Para tag handler def do_para(self, node): """This is the only place where text wrapping is automatically performed. Generally, this function parses the node (locally), wraps the text, and then adds the result to self.pieces. However, it may be convenient to allow the previous content of self.pieces to be included in the text wrapping. For this, use the following *convention*: If self.pieces ends with '', treat the _previous_ entry as part of the current paragraph. Else, insert new-line and start a new paragraph and "wrapping context". Paragraphs always end with ' \n', but if the parsed content ends with the special symbol '', this is passed on. """ if self.pieces[-1:] == ['']: pieces, self.pieces = self.pieces[:-2], self.pieces[-2:-1] else: self.add_text('\n') pieces, self.pieces = self.pieces, [''] self.subnode_parse(node) dont_end_paragraph = self.pieces[-1:] == [''] # Now do the text wrapping: width = self.textwidth - self.indent wrapped_para = [] for line in ''.join(self.pieces).splitlines(): keep_markdown_newline = line[-2:] == ' ' w_line = textwrap.wrap(line, width=width, break_long_words=False) if w_line == []: w_line = [''] if keep_markdown_newline: w_line[-1] = w_line[-1] + ' ' for wl in w_line: wrapped_para.append(wl + '\n') if wrapped_para: if wrapped_para[-1][-3:] != ' \n': wrapped_para[-1] = wrapped_para[-1][:-1] + ' \n' if dont_end_paragraph: wrapped_para.append('') pieces.extend(wrapped_para) self.pieces = pieces # MARK: List tag handlers def do_itemizedlist(self, node): if self.listitem == '': self.start_new_paragraph() elif self.pieces != [] and self.pieces[-1:] != ['']: self.add_text('\n') listitem = self.listitem if self.listitem in ['*', '-']: self.listitem = '-' else: self.listitem = '*' self.subnode_parse(node) self.listitem = listitem def do_orderedlist(self, node): if self.listitem == '': self.start_new_paragraph() elif self.pieces != [] and self.pieces[-1:] != ['']: self.add_text('\n') listitem = self.listitem self.listitem = 0 self.subnode_parse(node) self.listitem = listitem def do_listitem(self, node): try: self.listitem = int(self.listitem) + 1 item = str(self.listitem) + '. ' except: item = str(self.listitem) + ' ' self.subnode_parse(node, item, indent=4) # MARK: Parameter list tag handlers def do_parameterlist(self, node): self.start_new_paragraph() text = 'unknown' for key, val in node.attributes.items(): if key == 'kind': if val == 'param': text = 'Parameters' elif val == 'exception': text = 'Exceptions' elif val == 'retval': text = 'Returns' else: text = val break if self.indent == 0: self.add_text([text, '\n', len(text) * '-', '\n']) else: self.add_text([text, ': \n']) self.subnode_parse(node) def do_parameteritem(self, node): self.subnode_parse(node, pieces=['* ', '']) def do_parameternamelist(self, node): self.subnode_parse(node) self.add_text([' :', ' \n']) def do_parametername(self, node): if self.pieces != [] and self.pieces != ['* ', '']: self.add_text(', ') data = self.extract_text(node) self.add_text(['`', data, '`']) def do_parameterdescription(self, node): self.subnode_parse(node, pieces=[''], indent=4) # MARK: Section tag handler def do_simplesect(self, node): kind = node.attributes['kind'].value if kind in ('date', 'rcs', 'version'): return self.start_new_paragraph() if kind == 'warning': self.subnode_parse(node, pieces=['**Warning**: ',''], indent=4) elif kind == 'see': self.subnode_parse(node, pieces=['See also: ',''], indent=4) elif kind == 'return': if self.indent == 0: pieces = ['Returns', '\n', len('Returns') * '-', '\n', ''] else: pieces = ['Returns:', '\n', ''] self.subnode_parse(node, pieces=pieces) else: self.subnode_parse(node, pieces=[kind + ': ',''], indent=4) # MARK: %feature("docstring") producing tag handlers def do_compounddef(self, node): """This produces %feature("docstring") entries for classes, and handles class, namespace and file memberdef entries specially to allow for overloaded functions. For other cases, passes parsing on to standard handlers (which may produce unexpected results). """ kind = node.attributes['kind'].value if kind in ('class', 'struct'): prot = node.attributes['prot'].value if prot != 'public': return self.add_text('\n\n') classdefn = self.extract_text(self.get_specific_subnodes(node, 'compoundname')) classname = classdefn.split('::')[-1] self.add_text('%%feature("docstring") %s "\n' % classdefn) if self.with_constructor_list: constructor_nodes = [] for n in self.get_specific_subnodes(node, 'memberdef', recursive=2): if n.attributes['prot'].value == 'public': if self.extract_text(self.get_specific_subnodes(n, 'definition')) == classdefn + '::' + classname: constructor_nodes.append(n) for n in constructor_nodes: self.add_line_with_subsequent_indent(self.get_function_signature(n)) names = ('briefdescription','detaileddescription') sub_dict = self.get_specific_nodes(node, names) for n in ('briefdescription','detaileddescription'): if n in sub_dict: self.parse(sub_dict[n]) if self.with_constructor_list: self.make_constructor_list(constructor_nodes, classname) if self.with_attribute_list: self.make_attribute_list(node) sub_list = self.get_specific_subnodes(node, 'includes') if sub_list: self.parse(sub_list[0]) self.add_text(['";', '\n']) names = ['compoundname', 'briefdescription','detaileddescription', 'includes'] self.subnode_parse(node, ignore = names) elif kind in ('file', 'namespace'): nodes = node.getElementsByTagName('sectiondef') for n in nodes: self.parse(n) # now explicitely handle possibly overloaded member functions. if kind in ['class', 'struct','file', 'namespace']: md_nodes = self.get_memberdef_nodes_and_signatures(node, kind) for sig in md_nodes: self.handle_typical_memberdefs(sig, md_nodes[sig]) def do_memberdef(self, node): """Handle cases outside of class, struct, file or namespace. These are now dealt with by `handle_overloaded_memberfunction`. Do these even exist??? """ prot = node.attributes['prot'].value id = node.attributes['id'].value kind = node.attributes['kind'].value tmp = node.parentNode.parentNode.parentNode compdef = tmp.getElementsByTagName('compounddef')[0] cdef_kind = compdef.attributes['kind'].value if cdef_kind in ('file', 'namespace', 'class', 'struct'): # These cases are now handled by `handle_typical_memberdefs` return if prot != 'public': return first = self.get_specific_nodes(node, ('definition', 'name')) name = self.extract_text(first['name']) if name[:8] == 'operator': # Don't handle operators yet. return if not 'definition' in first or kind in ['variable', 'typedef']: return data = self.extract_text(first['definition']) self.add_text('\n') self.add_text(['/* where did this entry come from??? */', '\n']) self.add_text('%feature("docstring") %s "\n%s' % (data, data)) for n in node.childNodes: if n not in first.values(): self.parse(n) self.add_text(['";', '\n']) # MARK: Entry tag handlers (dont print anything meaningful) def do_sectiondef(self, node): kind = node.attributes['kind'].value if kind in ('public-func', 'func', 'user-defined', ''): self.subnode_parse(node) def do_header(self, node): """For a user defined section def a header field is present which should not be printed as such, so we comment it in the output.""" data = self.extract_text(node) self.add_text('\n/*\n %s \n*/\n' % data) # If our immediate sibling is a 'description' node then we # should comment that out also and remove it from the parent # node's children. parent = node.parentNode idx = parent.childNodes.index(node) if len(parent.childNodes) >= idx + 2: nd = parent.childNodes[idx + 2] if nd.nodeName == 'description': nd = parent.removeChild(nd) self.add_text('\n/*') self.subnode_parse(nd) self.add_text('\n*/\n') def do_member(self, node): kind = node.attributes['kind'].value refid = node.attributes['refid'].value if kind == 'function' and refid[:9] == 'namespace': self.subnode_parse(node) def do_doxygenindex(self, node): self.multi = 1 comps = node.getElementsByTagName('compound') for c in comps: refid = c.attributes['refid'].value fname = refid + '.xml' if not os.path.exists(fname): fname = os.path.join(self.my_dir, fname) if not self.quiet: print("parsing file: %s" % fname) p = Doxy2SWIG(fname, with_function_signature = self.with_function_signature, with_type_info = self.with_type_info, with_constructor_list = self.with_constructor_list, with_attribute_list = self.with_attribute_list, with_overloaded_functions = self.with_overloaded_functions, textwidth = self.textwidth, quiet = self.quiet) p.generate() self.pieces.extend(p.pieces)
basler/pypylon
scripts/builddoxy2swig/doxy2swig/doxy2swig.py
Doxy2SWIG.get_function_signature
python
def get_function_signature(self, node): name = self.extract_text(self.get_specific_subnodes(node, 'name')) if self.with_type_info: argsstring = self.extract_text(self.get_specific_subnodes(node, 'argsstring')) else: argsstring = [] param_id = 1 for n_param in self.get_specific_subnodes(node, 'param'): declname = self.extract_text(self.get_specific_subnodes(n_param, 'declname')) if not declname: declname = 'arg' + str(param_id) defval = self.extract_text(self.get_specific_subnodes(n_param, 'defval')) if defval: defval = '=' + defval argsstring.append(declname + defval) param_id = param_id + 1 argsstring = '(' + ', '.join(argsstring) + ')' type = self.extract_text(self.get_specific_subnodes(node, 'type')) function_definition = name + argsstring if type != '' and type != 'void': function_definition = function_definition + ' -> ' + type return '`' + function_definition + '` '
Returns the function signature string for memberdef nodes.
train
https://github.com/basler/pypylon/blob/d3510fa419b1c2b17f3f0b80a5fbb720c7b84008/scripts/builddoxy2swig/doxy2swig/doxy2swig.py#L337-L359
[ "def get_specific_subnodes(self, node, name, recursive=0):\n \"\"\"Given a node and a name, return a list of child `ELEMENT_NODEs`, that\n have a `tagName` matching the `name`. Search recursively for `recursive`\n levels.\n \"\"\"\n children = [x for x in node.childNodes if x.nodeType == x.ELEMENT_NODE]\n ret = [x for x in children if x.tagName == name]\n if recursive > 0:\n for x in children:\n ret.extend(self.get_specific_subnodes(x, name, recursive-1))\n return ret\n", "def extract_text(self, node):\n \"\"\"Return the string representation of the node or list of nodes by parsing the\n subnodes, but returning the result as a string instead of adding it to `self.pieces`.\n Note that this allows extracting text even if the node is in the ignore list.\n \"\"\"\n if not isinstance(node, (list, tuple)):\n node = [node]\n pieces, self.pieces = self.pieces, ['']\n for n in node:\n for sn in n.childNodes:\n self.parse(sn)\n ret = ''.join(self.pieces)\n self.pieces = pieces\n return ret\n" ]
class Doxy2SWIG: """Converts Doxygen generated XML files into a file containing docstrings that can be used by SWIG-1.3.x that have support for feature("docstring"). Once the data is parsed it is stored in self.pieces. """ def __init__(self, src, with_function_signature = False, with_type_info = False, with_constructor_list = False, with_attribute_list = False, with_overloaded_functions = False, textwidth = 80, quiet = False): """Initialize the instance given a source object. `src` can be a file or filename. If you do not want to include function definitions from doxygen then set `include_function_definition` to `False`. This is handy since this allows you to use the swig generated function definition using %feature("autodoc", [0,1]). """ # options: self.with_function_signature = with_function_signature self.with_type_info = with_type_info self.with_constructor_list = with_constructor_list self.with_attribute_list = with_attribute_list self.with_overloaded_functions = with_overloaded_functions self.textwidth = textwidth self.quiet = quiet # state: self.indent = 0 self.listitem = '' self.pieces = [] f = my_open_read(src) self.my_dir = os.path.dirname(f.name) self.xmldoc = minidom.parse(f).documentElement f.close() self.pieces.append('\n// File: %s\n' % os.path.basename(f.name)) self.space_re = re.compile(r'\s+') self.lead_spc = re.compile(r'^(%feature\S+\s+\S+\s*?)"\s+(\S)') self.multi = 0 self.ignores = ['inheritancegraph', 'param', 'listofallmembers', 'innerclass', 'name', 'declname', 'incdepgraph', 'invincdepgraph', 'programlisting', 'type', 'references', 'referencedby', 'location', 'collaborationgraph', 'reimplements', 'reimplementedby', 'derivedcompoundref', 'basecompoundref', 'argsstring', 'definition', 'exceptions'] #self.generics = [] def generate(self): """Parses the file set in the initialization. The resulting data is stored in `self.pieces`. """ self.parse(self.xmldoc) def write(self, fname): o = my_open_write(fname) o.write(''.join(self.pieces)) o.write('\n') o.close() def parse(self, node): """Parse a given node. This function in turn calls the `parse_<nodeType>` functions which handle the respective nodes. """ pm = getattr(self, "parse_%s" % node.__class__.__name__) pm(node) def parse_Document(self, node): self.parse(node.documentElement) def parse_Text(self, node): txt = node.data if txt == ' ': # this can happen when two tags follow in a text, e.g., # " ...</emph> <formaula>$..." etc. # here we want to keep the space. self.add_text(txt) return txt = txt.replace('\\', r'\\') txt = txt.replace('"', r'\"') # ignore pure whitespace m = self.space_re.match(txt) if m and len(m.group()) == len(txt): pass else: self.add_text(txt) def parse_Comment(self, node): """Parse a `COMMENT_NODE`. This does nothing for now.""" return def parse_Element(self, node): """Parse an `ELEMENT_NODE`. This calls specific `do_<tagName>` handers for different elements. If no handler is available the `subnode_parse` method is called. All tagNames specified in `self.ignores` are simply ignored. """ name = node.tagName ignores = self.ignores if name in ignores: return attr = "do_%s" % name if hasattr(self, attr): handlerMethod = getattr(self, attr) handlerMethod(node) else: self.subnode_parse(node) #if name not in self.generics: self.generics.append(name) # MARK: Special format parsing def subnode_parse(self, node, pieces=None, indent=0, ignore=[], restrict=None): """Parse the subnodes of a given node. Subnodes with tags in the `ignore` list are ignored. If pieces is given, use this as target for the parse results instead of self.pieces. Indent all lines by the amount given in `indent`. Note that the initial content in `pieces` is not indented. The final result is in any case added to self.pieces.""" if pieces is not None: old_pieces, self.pieces = self.pieces, pieces else: old_pieces = [] if type(indent) is int: indent = indent * ' ' if len(indent) > 0: pieces = ''.join(self.pieces) i_piece = pieces[:len(indent)] if self.pieces[-1:] == ['']: self.pieces = [pieces[len(indent):]] + [''] elif self.pieces != []: self.pieces = [pieces[len(indent):]] self.indent += len(indent) for n in node.childNodes: if restrict is not None: if n.nodeType == n.ELEMENT_NODE and n.tagName in restrict: self.parse(n) elif n.nodeType != n.ELEMENT_NODE or n.tagName not in ignore: self.parse(n) if len(indent) > 0: self.pieces = shift(self.pieces, indent, i_piece) self.indent -= len(indent) old_pieces.extend(self.pieces) self.pieces = old_pieces def surround_parse(self, node, pre_char, post_char): """Parse the subnodes of a given node. Subnodes with tags in the `ignore` list are ignored. Prepend `pre_char` and append `post_char` to the output in self.pieces.""" self.add_text(pre_char) self.subnode_parse(node) self.add_text(post_char) # MARK: Helper functions def get_specific_subnodes(self, node, name, recursive=0): """Given a node and a name, return a list of child `ELEMENT_NODEs`, that have a `tagName` matching the `name`. Search recursively for `recursive` levels. """ children = [x for x in node.childNodes if x.nodeType == x.ELEMENT_NODE] ret = [x for x in children if x.tagName == name] if recursive > 0: for x in children: ret.extend(self.get_specific_subnodes(x, name, recursive-1)) return ret def get_specific_nodes(self, node, names): """Given a node and a sequence of strings in `names`, return a dictionary containing the names as keys and child `ELEMENT_NODEs`, that have a `tagName` equal to the name. """ nodes = [(x.tagName, x) for x in node.childNodes if x.nodeType == x.ELEMENT_NODE and x.tagName in names] return dict(nodes) def add_text(self, value): """Adds text corresponding to `value` into `self.pieces`.""" if isinstance(value, (list, tuple)): self.pieces.extend(value) else: self.pieces.append(value) def start_new_paragraph(self): """Make sure to create an empty line. This is overridden, if the previous text ends with the special marker ''. In that case, nothing is done. """ if self.pieces[-1:] == ['']: # respect special marker return elif self.pieces == []: # first paragraph, add '\n', override with '' self.pieces = ['\n'] elif self.pieces[-1][-1:] != '\n': # previous line not ended self.pieces.extend([' \n' ,'\n']) else: #default self.pieces.append('\n') def add_line_with_subsequent_indent(self, line, indent=4): """Add line of text and wrap such that subsequent lines are indented by `indent` spaces. """ if isinstance(line, (list, tuple)): line = ''.join(line) line = line.strip() width = self.textwidth-self.indent-indent wrapped_lines = textwrap.wrap(line[indent:], width=width) for i in range(len(wrapped_lines)): if wrapped_lines[i] != '': wrapped_lines[i] = indent * ' ' + wrapped_lines[i] self.pieces.append(line[:indent] + '\n'.join(wrapped_lines)[indent:] + ' \n') def extract_text(self, node): """Return the string representation of the node or list of nodes by parsing the subnodes, but returning the result as a string instead of adding it to `self.pieces`. Note that this allows extracting text even if the node is in the ignore list. """ if not isinstance(node, (list, tuple)): node = [node] pieces, self.pieces = self.pieces, [''] for n in node: for sn in n.childNodes: self.parse(sn) ret = ''.join(self.pieces) self.pieces = pieces return ret # MARK: Special parsing tasks (need to be called manually) def make_constructor_list(self, constructor_nodes, classname): """Produces the "Constructors" section and the constructor signatures (since swig does not do so for classes) for class docstrings.""" if constructor_nodes == []: return self.add_text(['\n', 'Constructors', '\n', '------------']) for n in constructor_nodes: self.add_text('\n') self.add_line_with_subsequent_indent('* ' + self.get_function_signature(n)) self.subnode_parse(n, pieces = [], indent=4, ignore=['definition', 'name']) def make_attribute_list(self, node): """Produces the "Attributes" section in class docstrings for public member variables (attributes). """ atr_nodes = [] for n in self.get_specific_subnodes(node, 'memberdef', recursive=2): if n.attributes['kind'].value == 'variable' and n.attributes['prot'].value == 'public': atr_nodes.append(n) if not atr_nodes: return self.add_text(['\n', 'Attributes', '\n', '----------']) for n in atr_nodes: name = self.extract_text(self.get_specific_subnodes(n, 'name')) self.add_text(['\n* ', '`', name, '`', ' : ']) self.add_text(['`', self.extract_text(self.get_specific_subnodes(n, 'type')), '`']) self.add_text(' \n') restrict = ['briefdescription', 'detaileddescription'] self.subnode_parse(n, pieces=[''], indent=4, restrict=restrict) def get_memberdef_nodes_and_signatures(self, node, kind): """Collects the memberdef nodes and corresponding signatures that correspond to public function entries that are at most depth 2 deeper than the current (compounddef) node. Returns a dictionary with function signatures (what swig expects after the %feature directive) as keys, and a list of corresponding memberdef nodes as values.""" sig_dict = {} sig_prefix = '' if kind in ('file', 'namespace'): ns_node = node.getElementsByTagName('innernamespace') if not ns_node and kind == 'namespace': ns_node = node.getElementsByTagName('compoundname') if ns_node: sig_prefix = self.extract_text(ns_node[0]) + '::' elif kind in ('class', 'struct'): # Get the full function name. cn_node = node.getElementsByTagName('compoundname') sig_prefix = self.extract_text(cn_node[0]) + '::' md_nodes = self.get_specific_subnodes(node, 'memberdef', recursive=2) for n in md_nodes: if n.attributes['prot'].value != 'public': continue if n.attributes['kind'].value in ['variable', 'typedef']: continue if not self.get_specific_subnodes(n, 'definition'): continue name = self.extract_text(self.get_specific_subnodes(n, 'name')) if name[:8] == 'operator': continue sig = sig_prefix + name if sig in sig_dict: sig_dict[sig].append(n) else: sig_dict[sig] = [n] return sig_dict def handle_typical_memberdefs_no_overload(self, signature, memberdef_nodes): """Produce standard documentation for memberdef_nodes.""" for n in memberdef_nodes: self.add_text(['\n', '%feature("docstring") ', signature, ' "', '\n']) if self.with_function_signature: self.add_line_with_subsequent_indent(self.get_function_signature(n)) self.subnode_parse(n, pieces=[], ignore=['definition', 'name']) self.add_text(['";', '\n']) def handle_typical_memberdefs(self, signature, memberdef_nodes): """Produces docstring entries containing an "Overloaded function" section with the documentation for each overload, if the function is overloaded and self.with_overloaded_functions is set. Else, produce normal documentation. """ if len(memberdef_nodes) == 1 or not self.with_overloaded_functions: self.handle_typical_memberdefs_no_overload(signature, memberdef_nodes) return self.add_text(['\n', '%feature("docstring") ', signature, ' "', '\n']) if self.with_function_signature: for n in memberdef_nodes: self.add_line_with_subsequent_indent(self.get_function_signature(n)) self.add_text('\n') self.add_text(['Overloaded function', '\n', '-------------------']) for n in memberdef_nodes: self.add_text('\n') self.add_line_with_subsequent_indent('* ' + self.get_function_signature(n)) self.subnode_parse(n, pieces=[], indent=4, ignore=['definition', 'name']) self.add_text(['";', '\n']) # MARK: Tag handlers def do_linebreak(self, node): self.add_text(' ') def do_ndash(self, node): self.add_text('--') def do_mdash(self, node): self.add_text('---') def do_emphasis(self, node): self.surround_parse(node, '*', '*') def do_bold(self, node): self.surround_parse(node, '**', '**') def do_computeroutput(self, node): self.surround_parse(node, '`', '`') def do_heading(self, node): self.start_new_paragraph() pieces, self.pieces = self.pieces, [''] level = int(node.attributes['level'].value) self.subnode_parse(node) if level == 1: self.pieces.insert(0, '\n') self.add_text(['\n', len(''.join(self.pieces).strip()) * '=']) elif level == 2: self.add_text(['\n', len(''.join(self.pieces).strip()) * '-']) elif level >= 3: self.pieces.insert(0, level * '#' + ' ') # make following text have no gap to the heading: pieces.extend([''.join(self.pieces) + ' \n', '']) self.pieces = pieces def do_verbatim(self, node): self.start_new_paragraph() self.subnode_parse(node, pieces=[''], indent=4) def do_blockquote(self, node): self.start_new_paragraph() self.subnode_parse(node, pieces=[''], indent='> ') def do_hruler(self, node): self.start_new_paragraph() self.add_text('* * * * * \n') def do_includes(self, node): self.add_text('\nC++ includes: ') self.subnode_parse(node) self.add_text('\n') # MARK: Para tag handler def do_para(self, node): """This is the only place where text wrapping is automatically performed. Generally, this function parses the node (locally), wraps the text, and then adds the result to self.pieces. However, it may be convenient to allow the previous content of self.pieces to be included in the text wrapping. For this, use the following *convention*: If self.pieces ends with '', treat the _previous_ entry as part of the current paragraph. Else, insert new-line and start a new paragraph and "wrapping context". Paragraphs always end with ' \n', but if the parsed content ends with the special symbol '', this is passed on. """ if self.pieces[-1:] == ['']: pieces, self.pieces = self.pieces[:-2], self.pieces[-2:-1] else: self.add_text('\n') pieces, self.pieces = self.pieces, [''] self.subnode_parse(node) dont_end_paragraph = self.pieces[-1:] == [''] # Now do the text wrapping: width = self.textwidth - self.indent wrapped_para = [] for line in ''.join(self.pieces).splitlines(): keep_markdown_newline = line[-2:] == ' ' w_line = textwrap.wrap(line, width=width, break_long_words=False) if w_line == []: w_line = [''] if keep_markdown_newline: w_line[-1] = w_line[-1] + ' ' for wl in w_line: wrapped_para.append(wl + '\n') if wrapped_para: if wrapped_para[-1][-3:] != ' \n': wrapped_para[-1] = wrapped_para[-1][:-1] + ' \n' if dont_end_paragraph: wrapped_para.append('') pieces.extend(wrapped_para) self.pieces = pieces # MARK: List tag handlers def do_itemizedlist(self, node): if self.listitem == '': self.start_new_paragraph() elif self.pieces != [] and self.pieces[-1:] != ['']: self.add_text('\n') listitem = self.listitem if self.listitem in ['*', '-']: self.listitem = '-' else: self.listitem = '*' self.subnode_parse(node) self.listitem = listitem def do_orderedlist(self, node): if self.listitem == '': self.start_new_paragraph() elif self.pieces != [] and self.pieces[-1:] != ['']: self.add_text('\n') listitem = self.listitem self.listitem = 0 self.subnode_parse(node) self.listitem = listitem def do_listitem(self, node): try: self.listitem = int(self.listitem) + 1 item = str(self.listitem) + '. ' except: item = str(self.listitem) + ' ' self.subnode_parse(node, item, indent=4) # MARK: Parameter list tag handlers def do_parameterlist(self, node): self.start_new_paragraph() text = 'unknown' for key, val in node.attributes.items(): if key == 'kind': if val == 'param': text = 'Parameters' elif val == 'exception': text = 'Exceptions' elif val == 'retval': text = 'Returns' else: text = val break if self.indent == 0: self.add_text([text, '\n', len(text) * '-', '\n']) else: self.add_text([text, ': \n']) self.subnode_parse(node) def do_parameteritem(self, node): self.subnode_parse(node, pieces=['* ', '']) def do_parameternamelist(self, node): self.subnode_parse(node) self.add_text([' :', ' \n']) def do_parametername(self, node): if self.pieces != [] and self.pieces != ['* ', '']: self.add_text(', ') data = self.extract_text(node) self.add_text(['`', data, '`']) def do_parameterdescription(self, node): self.subnode_parse(node, pieces=[''], indent=4) # MARK: Section tag handler def do_simplesect(self, node): kind = node.attributes['kind'].value if kind in ('date', 'rcs', 'version'): return self.start_new_paragraph() if kind == 'warning': self.subnode_parse(node, pieces=['**Warning**: ',''], indent=4) elif kind == 'see': self.subnode_parse(node, pieces=['See also: ',''], indent=4) elif kind == 'return': if self.indent == 0: pieces = ['Returns', '\n', len('Returns') * '-', '\n', ''] else: pieces = ['Returns:', '\n', ''] self.subnode_parse(node, pieces=pieces) else: self.subnode_parse(node, pieces=[kind + ': ',''], indent=4) # MARK: %feature("docstring") producing tag handlers def do_compounddef(self, node): """This produces %feature("docstring") entries for classes, and handles class, namespace and file memberdef entries specially to allow for overloaded functions. For other cases, passes parsing on to standard handlers (which may produce unexpected results). """ kind = node.attributes['kind'].value if kind in ('class', 'struct'): prot = node.attributes['prot'].value if prot != 'public': return self.add_text('\n\n') classdefn = self.extract_text(self.get_specific_subnodes(node, 'compoundname')) classname = classdefn.split('::')[-1] self.add_text('%%feature("docstring") %s "\n' % classdefn) if self.with_constructor_list: constructor_nodes = [] for n in self.get_specific_subnodes(node, 'memberdef', recursive=2): if n.attributes['prot'].value == 'public': if self.extract_text(self.get_specific_subnodes(n, 'definition')) == classdefn + '::' + classname: constructor_nodes.append(n) for n in constructor_nodes: self.add_line_with_subsequent_indent(self.get_function_signature(n)) names = ('briefdescription','detaileddescription') sub_dict = self.get_specific_nodes(node, names) for n in ('briefdescription','detaileddescription'): if n in sub_dict: self.parse(sub_dict[n]) if self.with_constructor_list: self.make_constructor_list(constructor_nodes, classname) if self.with_attribute_list: self.make_attribute_list(node) sub_list = self.get_specific_subnodes(node, 'includes') if sub_list: self.parse(sub_list[0]) self.add_text(['";', '\n']) names = ['compoundname', 'briefdescription','detaileddescription', 'includes'] self.subnode_parse(node, ignore = names) elif kind in ('file', 'namespace'): nodes = node.getElementsByTagName('sectiondef') for n in nodes: self.parse(n) # now explicitely handle possibly overloaded member functions. if kind in ['class', 'struct','file', 'namespace']: md_nodes = self.get_memberdef_nodes_and_signatures(node, kind) for sig in md_nodes: self.handle_typical_memberdefs(sig, md_nodes[sig]) def do_memberdef(self, node): """Handle cases outside of class, struct, file or namespace. These are now dealt with by `handle_overloaded_memberfunction`. Do these even exist??? """ prot = node.attributes['prot'].value id = node.attributes['id'].value kind = node.attributes['kind'].value tmp = node.parentNode.parentNode.parentNode compdef = tmp.getElementsByTagName('compounddef')[0] cdef_kind = compdef.attributes['kind'].value if cdef_kind in ('file', 'namespace', 'class', 'struct'): # These cases are now handled by `handle_typical_memberdefs` return if prot != 'public': return first = self.get_specific_nodes(node, ('definition', 'name')) name = self.extract_text(first['name']) if name[:8] == 'operator': # Don't handle operators yet. return if not 'definition' in first or kind in ['variable', 'typedef']: return data = self.extract_text(first['definition']) self.add_text('\n') self.add_text(['/* where did this entry come from??? */', '\n']) self.add_text('%feature("docstring") %s "\n%s' % (data, data)) for n in node.childNodes: if n not in first.values(): self.parse(n) self.add_text(['";', '\n']) # MARK: Entry tag handlers (dont print anything meaningful) def do_sectiondef(self, node): kind = node.attributes['kind'].value if kind in ('public-func', 'func', 'user-defined', ''): self.subnode_parse(node) def do_header(self, node): """For a user defined section def a header field is present which should not be printed as such, so we comment it in the output.""" data = self.extract_text(node) self.add_text('\n/*\n %s \n*/\n' % data) # If our immediate sibling is a 'description' node then we # should comment that out also and remove it from the parent # node's children. parent = node.parentNode idx = parent.childNodes.index(node) if len(parent.childNodes) >= idx + 2: nd = parent.childNodes[idx + 2] if nd.nodeName == 'description': nd = parent.removeChild(nd) self.add_text('\n/*') self.subnode_parse(nd) self.add_text('\n*/\n') def do_member(self, node): kind = node.attributes['kind'].value refid = node.attributes['refid'].value if kind == 'function' and refid[:9] == 'namespace': self.subnode_parse(node) def do_doxygenindex(self, node): self.multi = 1 comps = node.getElementsByTagName('compound') for c in comps: refid = c.attributes['refid'].value fname = refid + '.xml' if not os.path.exists(fname): fname = os.path.join(self.my_dir, fname) if not self.quiet: print("parsing file: %s" % fname) p = Doxy2SWIG(fname, with_function_signature = self.with_function_signature, with_type_info = self.with_type_info, with_constructor_list = self.with_constructor_list, with_attribute_list = self.with_attribute_list, with_overloaded_functions = self.with_overloaded_functions, textwidth = self.textwidth, quiet = self.quiet) p.generate() self.pieces.extend(p.pieces)
basler/pypylon
scripts/builddoxy2swig/doxy2swig/doxy2swig.py
Doxy2SWIG.make_constructor_list
python
def make_constructor_list(self, constructor_nodes, classname): if constructor_nodes == []: return self.add_text(['\n', 'Constructors', '\n', '------------']) for n in constructor_nodes: self.add_text('\n') self.add_line_with_subsequent_indent('* ' + self.get_function_signature(n)) self.subnode_parse(n, pieces = [], indent=4, ignore=['definition', 'name'])
Produces the "Constructors" section and the constructor signatures (since swig does not do so for classes) for class docstrings.
train
https://github.com/basler/pypylon/blob/d3510fa419b1c2b17f3f0b80a5fbb720c7b84008/scripts/builddoxy2swig/doxy2swig/doxy2swig.py#L362-L372
[ "def subnode_parse(self, node, pieces=None, indent=0, ignore=[], restrict=None):\n \"\"\"Parse the subnodes of a given node. Subnodes with tags in the\n `ignore` list are ignored. If pieces is given, use this as target for\n the parse results instead of self.pieces. Indent all lines by the amount\n given in `indent`. Note that the initial content in `pieces` is not\n indented. The final result is in any case added to self.pieces.\"\"\"\n if pieces is not None:\n old_pieces, self.pieces = self.pieces, pieces\n else:\n old_pieces = []\n if type(indent) is int:\n indent = indent * ' '\n if len(indent) > 0:\n pieces = ''.join(self.pieces)\n i_piece = pieces[:len(indent)]\n if self.pieces[-1:] == ['']:\n self.pieces = [pieces[len(indent):]] + ['']\n elif self.pieces != []:\n self.pieces = [pieces[len(indent):]]\n self.indent += len(indent)\n for n in node.childNodes:\n if restrict is not None:\n if n.nodeType == n.ELEMENT_NODE and n.tagName in restrict:\n self.parse(n)\n elif n.nodeType != n.ELEMENT_NODE or n.tagName not in ignore:\n self.parse(n)\n if len(indent) > 0:\n self.pieces = shift(self.pieces, indent, i_piece)\n self.indent -= len(indent)\n old_pieces.extend(self.pieces)\n self.pieces = old_pieces\n", "def add_text(self, value):\n \"\"\"Adds text corresponding to `value` into `self.pieces`.\"\"\"\n if isinstance(value, (list, tuple)):\n self.pieces.extend(value)\n else:\n self.pieces.append(value)\n", "def add_line_with_subsequent_indent(self, line, indent=4):\n \"\"\"Add line of text and wrap such that subsequent lines are indented\n by `indent` spaces.\n \"\"\"\n if isinstance(line, (list, tuple)):\n line = ''.join(line)\n line = line.strip()\n width = self.textwidth-self.indent-indent\n wrapped_lines = textwrap.wrap(line[indent:], width=width)\n for i in range(len(wrapped_lines)):\n if wrapped_lines[i] != '':\n wrapped_lines[i] = indent * ' ' + wrapped_lines[i]\n self.pieces.append(line[:indent] + '\\n'.join(wrapped_lines)[indent:] + ' \\n')\n", "def get_function_signature(self, node):\n \"\"\"Returns the function signature string for memberdef nodes.\"\"\"\n name = self.extract_text(self.get_specific_subnodes(node, 'name'))\n if self.with_type_info:\n argsstring = self.extract_text(self.get_specific_subnodes(node, 'argsstring'))\n else:\n argsstring = []\n param_id = 1\n for n_param in self.get_specific_subnodes(node, 'param'):\n declname = self.extract_text(self.get_specific_subnodes(n_param, 'declname'))\n if not declname:\n declname = 'arg' + str(param_id)\n defval = self.extract_text(self.get_specific_subnodes(n_param, 'defval'))\n if defval:\n defval = '=' + defval\n argsstring.append(declname + defval)\n param_id = param_id + 1\n argsstring = '(' + ', '.join(argsstring) + ')'\n type = self.extract_text(self.get_specific_subnodes(node, 'type'))\n function_definition = name + argsstring\n if type != '' and type != 'void':\n function_definition = function_definition + ' -> ' + type\n return '`' + function_definition + '` '\n" ]
class Doxy2SWIG: """Converts Doxygen generated XML files into a file containing docstrings that can be used by SWIG-1.3.x that have support for feature("docstring"). Once the data is parsed it is stored in self.pieces. """ def __init__(self, src, with_function_signature = False, with_type_info = False, with_constructor_list = False, with_attribute_list = False, with_overloaded_functions = False, textwidth = 80, quiet = False): """Initialize the instance given a source object. `src` can be a file or filename. If you do not want to include function definitions from doxygen then set `include_function_definition` to `False`. This is handy since this allows you to use the swig generated function definition using %feature("autodoc", [0,1]). """ # options: self.with_function_signature = with_function_signature self.with_type_info = with_type_info self.with_constructor_list = with_constructor_list self.with_attribute_list = with_attribute_list self.with_overloaded_functions = with_overloaded_functions self.textwidth = textwidth self.quiet = quiet # state: self.indent = 0 self.listitem = '' self.pieces = [] f = my_open_read(src) self.my_dir = os.path.dirname(f.name) self.xmldoc = minidom.parse(f).documentElement f.close() self.pieces.append('\n// File: %s\n' % os.path.basename(f.name)) self.space_re = re.compile(r'\s+') self.lead_spc = re.compile(r'^(%feature\S+\s+\S+\s*?)"\s+(\S)') self.multi = 0 self.ignores = ['inheritancegraph', 'param', 'listofallmembers', 'innerclass', 'name', 'declname', 'incdepgraph', 'invincdepgraph', 'programlisting', 'type', 'references', 'referencedby', 'location', 'collaborationgraph', 'reimplements', 'reimplementedby', 'derivedcompoundref', 'basecompoundref', 'argsstring', 'definition', 'exceptions'] #self.generics = [] def generate(self): """Parses the file set in the initialization. The resulting data is stored in `self.pieces`. """ self.parse(self.xmldoc) def write(self, fname): o = my_open_write(fname) o.write(''.join(self.pieces)) o.write('\n') o.close() def parse(self, node): """Parse a given node. This function in turn calls the `parse_<nodeType>` functions which handle the respective nodes. """ pm = getattr(self, "parse_%s" % node.__class__.__name__) pm(node) def parse_Document(self, node): self.parse(node.documentElement) def parse_Text(self, node): txt = node.data if txt == ' ': # this can happen when two tags follow in a text, e.g., # " ...</emph> <formaula>$..." etc. # here we want to keep the space. self.add_text(txt) return txt = txt.replace('\\', r'\\') txt = txt.replace('"', r'\"') # ignore pure whitespace m = self.space_re.match(txt) if m and len(m.group()) == len(txt): pass else: self.add_text(txt) def parse_Comment(self, node): """Parse a `COMMENT_NODE`. This does nothing for now.""" return def parse_Element(self, node): """Parse an `ELEMENT_NODE`. This calls specific `do_<tagName>` handers for different elements. If no handler is available the `subnode_parse` method is called. All tagNames specified in `self.ignores` are simply ignored. """ name = node.tagName ignores = self.ignores if name in ignores: return attr = "do_%s" % name if hasattr(self, attr): handlerMethod = getattr(self, attr) handlerMethod(node) else: self.subnode_parse(node) #if name not in self.generics: self.generics.append(name) # MARK: Special format parsing def subnode_parse(self, node, pieces=None, indent=0, ignore=[], restrict=None): """Parse the subnodes of a given node. Subnodes with tags in the `ignore` list are ignored. If pieces is given, use this as target for the parse results instead of self.pieces. Indent all lines by the amount given in `indent`. Note that the initial content in `pieces` is not indented. The final result is in any case added to self.pieces.""" if pieces is not None: old_pieces, self.pieces = self.pieces, pieces else: old_pieces = [] if type(indent) is int: indent = indent * ' ' if len(indent) > 0: pieces = ''.join(self.pieces) i_piece = pieces[:len(indent)] if self.pieces[-1:] == ['']: self.pieces = [pieces[len(indent):]] + [''] elif self.pieces != []: self.pieces = [pieces[len(indent):]] self.indent += len(indent) for n in node.childNodes: if restrict is not None: if n.nodeType == n.ELEMENT_NODE and n.tagName in restrict: self.parse(n) elif n.nodeType != n.ELEMENT_NODE or n.tagName not in ignore: self.parse(n) if len(indent) > 0: self.pieces = shift(self.pieces, indent, i_piece) self.indent -= len(indent) old_pieces.extend(self.pieces) self.pieces = old_pieces def surround_parse(self, node, pre_char, post_char): """Parse the subnodes of a given node. Subnodes with tags in the `ignore` list are ignored. Prepend `pre_char` and append `post_char` to the output in self.pieces.""" self.add_text(pre_char) self.subnode_parse(node) self.add_text(post_char) # MARK: Helper functions def get_specific_subnodes(self, node, name, recursive=0): """Given a node and a name, return a list of child `ELEMENT_NODEs`, that have a `tagName` matching the `name`. Search recursively for `recursive` levels. """ children = [x for x in node.childNodes if x.nodeType == x.ELEMENT_NODE] ret = [x for x in children if x.tagName == name] if recursive > 0: for x in children: ret.extend(self.get_specific_subnodes(x, name, recursive-1)) return ret def get_specific_nodes(self, node, names): """Given a node and a sequence of strings in `names`, return a dictionary containing the names as keys and child `ELEMENT_NODEs`, that have a `tagName` equal to the name. """ nodes = [(x.tagName, x) for x in node.childNodes if x.nodeType == x.ELEMENT_NODE and x.tagName in names] return dict(nodes) def add_text(self, value): """Adds text corresponding to `value` into `self.pieces`.""" if isinstance(value, (list, tuple)): self.pieces.extend(value) else: self.pieces.append(value) def start_new_paragraph(self): """Make sure to create an empty line. This is overridden, if the previous text ends with the special marker ''. In that case, nothing is done. """ if self.pieces[-1:] == ['']: # respect special marker return elif self.pieces == []: # first paragraph, add '\n', override with '' self.pieces = ['\n'] elif self.pieces[-1][-1:] != '\n': # previous line not ended self.pieces.extend([' \n' ,'\n']) else: #default self.pieces.append('\n') def add_line_with_subsequent_indent(self, line, indent=4): """Add line of text and wrap such that subsequent lines are indented by `indent` spaces. """ if isinstance(line, (list, tuple)): line = ''.join(line) line = line.strip() width = self.textwidth-self.indent-indent wrapped_lines = textwrap.wrap(line[indent:], width=width) for i in range(len(wrapped_lines)): if wrapped_lines[i] != '': wrapped_lines[i] = indent * ' ' + wrapped_lines[i] self.pieces.append(line[:indent] + '\n'.join(wrapped_lines)[indent:] + ' \n') def extract_text(self, node): """Return the string representation of the node or list of nodes by parsing the subnodes, but returning the result as a string instead of adding it to `self.pieces`. Note that this allows extracting text even if the node is in the ignore list. """ if not isinstance(node, (list, tuple)): node = [node] pieces, self.pieces = self.pieces, [''] for n in node: for sn in n.childNodes: self.parse(sn) ret = ''.join(self.pieces) self.pieces = pieces return ret def get_function_signature(self, node): """Returns the function signature string for memberdef nodes.""" name = self.extract_text(self.get_specific_subnodes(node, 'name')) if self.with_type_info: argsstring = self.extract_text(self.get_specific_subnodes(node, 'argsstring')) else: argsstring = [] param_id = 1 for n_param in self.get_specific_subnodes(node, 'param'): declname = self.extract_text(self.get_specific_subnodes(n_param, 'declname')) if not declname: declname = 'arg' + str(param_id) defval = self.extract_text(self.get_specific_subnodes(n_param, 'defval')) if defval: defval = '=' + defval argsstring.append(declname + defval) param_id = param_id + 1 argsstring = '(' + ', '.join(argsstring) + ')' type = self.extract_text(self.get_specific_subnodes(node, 'type')) function_definition = name + argsstring if type != '' and type != 'void': function_definition = function_definition + ' -> ' + type return '`' + function_definition + '` ' # MARK: Special parsing tasks (need to be called manually) def make_attribute_list(self, node): """Produces the "Attributes" section in class docstrings for public member variables (attributes). """ atr_nodes = [] for n in self.get_specific_subnodes(node, 'memberdef', recursive=2): if n.attributes['kind'].value == 'variable' and n.attributes['prot'].value == 'public': atr_nodes.append(n) if not atr_nodes: return self.add_text(['\n', 'Attributes', '\n', '----------']) for n in atr_nodes: name = self.extract_text(self.get_specific_subnodes(n, 'name')) self.add_text(['\n* ', '`', name, '`', ' : ']) self.add_text(['`', self.extract_text(self.get_specific_subnodes(n, 'type')), '`']) self.add_text(' \n') restrict = ['briefdescription', 'detaileddescription'] self.subnode_parse(n, pieces=[''], indent=4, restrict=restrict) def get_memberdef_nodes_and_signatures(self, node, kind): """Collects the memberdef nodes and corresponding signatures that correspond to public function entries that are at most depth 2 deeper than the current (compounddef) node. Returns a dictionary with function signatures (what swig expects after the %feature directive) as keys, and a list of corresponding memberdef nodes as values.""" sig_dict = {} sig_prefix = '' if kind in ('file', 'namespace'): ns_node = node.getElementsByTagName('innernamespace') if not ns_node and kind == 'namespace': ns_node = node.getElementsByTagName('compoundname') if ns_node: sig_prefix = self.extract_text(ns_node[0]) + '::' elif kind in ('class', 'struct'): # Get the full function name. cn_node = node.getElementsByTagName('compoundname') sig_prefix = self.extract_text(cn_node[0]) + '::' md_nodes = self.get_specific_subnodes(node, 'memberdef', recursive=2) for n in md_nodes: if n.attributes['prot'].value != 'public': continue if n.attributes['kind'].value in ['variable', 'typedef']: continue if not self.get_specific_subnodes(n, 'definition'): continue name = self.extract_text(self.get_specific_subnodes(n, 'name')) if name[:8] == 'operator': continue sig = sig_prefix + name if sig in sig_dict: sig_dict[sig].append(n) else: sig_dict[sig] = [n] return sig_dict def handle_typical_memberdefs_no_overload(self, signature, memberdef_nodes): """Produce standard documentation for memberdef_nodes.""" for n in memberdef_nodes: self.add_text(['\n', '%feature("docstring") ', signature, ' "', '\n']) if self.with_function_signature: self.add_line_with_subsequent_indent(self.get_function_signature(n)) self.subnode_parse(n, pieces=[], ignore=['definition', 'name']) self.add_text(['";', '\n']) def handle_typical_memberdefs(self, signature, memberdef_nodes): """Produces docstring entries containing an "Overloaded function" section with the documentation for each overload, if the function is overloaded and self.with_overloaded_functions is set. Else, produce normal documentation. """ if len(memberdef_nodes) == 1 or not self.with_overloaded_functions: self.handle_typical_memberdefs_no_overload(signature, memberdef_nodes) return self.add_text(['\n', '%feature("docstring") ', signature, ' "', '\n']) if self.with_function_signature: for n in memberdef_nodes: self.add_line_with_subsequent_indent(self.get_function_signature(n)) self.add_text('\n') self.add_text(['Overloaded function', '\n', '-------------------']) for n in memberdef_nodes: self.add_text('\n') self.add_line_with_subsequent_indent('* ' + self.get_function_signature(n)) self.subnode_parse(n, pieces=[], indent=4, ignore=['definition', 'name']) self.add_text(['";', '\n']) # MARK: Tag handlers def do_linebreak(self, node): self.add_text(' ') def do_ndash(self, node): self.add_text('--') def do_mdash(self, node): self.add_text('---') def do_emphasis(self, node): self.surround_parse(node, '*', '*') def do_bold(self, node): self.surround_parse(node, '**', '**') def do_computeroutput(self, node): self.surround_parse(node, '`', '`') def do_heading(self, node): self.start_new_paragraph() pieces, self.pieces = self.pieces, [''] level = int(node.attributes['level'].value) self.subnode_parse(node) if level == 1: self.pieces.insert(0, '\n') self.add_text(['\n', len(''.join(self.pieces).strip()) * '=']) elif level == 2: self.add_text(['\n', len(''.join(self.pieces).strip()) * '-']) elif level >= 3: self.pieces.insert(0, level * '#' + ' ') # make following text have no gap to the heading: pieces.extend([''.join(self.pieces) + ' \n', '']) self.pieces = pieces def do_verbatim(self, node): self.start_new_paragraph() self.subnode_parse(node, pieces=[''], indent=4) def do_blockquote(self, node): self.start_new_paragraph() self.subnode_parse(node, pieces=[''], indent='> ') def do_hruler(self, node): self.start_new_paragraph() self.add_text('* * * * * \n') def do_includes(self, node): self.add_text('\nC++ includes: ') self.subnode_parse(node) self.add_text('\n') # MARK: Para tag handler def do_para(self, node): """This is the only place where text wrapping is automatically performed. Generally, this function parses the node (locally), wraps the text, and then adds the result to self.pieces. However, it may be convenient to allow the previous content of self.pieces to be included in the text wrapping. For this, use the following *convention*: If self.pieces ends with '', treat the _previous_ entry as part of the current paragraph. Else, insert new-line and start a new paragraph and "wrapping context". Paragraphs always end with ' \n', but if the parsed content ends with the special symbol '', this is passed on. """ if self.pieces[-1:] == ['']: pieces, self.pieces = self.pieces[:-2], self.pieces[-2:-1] else: self.add_text('\n') pieces, self.pieces = self.pieces, [''] self.subnode_parse(node) dont_end_paragraph = self.pieces[-1:] == [''] # Now do the text wrapping: width = self.textwidth - self.indent wrapped_para = [] for line in ''.join(self.pieces).splitlines(): keep_markdown_newline = line[-2:] == ' ' w_line = textwrap.wrap(line, width=width, break_long_words=False) if w_line == []: w_line = [''] if keep_markdown_newline: w_line[-1] = w_line[-1] + ' ' for wl in w_line: wrapped_para.append(wl + '\n') if wrapped_para: if wrapped_para[-1][-3:] != ' \n': wrapped_para[-1] = wrapped_para[-1][:-1] + ' \n' if dont_end_paragraph: wrapped_para.append('') pieces.extend(wrapped_para) self.pieces = pieces # MARK: List tag handlers def do_itemizedlist(self, node): if self.listitem == '': self.start_new_paragraph() elif self.pieces != [] and self.pieces[-1:] != ['']: self.add_text('\n') listitem = self.listitem if self.listitem in ['*', '-']: self.listitem = '-' else: self.listitem = '*' self.subnode_parse(node) self.listitem = listitem def do_orderedlist(self, node): if self.listitem == '': self.start_new_paragraph() elif self.pieces != [] and self.pieces[-1:] != ['']: self.add_text('\n') listitem = self.listitem self.listitem = 0 self.subnode_parse(node) self.listitem = listitem def do_listitem(self, node): try: self.listitem = int(self.listitem) + 1 item = str(self.listitem) + '. ' except: item = str(self.listitem) + ' ' self.subnode_parse(node, item, indent=4) # MARK: Parameter list tag handlers def do_parameterlist(self, node): self.start_new_paragraph() text = 'unknown' for key, val in node.attributes.items(): if key == 'kind': if val == 'param': text = 'Parameters' elif val == 'exception': text = 'Exceptions' elif val == 'retval': text = 'Returns' else: text = val break if self.indent == 0: self.add_text([text, '\n', len(text) * '-', '\n']) else: self.add_text([text, ': \n']) self.subnode_parse(node) def do_parameteritem(self, node): self.subnode_parse(node, pieces=['* ', '']) def do_parameternamelist(self, node): self.subnode_parse(node) self.add_text([' :', ' \n']) def do_parametername(self, node): if self.pieces != [] and self.pieces != ['* ', '']: self.add_text(', ') data = self.extract_text(node) self.add_text(['`', data, '`']) def do_parameterdescription(self, node): self.subnode_parse(node, pieces=[''], indent=4) # MARK: Section tag handler def do_simplesect(self, node): kind = node.attributes['kind'].value if kind in ('date', 'rcs', 'version'): return self.start_new_paragraph() if kind == 'warning': self.subnode_parse(node, pieces=['**Warning**: ',''], indent=4) elif kind == 'see': self.subnode_parse(node, pieces=['See also: ',''], indent=4) elif kind == 'return': if self.indent == 0: pieces = ['Returns', '\n', len('Returns') * '-', '\n', ''] else: pieces = ['Returns:', '\n', ''] self.subnode_parse(node, pieces=pieces) else: self.subnode_parse(node, pieces=[kind + ': ',''], indent=4) # MARK: %feature("docstring") producing tag handlers def do_compounddef(self, node): """This produces %feature("docstring") entries for classes, and handles class, namespace and file memberdef entries specially to allow for overloaded functions. For other cases, passes parsing on to standard handlers (which may produce unexpected results). """ kind = node.attributes['kind'].value if kind in ('class', 'struct'): prot = node.attributes['prot'].value if prot != 'public': return self.add_text('\n\n') classdefn = self.extract_text(self.get_specific_subnodes(node, 'compoundname')) classname = classdefn.split('::')[-1] self.add_text('%%feature("docstring") %s "\n' % classdefn) if self.with_constructor_list: constructor_nodes = [] for n in self.get_specific_subnodes(node, 'memberdef', recursive=2): if n.attributes['prot'].value == 'public': if self.extract_text(self.get_specific_subnodes(n, 'definition')) == classdefn + '::' + classname: constructor_nodes.append(n) for n in constructor_nodes: self.add_line_with_subsequent_indent(self.get_function_signature(n)) names = ('briefdescription','detaileddescription') sub_dict = self.get_specific_nodes(node, names) for n in ('briefdescription','detaileddescription'): if n in sub_dict: self.parse(sub_dict[n]) if self.with_constructor_list: self.make_constructor_list(constructor_nodes, classname) if self.with_attribute_list: self.make_attribute_list(node) sub_list = self.get_specific_subnodes(node, 'includes') if sub_list: self.parse(sub_list[0]) self.add_text(['";', '\n']) names = ['compoundname', 'briefdescription','detaileddescription', 'includes'] self.subnode_parse(node, ignore = names) elif kind in ('file', 'namespace'): nodes = node.getElementsByTagName('sectiondef') for n in nodes: self.parse(n) # now explicitely handle possibly overloaded member functions. if kind in ['class', 'struct','file', 'namespace']: md_nodes = self.get_memberdef_nodes_and_signatures(node, kind) for sig in md_nodes: self.handle_typical_memberdefs(sig, md_nodes[sig]) def do_memberdef(self, node): """Handle cases outside of class, struct, file or namespace. These are now dealt with by `handle_overloaded_memberfunction`. Do these even exist??? """ prot = node.attributes['prot'].value id = node.attributes['id'].value kind = node.attributes['kind'].value tmp = node.parentNode.parentNode.parentNode compdef = tmp.getElementsByTagName('compounddef')[0] cdef_kind = compdef.attributes['kind'].value if cdef_kind in ('file', 'namespace', 'class', 'struct'): # These cases are now handled by `handle_typical_memberdefs` return if prot != 'public': return first = self.get_specific_nodes(node, ('definition', 'name')) name = self.extract_text(first['name']) if name[:8] == 'operator': # Don't handle operators yet. return if not 'definition' in first or kind in ['variable', 'typedef']: return data = self.extract_text(first['definition']) self.add_text('\n') self.add_text(['/* where did this entry come from??? */', '\n']) self.add_text('%feature("docstring") %s "\n%s' % (data, data)) for n in node.childNodes: if n not in first.values(): self.parse(n) self.add_text(['";', '\n']) # MARK: Entry tag handlers (dont print anything meaningful) def do_sectiondef(self, node): kind = node.attributes['kind'].value if kind in ('public-func', 'func', 'user-defined', ''): self.subnode_parse(node) def do_header(self, node): """For a user defined section def a header field is present which should not be printed as such, so we comment it in the output.""" data = self.extract_text(node) self.add_text('\n/*\n %s \n*/\n' % data) # If our immediate sibling is a 'description' node then we # should comment that out also and remove it from the parent # node's children. parent = node.parentNode idx = parent.childNodes.index(node) if len(parent.childNodes) >= idx + 2: nd = parent.childNodes[idx + 2] if nd.nodeName == 'description': nd = parent.removeChild(nd) self.add_text('\n/*') self.subnode_parse(nd) self.add_text('\n*/\n') def do_member(self, node): kind = node.attributes['kind'].value refid = node.attributes['refid'].value if kind == 'function' and refid[:9] == 'namespace': self.subnode_parse(node) def do_doxygenindex(self, node): self.multi = 1 comps = node.getElementsByTagName('compound') for c in comps: refid = c.attributes['refid'].value fname = refid + '.xml' if not os.path.exists(fname): fname = os.path.join(self.my_dir, fname) if not self.quiet: print("parsing file: %s" % fname) p = Doxy2SWIG(fname, with_function_signature = self.with_function_signature, with_type_info = self.with_type_info, with_constructor_list = self.with_constructor_list, with_attribute_list = self.with_attribute_list, with_overloaded_functions = self.with_overloaded_functions, textwidth = self.textwidth, quiet = self.quiet) p.generate() self.pieces.extend(p.pieces)
basler/pypylon
scripts/builddoxy2swig/doxy2swig/doxy2swig.py
Doxy2SWIG.make_attribute_list
python
def make_attribute_list(self, node): atr_nodes = [] for n in self.get_specific_subnodes(node, 'memberdef', recursive=2): if n.attributes['kind'].value == 'variable' and n.attributes['prot'].value == 'public': atr_nodes.append(n) if not atr_nodes: return self.add_text(['\n', 'Attributes', '\n', '----------']) for n in atr_nodes: name = self.extract_text(self.get_specific_subnodes(n, 'name')) self.add_text(['\n* ', '`', name, '`', ' : ']) self.add_text(['`', self.extract_text(self.get_specific_subnodes(n, 'type')), '`']) self.add_text(' \n') restrict = ['briefdescription', 'detaileddescription'] self.subnode_parse(n, pieces=[''], indent=4, restrict=restrict)
Produces the "Attributes" section in class docstrings for public member variables (attributes).
train
https://github.com/basler/pypylon/blob/d3510fa419b1c2b17f3f0b80a5fbb720c7b84008/scripts/builddoxy2swig/doxy2swig/doxy2swig.py#L374-L392
[ "def subnode_parse(self, node, pieces=None, indent=0, ignore=[], restrict=None):\n \"\"\"Parse the subnodes of a given node. Subnodes with tags in the\n `ignore` list are ignored. If pieces is given, use this as target for\n the parse results instead of self.pieces. Indent all lines by the amount\n given in `indent`. Note that the initial content in `pieces` is not\n indented. The final result is in any case added to self.pieces.\"\"\"\n if pieces is not None:\n old_pieces, self.pieces = self.pieces, pieces\n else:\n old_pieces = []\n if type(indent) is int:\n indent = indent * ' '\n if len(indent) > 0:\n pieces = ''.join(self.pieces)\n i_piece = pieces[:len(indent)]\n if self.pieces[-1:] == ['']:\n self.pieces = [pieces[len(indent):]] + ['']\n elif self.pieces != []:\n self.pieces = [pieces[len(indent):]]\n self.indent += len(indent)\n for n in node.childNodes:\n if restrict is not None:\n if n.nodeType == n.ELEMENT_NODE and n.tagName in restrict:\n self.parse(n)\n elif n.nodeType != n.ELEMENT_NODE or n.tagName not in ignore:\n self.parse(n)\n if len(indent) > 0:\n self.pieces = shift(self.pieces, indent, i_piece)\n self.indent -= len(indent)\n old_pieces.extend(self.pieces)\n self.pieces = old_pieces\n", "def get_specific_subnodes(self, node, name, recursive=0):\n \"\"\"Given a node and a name, return a list of child `ELEMENT_NODEs`, that\n have a `tagName` matching the `name`. Search recursively for `recursive`\n levels.\n \"\"\"\n children = [x for x in node.childNodes if x.nodeType == x.ELEMENT_NODE]\n ret = [x for x in children if x.tagName == name]\n if recursive > 0:\n for x in children:\n ret.extend(self.get_specific_subnodes(x, name, recursive-1))\n return ret\n", "def add_text(self, value):\n \"\"\"Adds text corresponding to `value` into `self.pieces`.\"\"\"\n if isinstance(value, (list, tuple)):\n self.pieces.extend(value)\n else:\n self.pieces.append(value)\n", "def extract_text(self, node):\n \"\"\"Return the string representation of the node or list of nodes by parsing the\n subnodes, but returning the result as a string instead of adding it to `self.pieces`.\n Note that this allows extracting text even if the node is in the ignore list.\n \"\"\"\n if not isinstance(node, (list, tuple)):\n node = [node]\n pieces, self.pieces = self.pieces, ['']\n for n in node:\n for sn in n.childNodes:\n self.parse(sn)\n ret = ''.join(self.pieces)\n self.pieces = pieces\n return ret\n" ]
class Doxy2SWIG: """Converts Doxygen generated XML files into a file containing docstrings that can be used by SWIG-1.3.x that have support for feature("docstring"). Once the data is parsed it is stored in self.pieces. """ def __init__(self, src, with_function_signature = False, with_type_info = False, with_constructor_list = False, with_attribute_list = False, with_overloaded_functions = False, textwidth = 80, quiet = False): """Initialize the instance given a source object. `src` can be a file or filename. If you do not want to include function definitions from doxygen then set `include_function_definition` to `False`. This is handy since this allows you to use the swig generated function definition using %feature("autodoc", [0,1]). """ # options: self.with_function_signature = with_function_signature self.with_type_info = with_type_info self.with_constructor_list = with_constructor_list self.with_attribute_list = with_attribute_list self.with_overloaded_functions = with_overloaded_functions self.textwidth = textwidth self.quiet = quiet # state: self.indent = 0 self.listitem = '' self.pieces = [] f = my_open_read(src) self.my_dir = os.path.dirname(f.name) self.xmldoc = minidom.parse(f).documentElement f.close() self.pieces.append('\n// File: %s\n' % os.path.basename(f.name)) self.space_re = re.compile(r'\s+') self.lead_spc = re.compile(r'^(%feature\S+\s+\S+\s*?)"\s+(\S)') self.multi = 0 self.ignores = ['inheritancegraph', 'param', 'listofallmembers', 'innerclass', 'name', 'declname', 'incdepgraph', 'invincdepgraph', 'programlisting', 'type', 'references', 'referencedby', 'location', 'collaborationgraph', 'reimplements', 'reimplementedby', 'derivedcompoundref', 'basecompoundref', 'argsstring', 'definition', 'exceptions'] #self.generics = [] def generate(self): """Parses the file set in the initialization. The resulting data is stored in `self.pieces`. """ self.parse(self.xmldoc) def write(self, fname): o = my_open_write(fname) o.write(''.join(self.pieces)) o.write('\n') o.close() def parse(self, node): """Parse a given node. This function in turn calls the `parse_<nodeType>` functions which handle the respective nodes. """ pm = getattr(self, "parse_%s" % node.__class__.__name__) pm(node) def parse_Document(self, node): self.parse(node.documentElement) def parse_Text(self, node): txt = node.data if txt == ' ': # this can happen when two tags follow in a text, e.g., # " ...</emph> <formaula>$..." etc. # here we want to keep the space. self.add_text(txt) return txt = txt.replace('\\', r'\\') txt = txt.replace('"', r'\"') # ignore pure whitespace m = self.space_re.match(txt) if m and len(m.group()) == len(txt): pass else: self.add_text(txt) def parse_Comment(self, node): """Parse a `COMMENT_NODE`. This does nothing for now.""" return def parse_Element(self, node): """Parse an `ELEMENT_NODE`. This calls specific `do_<tagName>` handers for different elements. If no handler is available the `subnode_parse` method is called. All tagNames specified in `self.ignores` are simply ignored. """ name = node.tagName ignores = self.ignores if name in ignores: return attr = "do_%s" % name if hasattr(self, attr): handlerMethod = getattr(self, attr) handlerMethod(node) else: self.subnode_parse(node) #if name not in self.generics: self.generics.append(name) # MARK: Special format parsing def subnode_parse(self, node, pieces=None, indent=0, ignore=[], restrict=None): """Parse the subnodes of a given node. Subnodes with tags in the `ignore` list are ignored. If pieces is given, use this as target for the parse results instead of self.pieces. Indent all lines by the amount given in `indent`. Note that the initial content in `pieces` is not indented. The final result is in any case added to self.pieces.""" if pieces is not None: old_pieces, self.pieces = self.pieces, pieces else: old_pieces = [] if type(indent) is int: indent = indent * ' ' if len(indent) > 0: pieces = ''.join(self.pieces) i_piece = pieces[:len(indent)] if self.pieces[-1:] == ['']: self.pieces = [pieces[len(indent):]] + [''] elif self.pieces != []: self.pieces = [pieces[len(indent):]] self.indent += len(indent) for n in node.childNodes: if restrict is not None: if n.nodeType == n.ELEMENT_NODE and n.tagName in restrict: self.parse(n) elif n.nodeType != n.ELEMENT_NODE or n.tagName not in ignore: self.parse(n) if len(indent) > 0: self.pieces = shift(self.pieces, indent, i_piece) self.indent -= len(indent) old_pieces.extend(self.pieces) self.pieces = old_pieces def surround_parse(self, node, pre_char, post_char): """Parse the subnodes of a given node. Subnodes with tags in the `ignore` list are ignored. Prepend `pre_char` and append `post_char` to the output in self.pieces.""" self.add_text(pre_char) self.subnode_parse(node) self.add_text(post_char) # MARK: Helper functions def get_specific_subnodes(self, node, name, recursive=0): """Given a node and a name, return a list of child `ELEMENT_NODEs`, that have a `tagName` matching the `name`. Search recursively for `recursive` levels. """ children = [x for x in node.childNodes if x.nodeType == x.ELEMENT_NODE] ret = [x for x in children if x.tagName == name] if recursive > 0: for x in children: ret.extend(self.get_specific_subnodes(x, name, recursive-1)) return ret def get_specific_nodes(self, node, names): """Given a node and a sequence of strings in `names`, return a dictionary containing the names as keys and child `ELEMENT_NODEs`, that have a `tagName` equal to the name. """ nodes = [(x.tagName, x) for x in node.childNodes if x.nodeType == x.ELEMENT_NODE and x.tagName in names] return dict(nodes) def add_text(self, value): """Adds text corresponding to `value` into `self.pieces`.""" if isinstance(value, (list, tuple)): self.pieces.extend(value) else: self.pieces.append(value) def start_new_paragraph(self): """Make sure to create an empty line. This is overridden, if the previous text ends with the special marker ''. In that case, nothing is done. """ if self.pieces[-1:] == ['']: # respect special marker return elif self.pieces == []: # first paragraph, add '\n', override with '' self.pieces = ['\n'] elif self.pieces[-1][-1:] != '\n': # previous line not ended self.pieces.extend([' \n' ,'\n']) else: #default self.pieces.append('\n') def add_line_with_subsequent_indent(self, line, indent=4): """Add line of text and wrap such that subsequent lines are indented by `indent` spaces. """ if isinstance(line, (list, tuple)): line = ''.join(line) line = line.strip() width = self.textwidth-self.indent-indent wrapped_lines = textwrap.wrap(line[indent:], width=width) for i in range(len(wrapped_lines)): if wrapped_lines[i] != '': wrapped_lines[i] = indent * ' ' + wrapped_lines[i] self.pieces.append(line[:indent] + '\n'.join(wrapped_lines)[indent:] + ' \n') def extract_text(self, node): """Return the string representation of the node or list of nodes by parsing the subnodes, but returning the result as a string instead of adding it to `self.pieces`. Note that this allows extracting text even if the node is in the ignore list. """ if not isinstance(node, (list, tuple)): node = [node] pieces, self.pieces = self.pieces, [''] for n in node: for sn in n.childNodes: self.parse(sn) ret = ''.join(self.pieces) self.pieces = pieces return ret def get_function_signature(self, node): """Returns the function signature string for memberdef nodes.""" name = self.extract_text(self.get_specific_subnodes(node, 'name')) if self.with_type_info: argsstring = self.extract_text(self.get_specific_subnodes(node, 'argsstring')) else: argsstring = [] param_id = 1 for n_param in self.get_specific_subnodes(node, 'param'): declname = self.extract_text(self.get_specific_subnodes(n_param, 'declname')) if not declname: declname = 'arg' + str(param_id) defval = self.extract_text(self.get_specific_subnodes(n_param, 'defval')) if defval: defval = '=' + defval argsstring.append(declname + defval) param_id = param_id + 1 argsstring = '(' + ', '.join(argsstring) + ')' type = self.extract_text(self.get_specific_subnodes(node, 'type')) function_definition = name + argsstring if type != '' and type != 'void': function_definition = function_definition + ' -> ' + type return '`' + function_definition + '` ' # MARK: Special parsing tasks (need to be called manually) def make_constructor_list(self, constructor_nodes, classname): """Produces the "Constructors" section and the constructor signatures (since swig does not do so for classes) for class docstrings.""" if constructor_nodes == []: return self.add_text(['\n', 'Constructors', '\n', '------------']) for n in constructor_nodes: self.add_text('\n') self.add_line_with_subsequent_indent('* ' + self.get_function_signature(n)) self.subnode_parse(n, pieces = [], indent=4, ignore=['definition', 'name']) def get_memberdef_nodes_and_signatures(self, node, kind): """Collects the memberdef nodes and corresponding signatures that correspond to public function entries that are at most depth 2 deeper than the current (compounddef) node. Returns a dictionary with function signatures (what swig expects after the %feature directive) as keys, and a list of corresponding memberdef nodes as values.""" sig_dict = {} sig_prefix = '' if kind in ('file', 'namespace'): ns_node = node.getElementsByTagName('innernamespace') if not ns_node and kind == 'namespace': ns_node = node.getElementsByTagName('compoundname') if ns_node: sig_prefix = self.extract_text(ns_node[0]) + '::' elif kind in ('class', 'struct'): # Get the full function name. cn_node = node.getElementsByTagName('compoundname') sig_prefix = self.extract_text(cn_node[0]) + '::' md_nodes = self.get_specific_subnodes(node, 'memberdef', recursive=2) for n in md_nodes: if n.attributes['prot'].value != 'public': continue if n.attributes['kind'].value in ['variable', 'typedef']: continue if not self.get_specific_subnodes(n, 'definition'): continue name = self.extract_text(self.get_specific_subnodes(n, 'name')) if name[:8] == 'operator': continue sig = sig_prefix + name if sig in sig_dict: sig_dict[sig].append(n) else: sig_dict[sig] = [n] return sig_dict def handle_typical_memberdefs_no_overload(self, signature, memberdef_nodes): """Produce standard documentation for memberdef_nodes.""" for n in memberdef_nodes: self.add_text(['\n', '%feature("docstring") ', signature, ' "', '\n']) if self.with_function_signature: self.add_line_with_subsequent_indent(self.get_function_signature(n)) self.subnode_parse(n, pieces=[], ignore=['definition', 'name']) self.add_text(['";', '\n']) def handle_typical_memberdefs(self, signature, memberdef_nodes): """Produces docstring entries containing an "Overloaded function" section with the documentation for each overload, if the function is overloaded and self.with_overloaded_functions is set. Else, produce normal documentation. """ if len(memberdef_nodes) == 1 or not self.with_overloaded_functions: self.handle_typical_memberdefs_no_overload(signature, memberdef_nodes) return self.add_text(['\n', '%feature("docstring") ', signature, ' "', '\n']) if self.with_function_signature: for n in memberdef_nodes: self.add_line_with_subsequent_indent(self.get_function_signature(n)) self.add_text('\n') self.add_text(['Overloaded function', '\n', '-------------------']) for n in memberdef_nodes: self.add_text('\n') self.add_line_with_subsequent_indent('* ' + self.get_function_signature(n)) self.subnode_parse(n, pieces=[], indent=4, ignore=['definition', 'name']) self.add_text(['";', '\n']) # MARK: Tag handlers def do_linebreak(self, node): self.add_text(' ') def do_ndash(self, node): self.add_text('--') def do_mdash(self, node): self.add_text('---') def do_emphasis(self, node): self.surround_parse(node, '*', '*') def do_bold(self, node): self.surround_parse(node, '**', '**') def do_computeroutput(self, node): self.surround_parse(node, '`', '`') def do_heading(self, node): self.start_new_paragraph() pieces, self.pieces = self.pieces, [''] level = int(node.attributes['level'].value) self.subnode_parse(node) if level == 1: self.pieces.insert(0, '\n') self.add_text(['\n', len(''.join(self.pieces).strip()) * '=']) elif level == 2: self.add_text(['\n', len(''.join(self.pieces).strip()) * '-']) elif level >= 3: self.pieces.insert(0, level * '#' + ' ') # make following text have no gap to the heading: pieces.extend([''.join(self.pieces) + ' \n', '']) self.pieces = pieces def do_verbatim(self, node): self.start_new_paragraph() self.subnode_parse(node, pieces=[''], indent=4) def do_blockquote(self, node): self.start_new_paragraph() self.subnode_parse(node, pieces=[''], indent='> ') def do_hruler(self, node): self.start_new_paragraph() self.add_text('* * * * * \n') def do_includes(self, node): self.add_text('\nC++ includes: ') self.subnode_parse(node) self.add_text('\n') # MARK: Para tag handler def do_para(self, node): """This is the only place where text wrapping is automatically performed. Generally, this function parses the node (locally), wraps the text, and then adds the result to self.pieces. However, it may be convenient to allow the previous content of self.pieces to be included in the text wrapping. For this, use the following *convention*: If self.pieces ends with '', treat the _previous_ entry as part of the current paragraph. Else, insert new-line and start a new paragraph and "wrapping context". Paragraphs always end with ' \n', but if the parsed content ends with the special symbol '', this is passed on. """ if self.pieces[-1:] == ['']: pieces, self.pieces = self.pieces[:-2], self.pieces[-2:-1] else: self.add_text('\n') pieces, self.pieces = self.pieces, [''] self.subnode_parse(node) dont_end_paragraph = self.pieces[-1:] == [''] # Now do the text wrapping: width = self.textwidth - self.indent wrapped_para = [] for line in ''.join(self.pieces).splitlines(): keep_markdown_newline = line[-2:] == ' ' w_line = textwrap.wrap(line, width=width, break_long_words=False) if w_line == []: w_line = [''] if keep_markdown_newline: w_line[-1] = w_line[-1] + ' ' for wl in w_line: wrapped_para.append(wl + '\n') if wrapped_para: if wrapped_para[-1][-3:] != ' \n': wrapped_para[-1] = wrapped_para[-1][:-1] + ' \n' if dont_end_paragraph: wrapped_para.append('') pieces.extend(wrapped_para) self.pieces = pieces # MARK: List tag handlers def do_itemizedlist(self, node): if self.listitem == '': self.start_new_paragraph() elif self.pieces != [] and self.pieces[-1:] != ['']: self.add_text('\n') listitem = self.listitem if self.listitem in ['*', '-']: self.listitem = '-' else: self.listitem = '*' self.subnode_parse(node) self.listitem = listitem def do_orderedlist(self, node): if self.listitem == '': self.start_new_paragraph() elif self.pieces != [] and self.pieces[-1:] != ['']: self.add_text('\n') listitem = self.listitem self.listitem = 0 self.subnode_parse(node) self.listitem = listitem def do_listitem(self, node): try: self.listitem = int(self.listitem) + 1 item = str(self.listitem) + '. ' except: item = str(self.listitem) + ' ' self.subnode_parse(node, item, indent=4) # MARK: Parameter list tag handlers def do_parameterlist(self, node): self.start_new_paragraph() text = 'unknown' for key, val in node.attributes.items(): if key == 'kind': if val == 'param': text = 'Parameters' elif val == 'exception': text = 'Exceptions' elif val == 'retval': text = 'Returns' else: text = val break if self.indent == 0: self.add_text([text, '\n', len(text) * '-', '\n']) else: self.add_text([text, ': \n']) self.subnode_parse(node) def do_parameteritem(self, node): self.subnode_parse(node, pieces=['* ', '']) def do_parameternamelist(self, node): self.subnode_parse(node) self.add_text([' :', ' \n']) def do_parametername(self, node): if self.pieces != [] and self.pieces != ['* ', '']: self.add_text(', ') data = self.extract_text(node) self.add_text(['`', data, '`']) def do_parameterdescription(self, node): self.subnode_parse(node, pieces=[''], indent=4) # MARK: Section tag handler def do_simplesect(self, node): kind = node.attributes['kind'].value if kind in ('date', 'rcs', 'version'): return self.start_new_paragraph() if kind == 'warning': self.subnode_parse(node, pieces=['**Warning**: ',''], indent=4) elif kind == 'see': self.subnode_parse(node, pieces=['See also: ',''], indent=4) elif kind == 'return': if self.indent == 0: pieces = ['Returns', '\n', len('Returns') * '-', '\n', ''] else: pieces = ['Returns:', '\n', ''] self.subnode_parse(node, pieces=pieces) else: self.subnode_parse(node, pieces=[kind + ': ',''], indent=4) # MARK: %feature("docstring") producing tag handlers def do_compounddef(self, node): """This produces %feature("docstring") entries for classes, and handles class, namespace and file memberdef entries specially to allow for overloaded functions. For other cases, passes parsing on to standard handlers (which may produce unexpected results). """ kind = node.attributes['kind'].value if kind in ('class', 'struct'): prot = node.attributes['prot'].value if prot != 'public': return self.add_text('\n\n') classdefn = self.extract_text(self.get_specific_subnodes(node, 'compoundname')) classname = classdefn.split('::')[-1] self.add_text('%%feature("docstring") %s "\n' % classdefn) if self.with_constructor_list: constructor_nodes = [] for n in self.get_specific_subnodes(node, 'memberdef', recursive=2): if n.attributes['prot'].value == 'public': if self.extract_text(self.get_specific_subnodes(n, 'definition')) == classdefn + '::' + classname: constructor_nodes.append(n) for n in constructor_nodes: self.add_line_with_subsequent_indent(self.get_function_signature(n)) names = ('briefdescription','detaileddescription') sub_dict = self.get_specific_nodes(node, names) for n in ('briefdescription','detaileddescription'): if n in sub_dict: self.parse(sub_dict[n]) if self.with_constructor_list: self.make_constructor_list(constructor_nodes, classname) if self.with_attribute_list: self.make_attribute_list(node) sub_list = self.get_specific_subnodes(node, 'includes') if sub_list: self.parse(sub_list[0]) self.add_text(['";', '\n']) names = ['compoundname', 'briefdescription','detaileddescription', 'includes'] self.subnode_parse(node, ignore = names) elif kind in ('file', 'namespace'): nodes = node.getElementsByTagName('sectiondef') for n in nodes: self.parse(n) # now explicitely handle possibly overloaded member functions. if kind in ['class', 'struct','file', 'namespace']: md_nodes = self.get_memberdef_nodes_and_signatures(node, kind) for sig in md_nodes: self.handle_typical_memberdefs(sig, md_nodes[sig]) def do_memberdef(self, node): """Handle cases outside of class, struct, file or namespace. These are now dealt with by `handle_overloaded_memberfunction`. Do these even exist??? """ prot = node.attributes['prot'].value id = node.attributes['id'].value kind = node.attributes['kind'].value tmp = node.parentNode.parentNode.parentNode compdef = tmp.getElementsByTagName('compounddef')[0] cdef_kind = compdef.attributes['kind'].value if cdef_kind in ('file', 'namespace', 'class', 'struct'): # These cases are now handled by `handle_typical_memberdefs` return if prot != 'public': return first = self.get_specific_nodes(node, ('definition', 'name')) name = self.extract_text(first['name']) if name[:8] == 'operator': # Don't handle operators yet. return if not 'definition' in first or kind in ['variable', 'typedef']: return data = self.extract_text(first['definition']) self.add_text('\n') self.add_text(['/* where did this entry come from??? */', '\n']) self.add_text('%feature("docstring") %s "\n%s' % (data, data)) for n in node.childNodes: if n not in first.values(): self.parse(n) self.add_text(['";', '\n']) # MARK: Entry tag handlers (dont print anything meaningful) def do_sectiondef(self, node): kind = node.attributes['kind'].value if kind in ('public-func', 'func', 'user-defined', ''): self.subnode_parse(node) def do_header(self, node): """For a user defined section def a header field is present which should not be printed as such, so we comment it in the output.""" data = self.extract_text(node) self.add_text('\n/*\n %s \n*/\n' % data) # If our immediate sibling is a 'description' node then we # should comment that out also and remove it from the parent # node's children. parent = node.parentNode idx = parent.childNodes.index(node) if len(parent.childNodes) >= idx + 2: nd = parent.childNodes[idx + 2] if nd.nodeName == 'description': nd = parent.removeChild(nd) self.add_text('\n/*') self.subnode_parse(nd) self.add_text('\n*/\n') def do_member(self, node): kind = node.attributes['kind'].value refid = node.attributes['refid'].value if kind == 'function' and refid[:9] == 'namespace': self.subnode_parse(node) def do_doxygenindex(self, node): self.multi = 1 comps = node.getElementsByTagName('compound') for c in comps: refid = c.attributes['refid'].value fname = refid + '.xml' if not os.path.exists(fname): fname = os.path.join(self.my_dir, fname) if not self.quiet: print("parsing file: %s" % fname) p = Doxy2SWIG(fname, with_function_signature = self.with_function_signature, with_type_info = self.with_type_info, with_constructor_list = self.with_constructor_list, with_attribute_list = self.with_attribute_list, with_overloaded_functions = self.with_overloaded_functions, textwidth = self.textwidth, quiet = self.quiet) p.generate() self.pieces.extend(p.pieces)
basler/pypylon
scripts/builddoxy2swig/doxy2swig/doxy2swig.py
Doxy2SWIG.get_memberdef_nodes_and_signatures
python
def get_memberdef_nodes_and_signatures(self, node, kind): sig_dict = {} sig_prefix = '' if kind in ('file', 'namespace'): ns_node = node.getElementsByTagName('innernamespace') if not ns_node and kind == 'namespace': ns_node = node.getElementsByTagName('compoundname') if ns_node: sig_prefix = self.extract_text(ns_node[0]) + '::' elif kind in ('class', 'struct'): # Get the full function name. cn_node = node.getElementsByTagName('compoundname') sig_prefix = self.extract_text(cn_node[0]) + '::' md_nodes = self.get_specific_subnodes(node, 'memberdef', recursive=2) for n in md_nodes: if n.attributes['prot'].value != 'public': continue if n.attributes['kind'].value in ['variable', 'typedef']: continue if not self.get_specific_subnodes(n, 'definition'): continue name = self.extract_text(self.get_specific_subnodes(n, 'name')) if name[:8] == 'operator': continue sig = sig_prefix + name if sig in sig_dict: sig_dict[sig].append(n) else: sig_dict[sig] = [n] return sig_dict
Collects the memberdef nodes and corresponding signatures that correspond to public function entries that are at most depth 2 deeper than the current (compounddef) node. Returns a dictionary with function signatures (what swig expects after the %feature directive) as keys, and a list of corresponding memberdef nodes as values.
train
https://github.com/basler/pypylon/blob/d3510fa419b1c2b17f3f0b80a5fbb720c7b84008/scripts/builddoxy2swig/doxy2swig/doxy2swig.py#L394-L429
[ "def get_specific_subnodes(self, node, name, recursive=0):\n \"\"\"Given a node and a name, return a list of child `ELEMENT_NODEs`, that\n have a `tagName` matching the `name`. Search recursively for `recursive`\n levels.\n \"\"\"\n children = [x for x in node.childNodes if x.nodeType == x.ELEMENT_NODE]\n ret = [x for x in children if x.tagName == name]\n if recursive > 0:\n for x in children:\n ret.extend(self.get_specific_subnodes(x, name, recursive-1))\n return ret\n", "def extract_text(self, node):\n \"\"\"Return the string representation of the node or list of nodes by parsing the\n subnodes, but returning the result as a string instead of adding it to `self.pieces`.\n Note that this allows extracting text even if the node is in the ignore list.\n \"\"\"\n if not isinstance(node, (list, tuple)):\n node = [node]\n pieces, self.pieces = self.pieces, ['']\n for n in node:\n for sn in n.childNodes:\n self.parse(sn)\n ret = ''.join(self.pieces)\n self.pieces = pieces\n return ret\n" ]
class Doxy2SWIG: """Converts Doxygen generated XML files into a file containing docstrings that can be used by SWIG-1.3.x that have support for feature("docstring"). Once the data is parsed it is stored in self.pieces. """ def __init__(self, src, with_function_signature = False, with_type_info = False, with_constructor_list = False, with_attribute_list = False, with_overloaded_functions = False, textwidth = 80, quiet = False): """Initialize the instance given a source object. `src` can be a file or filename. If you do not want to include function definitions from doxygen then set `include_function_definition` to `False`. This is handy since this allows you to use the swig generated function definition using %feature("autodoc", [0,1]). """ # options: self.with_function_signature = with_function_signature self.with_type_info = with_type_info self.with_constructor_list = with_constructor_list self.with_attribute_list = with_attribute_list self.with_overloaded_functions = with_overloaded_functions self.textwidth = textwidth self.quiet = quiet # state: self.indent = 0 self.listitem = '' self.pieces = [] f = my_open_read(src) self.my_dir = os.path.dirname(f.name) self.xmldoc = minidom.parse(f).documentElement f.close() self.pieces.append('\n// File: %s\n' % os.path.basename(f.name)) self.space_re = re.compile(r'\s+') self.lead_spc = re.compile(r'^(%feature\S+\s+\S+\s*?)"\s+(\S)') self.multi = 0 self.ignores = ['inheritancegraph', 'param', 'listofallmembers', 'innerclass', 'name', 'declname', 'incdepgraph', 'invincdepgraph', 'programlisting', 'type', 'references', 'referencedby', 'location', 'collaborationgraph', 'reimplements', 'reimplementedby', 'derivedcompoundref', 'basecompoundref', 'argsstring', 'definition', 'exceptions'] #self.generics = [] def generate(self): """Parses the file set in the initialization. The resulting data is stored in `self.pieces`. """ self.parse(self.xmldoc) def write(self, fname): o = my_open_write(fname) o.write(''.join(self.pieces)) o.write('\n') o.close() def parse(self, node): """Parse a given node. This function in turn calls the `parse_<nodeType>` functions which handle the respective nodes. """ pm = getattr(self, "parse_%s" % node.__class__.__name__) pm(node) def parse_Document(self, node): self.parse(node.documentElement) def parse_Text(self, node): txt = node.data if txt == ' ': # this can happen when two tags follow in a text, e.g., # " ...</emph> <formaula>$..." etc. # here we want to keep the space. self.add_text(txt) return txt = txt.replace('\\', r'\\') txt = txt.replace('"', r'\"') # ignore pure whitespace m = self.space_re.match(txt) if m and len(m.group()) == len(txt): pass else: self.add_text(txt) def parse_Comment(self, node): """Parse a `COMMENT_NODE`. This does nothing for now.""" return def parse_Element(self, node): """Parse an `ELEMENT_NODE`. This calls specific `do_<tagName>` handers for different elements. If no handler is available the `subnode_parse` method is called. All tagNames specified in `self.ignores` are simply ignored. """ name = node.tagName ignores = self.ignores if name in ignores: return attr = "do_%s" % name if hasattr(self, attr): handlerMethod = getattr(self, attr) handlerMethod(node) else: self.subnode_parse(node) #if name not in self.generics: self.generics.append(name) # MARK: Special format parsing def subnode_parse(self, node, pieces=None, indent=0, ignore=[], restrict=None): """Parse the subnodes of a given node. Subnodes with tags in the `ignore` list are ignored. If pieces is given, use this as target for the parse results instead of self.pieces. Indent all lines by the amount given in `indent`. Note that the initial content in `pieces` is not indented. The final result is in any case added to self.pieces.""" if pieces is not None: old_pieces, self.pieces = self.pieces, pieces else: old_pieces = [] if type(indent) is int: indent = indent * ' ' if len(indent) > 0: pieces = ''.join(self.pieces) i_piece = pieces[:len(indent)] if self.pieces[-1:] == ['']: self.pieces = [pieces[len(indent):]] + [''] elif self.pieces != []: self.pieces = [pieces[len(indent):]] self.indent += len(indent) for n in node.childNodes: if restrict is not None: if n.nodeType == n.ELEMENT_NODE and n.tagName in restrict: self.parse(n) elif n.nodeType != n.ELEMENT_NODE or n.tagName not in ignore: self.parse(n) if len(indent) > 0: self.pieces = shift(self.pieces, indent, i_piece) self.indent -= len(indent) old_pieces.extend(self.pieces) self.pieces = old_pieces def surround_parse(self, node, pre_char, post_char): """Parse the subnodes of a given node. Subnodes with tags in the `ignore` list are ignored. Prepend `pre_char` and append `post_char` to the output in self.pieces.""" self.add_text(pre_char) self.subnode_parse(node) self.add_text(post_char) # MARK: Helper functions def get_specific_subnodes(self, node, name, recursive=0): """Given a node and a name, return a list of child `ELEMENT_NODEs`, that have a `tagName` matching the `name`. Search recursively for `recursive` levels. """ children = [x for x in node.childNodes if x.nodeType == x.ELEMENT_NODE] ret = [x for x in children if x.tagName == name] if recursive > 0: for x in children: ret.extend(self.get_specific_subnodes(x, name, recursive-1)) return ret def get_specific_nodes(self, node, names): """Given a node and a sequence of strings in `names`, return a dictionary containing the names as keys and child `ELEMENT_NODEs`, that have a `tagName` equal to the name. """ nodes = [(x.tagName, x) for x in node.childNodes if x.nodeType == x.ELEMENT_NODE and x.tagName in names] return dict(nodes) def add_text(self, value): """Adds text corresponding to `value` into `self.pieces`.""" if isinstance(value, (list, tuple)): self.pieces.extend(value) else: self.pieces.append(value) def start_new_paragraph(self): """Make sure to create an empty line. This is overridden, if the previous text ends with the special marker ''. In that case, nothing is done. """ if self.pieces[-1:] == ['']: # respect special marker return elif self.pieces == []: # first paragraph, add '\n', override with '' self.pieces = ['\n'] elif self.pieces[-1][-1:] != '\n': # previous line not ended self.pieces.extend([' \n' ,'\n']) else: #default self.pieces.append('\n') def add_line_with_subsequent_indent(self, line, indent=4): """Add line of text and wrap such that subsequent lines are indented by `indent` spaces. """ if isinstance(line, (list, tuple)): line = ''.join(line) line = line.strip() width = self.textwidth-self.indent-indent wrapped_lines = textwrap.wrap(line[indent:], width=width) for i in range(len(wrapped_lines)): if wrapped_lines[i] != '': wrapped_lines[i] = indent * ' ' + wrapped_lines[i] self.pieces.append(line[:indent] + '\n'.join(wrapped_lines)[indent:] + ' \n') def extract_text(self, node): """Return the string representation of the node or list of nodes by parsing the subnodes, but returning the result as a string instead of adding it to `self.pieces`. Note that this allows extracting text even if the node is in the ignore list. """ if not isinstance(node, (list, tuple)): node = [node] pieces, self.pieces = self.pieces, [''] for n in node: for sn in n.childNodes: self.parse(sn) ret = ''.join(self.pieces) self.pieces = pieces return ret def get_function_signature(self, node): """Returns the function signature string for memberdef nodes.""" name = self.extract_text(self.get_specific_subnodes(node, 'name')) if self.with_type_info: argsstring = self.extract_text(self.get_specific_subnodes(node, 'argsstring')) else: argsstring = [] param_id = 1 for n_param in self.get_specific_subnodes(node, 'param'): declname = self.extract_text(self.get_specific_subnodes(n_param, 'declname')) if not declname: declname = 'arg' + str(param_id) defval = self.extract_text(self.get_specific_subnodes(n_param, 'defval')) if defval: defval = '=' + defval argsstring.append(declname + defval) param_id = param_id + 1 argsstring = '(' + ', '.join(argsstring) + ')' type = self.extract_text(self.get_specific_subnodes(node, 'type')) function_definition = name + argsstring if type != '' and type != 'void': function_definition = function_definition + ' -> ' + type return '`' + function_definition + '` ' # MARK: Special parsing tasks (need to be called manually) def make_constructor_list(self, constructor_nodes, classname): """Produces the "Constructors" section and the constructor signatures (since swig does not do so for classes) for class docstrings.""" if constructor_nodes == []: return self.add_text(['\n', 'Constructors', '\n', '------------']) for n in constructor_nodes: self.add_text('\n') self.add_line_with_subsequent_indent('* ' + self.get_function_signature(n)) self.subnode_parse(n, pieces = [], indent=4, ignore=['definition', 'name']) def make_attribute_list(self, node): """Produces the "Attributes" section in class docstrings for public member variables (attributes). """ atr_nodes = [] for n in self.get_specific_subnodes(node, 'memberdef', recursive=2): if n.attributes['kind'].value == 'variable' and n.attributes['prot'].value == 'public': atr_nodes.append(n) if not atr_nodes: return self.add_text(['\n', 'Attributes', '\n', '----------']) for n in atr_nodes: name = self.extract_text(self.get_specific_subnodes(n, 'name')) self.add_text(['\n* ', '`', name, '`', ' : ']) self.add_text(['`', self.extract_text(self.get_specific_subnodes(n, 'type')), '`']) self.add_text(' \n') restrict = ['briefdescription', 'detaileddescription'] self.subnode_parse(n, pieces=[''], indent=4, restrict=restrict) def handle_typical_memberdefs_no_overload(self, signature, memberdef_nodes): """Produce standard documentation for memberdef_nodes.""" for n in memberdef_nodes: self.add_text(['\n', '%feature("docstring") ', signature, ' "', '\n']) if self.with_function_signature: self.add_line_with_subsequent_indent(self.get_function_signature(n)) self.subnode_parse(n, pieces=[], ignore=['definition', 'name']) self.add_text(['";', '\n']) def handle_typical_memberdefs(self, signature, memberdef_nodes): """Produces docstring entries containing an "Overloaded function" section with the documentation for each overload, if the function is overloaded and self.with_overloaded_functions is set. Else, produce normal documentation. """ if len(memberdef_nodes) == 1 or not self.with_overloaded_functions: self.handle_typical_memberdefs_no_overload(signature, memberdef_nodes) return self.add_text(['\n', '%feature("docstring") ', signature, ' "', '\n']) if self.with_function_signature: for n in memberdef_nodes: self.add_line_with_subsequent_indent(self.get_function_signature(n)) self.add_text('\n') self.add_text(['Overloaded function', '\n', '-------------------']) for n in memberdef_nodes: self.add_text('\n') self.add_line_with_subsequent_indent('* ' + self.get_function_signature(n)) self.subnode_parse(n, pieces=[], indent=4, ignore=['definition', 'name']) self.add_text(['";', '\n']) # MARK: Tag handlers def do_linebreak(self, node): self.add_text(' ') def do_ndash(self, node): self.add_text('--') def do_mdash(self, node): self.add_text('---') def do_emphasis(self, node): self.surround_parse(node, '*', '*') def do_bold(self, node): self.surround_parse(node, '**', '**') def do_computeroutput(self, node): self.surround_parse(node, '`', '`') def do_heading(self, node): self.start_new_paragraph() pieces, self.pieces = self.pieces, [''] level = int(node.attributes['level'].value) self.subnode_parse(node) if level == 1: self.pieces.insert(0, '\n') self.add_text(['\n', len(''.join(self.pieces).strip()) * '=']) elif level == 2: self.add_text(['\n', len(''.join(self.pieces).strip()) * '-']) elif level >= 3: self.pieces.insert(0, level * '#' + ' ') # make following text have no gap to the heading: pieces.extend([''.join(self.pieces) + ' \n', '']) self.pieces = pieces def do_verbatim(self, node): self.start_new_paragraph() self.subnode_parse(node, pieces=[''], indent=4) def do_blockquote(self, node): self.start_new_paragraph() self.subnode_parse(node, pieces=[''], indent='> ') def do_hruler(self, node): self.start_new_paragraph() self.add_text('* * * * * \n') def do_includes(self, node): self.add_text('\nC++ includes: ') self.subnode_parse(node) self.add_text('\n') # MARK: Para tag handler def do_para(self, node): """This is the only place where text wrapping is automatically performed. Generally, this function parses the node (locally), wraps the text, and then adds the result to self.pieces. However, it may be convenient to allow the previous content of self.pieces to be included in the text wrapping. For this, use the following *convention*: If self.pieces ends with '', treat the _previous_ entry as part of the current paragraph. Else, insert new-line and start a new paragraph and "wrapping context". Paragraphs always end with ' \n', but if the parsed content ends with the special symbol '', this is passed on. """ if self.pieces[-1:] == ['']: pieces, self.pieces = self.pieces[:-2], self.pieces[-2:-1] else: self.add_text('\n') pieces, self.pieces = self.pieces, [''] self.subnode_parse(node) dont_end_paragraph = self.pieces[-1:] == [''] # Now do the text wrapping: width = self.textwidth - self.indent wrapped_para = [] for line in ''.join(self.pieces).splitlines(): keep_markdown_newline = line[-2:] == ' ' w_line = textwrap.wrap(line, width=width, break_long_words=False) if w_line == []: w_line = [''] if keep_markdown_newline: w_line[-1] = w_line[-1] + ' ' for wl in w_line: wrapped_para.append(wl + '\n') if wrapped_para: if wrapped_para[-1][-3:] != ' \n': wrapped_para[-1] = wrapped_para[-1][:-1] + ' \n' if dont_end_paragraph: wrapped_para.append('') pieces.extend(wrapped_para) self.pieces = pieces # MARK: List tag handlers def do_itemizedlist(self, node): if self.listitem == '': self.start_new_paragraph() elif self.pieces != [] and self.pieces[-1:] != ['']: self.add_text('\n') listitem = self.listitem if self.listitem in ['*', '-']: self.listitem = '-' else: self.listitem = '*' self.subnode_parse(node) self.listitem = listitem def do_orderedlist(self, node): if self.listitem == '': self.start_new_paragraph() elif self.pieces != [] and self.pieces[-1:] != ['']: self.add_text('\n') listitem = self.listitem self.listitem = 0 self.subnode_parse(node) self.listitem = listitem def do_listitem(self, node): try: self.listitem = int(self.listitem) + 1 item = str(self.listitem) + '. ' except: item = str(self.listitem) + ' ' self.subnode_parse(node, item, indent=4) # MARK: Parameter list tag handlers def do_parameterlist(self, node): self.start_new_paragraph() text = 'unknown' for key, val in node.attributes.items(): if key == 'kind': if val == 'param': text = 'Parameters' elif val == 'exception': text = 'Exceptions' elif val == 'retval': text = 'Returns' else: text = val break if self.indent == 0: self.add_text([text, '\n', len(text) * '-', '\n']) else: self.add_text([text, ': \n']) self.subnode_parse(node) def do_parameteritem(self, node): self.subnode_parse(node, pieces=['* ', '']) def do_parameternamelist(self, node): self.subnode_parse(node) self.add_text([' :', ' \n']) def do_parametername(self, node): if self.pieces != [] and self.pieces != ['* ', '']: self.add_text(', ') data = self.extract_text(node) self.add_text(['`', data, '`']) def do_parameterdescription(self, node): self.subnode_parse(node, pieces=[''], indent=4) # MARK: Section tag handler def do_simplesect(self, node): kind = node.attributes['kind'].value if kind in ('date', 'rcs', 'version'): return self.start_new_paragraph() if kind == 'warning': self.subnode_parse(node, pieces=['**Warning**: ',''], indent=4) elif kind == 'see': self.subnode_parse(node, pieces=['See also: ',''], indent=4) elif kind == 'return': if self.indent == 0: pieces = ['Returns', '\n', len('Returns') * '-', '\n', ''] else: pieces = ['Returns:', '\n', ''] self.subnode_parse(node, pieces=pieces) else: self.subnode_parse(node, pieces=[kind + ': ',''], indent=4) # MARK: %feature("docstring") producing tag handlers def do_compounddef(self, node): """This produces %feature("docstring") entries for classes, and handles class, namespace and file memberdef entries specially to allow for overloaded functions. For other cases, passes parsing on to standard handlers (which may produce unexpected results). """ kind = node.attributes['kind'].value if kind in ('class', 'struct'): prot = node.attributes['prot'].value if prot != 'public': return self.add_text('\n\n') classdefn = self.extract_text(self.get_specific_subnodes(node, 'compoundname')) classname = classdefn.split('::')[-1] self.add_text('%%feature("docstring") %s "\n' % classdefn) if self.with_constructor_list: constructor_nodes = [] for n in self.get_specific_subnodes(node, 'memberdef', recursive=2): if n.attributes['prot'].value == 'public': if self.extract_text(self.get_specific_subnodes(n, 'definition')) == classdefn + '::' + classname: constructor_nodes.append(n) for n in constructor_nodes: self.add_line_with_subsequent_indent(self.get_function_signature(n)) names = ('briefdescription','detaileddescription') sub_dict = self.get_specific_nodes(node, names) for n in ('briefdescription','detaileddescription'): if n in sub_dict: self.parse(sub_dict[n]) if self.with_constructor_list: self.make_constructor_list(constructor_nodes, classname) if self.with_attribute_list: self.make_attribute_list(node) sub_list = self.get_specific_subnodes(node, 'includes') if sub_list: self.parse(sub_list[0]) self.add_text(['";', '\n']) names = ['compoundname', 'briefdescription','detaileddescription', 'includes'] self.subnode_parse(node, ignore = names) elif kind in ('file', 'namespace'): nodes = node.getElementsByTagName('sectiondef') for n in nodes: self.parse(n) # now explicitely handle possibly overloaded member functions. if kind in ['class', 'struct','file', 'namespace']: md_nodes = self.get_memberdef_nodes_and_signatures(node, kind) for sig in md_nodes: self.handle_typical_memberdefs(sig, md_nodes[sig]) def do_memberdef(self, node): """Handle cases outside of class, struct, file or namespace. These are now dealt with by `handle_overloaded_memberfunction`. Do these even exist??? """ prot = node.attributes['prot'].value id = node.attributes['id'].value kind = node.attributes['kind'].value tmp = node.parentNode.parentNode.parentNode compdef = tmp.getElementsByTagName('compounddef')[0] cdef_kind = compdef.attributes['kind'].value if cdef_kind in ('file', 'namespace', 'class', 'struct'): # These cases are now handled by `handle_typical_memberdefs` return if prot != 'public': return first = self.get_specific_nodes(node, ('definition', 'name')) name = self.extract_text(first['name']) if name[:8] == 'operator': # Don't handle operators yet. return if not 'definition' in first or kind in ['variable', 'typedef']: return data = self.extract_text(first['definition']) self.add_text('\n') self.add_text(['/* where did this entry come from??? */', '\n']) self.add_text('%feature("docstring") %s "\n%s' % (data, data)) for n in node.childNodes: if n not in first.values(): self.parse(n) self.add_text(['";', '\n']) # MARK: Entry tag handlers (dont print anything meaningful) def do_sectiondef(self, node): kind = node.attributes['kind'].value if kind in ('public-func', 'func', 'user-defined', ''): self.subnode_parse(node) def do_header(self, node): """For a user defined section def a header field is present which should not be printed as such, so we comment it in the output.""" data = self.extract_text(node) self.add_text('\n/*\n %s \n*/\n' % data) # If our immediate sibling is a 'description' node then we # should comment that out also and remove it from the parent # node's children. parent = node.parentNode idx = parent.childNodes.index(node) if len(parent.childNodes) >= idx + 2: nd = parent.childNodes[idx + 2] if nd.nodeName == 'description': nd = parent.removeChild(nd) self.add_text('\n/*') self.subnode_parse(nd) self.add_text('\n*/\n') def do_member(self, node): kind = node.attributes['kind'].value refid = node.attributes['refid'].value if kind == 'function' and refid[:9] == 'namespace': self.subnode_parse(node) def do_doxygenindex(self, node): self.multi = 1 comps = node.getElementsByTagName('compound') for c in comps: refid = c.attributes['refid'].value fname = refid + '.xml' if not os.path.exists(fname): fname = os.path.join(self.my_dir, fname) if not self.quiet: print("parsing file: %s" % fname) p = Doxy2SWIG(fname, with_function_signature = self.with_function_signature, with_type_info = self.with_type_info, with_constructor_list = self.with_constructor_list, with_attribute_list = self.with_attribute_list, with_overloaded_functions = self.with_overloaded_functions, textwidth = self.textwidth, quiet = self.quiet) p.generate() self.pieces.extend(p.pieces)
basler/pypylon
scripts/builddoxy2swig/doxy2swig/doxy2swig.py
Doxy2SWIG.handle_typical_memberdefs_no_overload
python
def handle_typical_memberdefs_no_overload(self, signature, memberdef_nodes): for n in memberdef_nodes: self.add_text(['\n', '%feature("docstring") ', signature, ' "', '\n']) if self.with_function_signature: self.add_line_with_subsequent_indent(self.get_function_signature(n)) self.subnode_parse(n, pieces=[], ignore=['definition', 'name']) self.add_text(['";', '\n'])
Produce standard documentation for memberdef_nodes.
train
https://github.com/basler/pypylon/blob/d3510fa419b1c2b17f3f0b80a5fbb720c7b84008/scripts/builddoxy2swig/doxy2swig/doxy2swig.py#L431-L438
[ "def subnode_parse(self, node, pieces=None, indent=0, ignore=[], restrict=None):\n \"\"\"Parse the subnodes of a given node. Subnodes with tags in the\n `ignore` list are ignored. If pieces is given, use this as target for\n the parse results instead of self.pieces. Indent all lines by the amount\n given in `indent`. Note that the initial content in `pieces` is not\n indented. The final result is in any case added to self.pieces.\"\"\"\n if pieces is not None:\n old_pieces, self.pieces = self.pieces, pieces\n else:\n old_pieces = []\n if type(indent) is int:\n indent = indent * ' '\n if len(indent) > 0:\n pieces = ''.join(self.pieces)\n i_piece = pieces[:len(indent)]\n if self.pieces[-1:] == ['']:\n self.pieces = [pieces[len(indent):]] + ['']\n elif self.pieces != []:\n self.pieces = [pieces[len(indent):]]\n self.indent += len(indent)\n for n in node.childNodes:\n if restrict is not None:\n if n.nodeType == n.ELEMENT_NODE and n.tagName in restrict:\n self.parse(n)\n elif n.nodeType != n.ELEMENT_NODE or n.tagName not in ignore:\n self.parse(n)\n if len(indent) > 0:\n self.pieces = shift(self.pieces, indent, i_piece)\n self.indent -= len(indent)\n old_pieces.extend(self.pieces)\n self.pieces = old_pieces\n", "def add_text(self, value):\n \"\"\"Adds text corresponding to `value` into `self.pieces`.\"\"\"\n if isinstance(value, (list, tuple)):\n self.pieces.extend(value)\n else:\n self.pieces.append(value)\n", "def add_line_with_subsequent_indent(self, line, indent=4):\n \"\"\"Add line of text and wrap such that subsequent lines are indented\n by `indent` spaces.\n \"\"\"\n if isinstance(line, (list, tuple)):\n line = ''.join(line)\n line = line.strip()\n width = self.textwidth-self.indent-indent\n wrapped_lines = textwrap.wrap(line[indent:], width=width)\n for i in range(len(wrapped_lines)):\n if wrapped_lines[i] != '':\n wrapped_lines[i] = indent * ' ' + wrapped_lines[i]\n self.pieces.append(line[:indent] + '\\n'.join(wrapped_lines)[indent:] + ' \\n')\n", "def get_function_signature(self, node):\n \"\"\"Returns the function signature string for memberdef nodes.\"\"\"\n name = self.extract_text(self.get_specific_subnodes(node, 'name'))\n if self.with_type_info:\n argsstring = self.extract_text(self.get_specific_subnodes(node, 'argsstring'))\n else:\n argsstring = []\n param_id = 1\n for n_param in self.get_specific_subnodes(node, 'param'):\n declname = self.extract_text(self.get_specific_subnodes(n_param, 'declname'))\n if not declname:\n declname = 'arg' + str(param_id)\n defval = self.extract_text(self.get_specific_subnodes(n_param, 'defval'))\n if defval:\n defval = '=' + defval\n argsstring.append(declname + defval)\n param_id = param_id + 1\n argsstring = '(' + ', '.join(argsstring) + ')'\n type = self.extract_text(self.get_specific_subnodes(node, 'type'))\n function_definition = name + argsstring\n if type != '' and type != 'void':\n function_definition = function_definition + ' -> ' + type\n return '`' + function_definition + '` '\n" ]
class Doxy2SWIG: """Converts Doxygen generated XML files into a file containing docstrings that can be used by SWIG-1.3.x that have support for feature("docstring"). Once the data is parsed it is stored in self.pieces. """ def __init__(self, src, with_function_signature = False, with_type_info = False, with_constructor_list = False, with_attribute_list = False, with_overloaded_functions = False, textwidth = 80, quiet = False): """Initialize the instance given a source object. `src` can be a file or filename. If you do not want to include function definitions from doxygen then set `include_function_definition` to `False`. This is handy since this allows you to use the swig generated function definition using %feature("autodoc", [0,1]). """ # options: self.with_function_signature = with_function_signature self.with_type_info = with_type_info self.with_constructor_list = with_constructor_list self.with_attribute_list = with_attribute_list self.with_overloaded_functions = with_overloaded_functions self.textwidth = textwidth self.quiet = quiet # state: self.indent = 0 self.listitem = '' self.pieces = [] f = my_open_read(src) self.my_dir = os.path.dirname(f.name) self.xmldoc = minidom.parse(f).documentElement f.close() self.pieces.append('\n// File: %s\n' % os.path.basename(f.name)) self.space_re = re.compile(r'\s+') self.lead_spc = re.compile(r'^(%feature\S+\s+\S+\s*?)"\s+(\S)') self.multi = 0 self.ignores = ['inheritancegraph', 'param', 'listofallmembers', 'innerclass', 'name', 'declname', 'incdepgraph', 'invincdepgraph', 'programlisting', 'type', 'references', 'referencedby', 'location', 'collaborationgraph', 'reimplements', 'reimplementedby', 'derivedcompoundref', 'basecompoundref', 'argsstring', 'definition', 'exceptions'] #self.generics = [] def generate(self): """Parses the file set in the initialization. The resulting data is stored in `self.pieces`. """ self.parse(self.xmldoc) def write(self, fname): o = my_open_write(fname) o.write(''.join(self.pieces)) o.write('\n') o.close() def parse(self, node): """Parse a given node. This function in turn calls the `parse_<nodeType>` functions which handle the respective nodes. """ pm = getattr(self, "parse_%s" % node.__class__.__name__) pm(node) def parse_Document(self, node): self.parse(node.documentElement) def parse_Text(self, node): txt = node.data if txt == ' ': # this can happen when two tags follow in a text, e.g., # " ...</emph> <formaula>$..." etc. # here we want to keep the space. self.add_text(txt) return txt = txt.replace('\\', r'\\') txt = txt.replace('"', r'\"') # ignore pure whitespace m = self.space_re.match(txt) if m and len(m.group()) == len(txt): pass else: self.add_text(txt) def parse_Comment(self, node): """Parse a `COMMENT_NODE`. This does nothing for now.""" return def parse_Element(self, node): """Parse an `ELEMENT_NODE`. This calls specific `do_<tagName>` handers for different elements. If no handler is available the `subnode_parse` method is called. All tagNames specified in `self.ignores` are simply ignored. """ name = node.tagName ignores = self.ignores if name in ignores: return attr = "do_%s" % name if hasattr(self, attr): handlerMethod = getattr(self, attr) handlerMethod(node) else: self.subnode_parse(node) #if name not in self.generics: self.generics.append(name) # MARK: Special format parsing def subnode_parse(self, node, pieces=None, indent=0, ignore=[], restrict=None): """Parse the subnodes of a given node. Subnodes with tags in the `ignore` list are ignored. If pieces is given, use this as target for the parse results instead of self.pieces. Indent all lines by the amount given in `indent`. Note that the initial content in `pieces` is not indented. The final result is in any case added to self.pieces.""" if pieces is not None: old_pieces, self.pieces = self.pieces, pieces else: old_pieces = [] if type(indent) is int: indent = indent * ' ' if len(indent) > 0: pieces = ''.join(self.pieces) i_piece = pieces[:len(indent)] if self.pieces[-1:] == ['']: self.pieces = [pieces[len(indent):]] + [''] elif self.pieces != []: self.pieces = [pieces[len(indent):]] self.indent += len(indent) for n in node.childNodes: if restrict is not None: if n.nodeType == n.ELEMENT_NODE and n.tagName in restrict: self.parse(n) elif n.nodeType != n.ELEMENT_NODE or n.tagName not in ignore: self.parse(n) if len(indent) > 0: self.pieces = shift(self.pieces, indent, i_piece) self.indent -= len(indent) old_pieces.extend(self.pieces) self.pieces = old_pieces def surround_parse(self, node, pre_char, post_char): """Parse the subnodes of a given node. Subnodes with tags in the `ignore` list are ignored. Prepend `pre_char` and append `post_char` to the output in self.pieces.""" self.add_text(pre_char) self.subnode_parse(node) self.add_text(post_char) # MARK: Helper functions def get_specific_subnodes(self, node, name, recursive=0): """Given a node and a name, return a list of child `ELEMENT_NODEs`, that have a `tagName` matching the `name`. Search recursively for `recursive` levels. """ children = [x for x in node.childNodes if x.nodeType == x.ELEMENT_NODE] ret = [x for x in children if x.tagName == name] if recursive > 0: for x in children: ret.extend(self.get_specific_subnodes(x, name, recursive-1)) return ret def get_specific_nodes(self, node, names): """Given a node and a sequence of strings in `names`, return a dictionary containing the names as keys and child `ELEMENT_NODEs`, that have a `tagName` equal to the name. """ nodes = [(x.tagName, x) for x in node.childNodes if x.nodeType == x.ELEMENT_NODE and x.tagName in names] return dict(nodes) def add_text(self, value): """Adds text corresponding to `value` into `self.pieces`.""" if isinstance(value, (list, tuple)): self.pieces.extend(value) else: self.pieces.append(value) def start_new_paragraph(self): """Make sure to create an empty line. This is overridden, if the previous text ends with the special marker ''. In that case, nothing is done. """ if self.pieces[-1:] == ['']: # respect special marker return elif self.pieces == []: # first paragraph, add '\n', override with '' self.pieces = ['\n'] elif self.pieces[-1][-1:] != '\n': # previous line not ended self.pieces.extend([' \n' ,'\n']) else: #default self.pieces.append('\n') def add_line_with_subsequent_indent(self, line, indent=4): """Add line of text and wrap such that subsequent lines are indented by `indent` spaces. """ if isinstance(line, (list, tuple)): line = ''.join(line) line = line.strip() width = self.textwidth-self.indent-indent wrapped_lines = textwrap.wrap(line[indent:], width=width) for i in range(len(wrapped_lines)): if wrapped_lines[i] != '': wrapped_lines[i] = indent * ' ' + wrapped_lines[i] self.pieces.append(line[:indent] + '\n'.join(wrapped_lines)[indent:] + ' \n') def extract_text(self, node): """Return the string representation of the node or list of nodes by parsing the subnodes, but returning the result as a string instead of adding it to `self.pieces`. Note that this allows extracting text even if the node is in the ignore list. """ if not isinstance(node, (list, tuple)): node = [node] pieces, self.pieces = self.pieces, [''] for n in node: for sn in n.childNodes: self.parse(sn) ret = ''.join(self.pieces) self.pieces = pieces return ret def get_function_signature(self, node): """Returns the function signature string for memberdef nodes.""" name = self.extract_text(self.get_specific_subnodes(node, 'name')) if self.with_type_info: argsstring = self.extract_text(self.get_specific_subnodes(node, 'argsstring')) else: argsstring = [] param_id = 1 for n_param in self.get_specific_subnodes(node, 'param'): declname = self.extract_text(self.get_specific_subnodes(n_param, 'declname')) if not declname: declname = 'arg' + str(param_id) defval = self.extract_text(self.get_specific_subnodes(n_param, 'defval')) if defval: defval = '=' + defval argsstring.append(declname + defval) param_id = param_id + 1 argsstring = '(' + ', '.join(argsstring) + ')' type = self.extract_text(self.get_specific_subnodes(node, 'type')) function_definition = name + argsstring if type != '' and type != 'void': function_definition = function_definition + ' -> ' + type return '`' + function_definition + '` ' # MARK: Special parsing tasks (need to be called manually) def make_constructor_list(self, constructor_nodes, classname): """Produces the "Constructors" section and the constructor signatures (since swig does not do so for classes) for class docstrings.""" if constructor_nodes == []: return self.add_text(['\n', 'Constructors', '\n', '------------']) for n in constructor_nodes: self.add_text('\n') self.add_line_with_subsequent_indent('* ' + self.get_function_signature(n)) self.subnode_parse(n, pieces = [], indent=4, ignore=['definition', 'name']) def make_attribute_list(self, node): """Produces the "Attributes" section in class docstrings for public member variables (attributes). """ atr_nodes = [] for n in self.get_specific_subnodes(node, 'memberdef', recursive=2): if n.attributes['kind'].value == 'variable' and n.attributes['prot'].value == 'public': atr_nodes.append(n) if not atr_nodes: return self.add_text(['\n', 'Attributes', '\n', '----------']) for n in atr_nodes: name = self.extract_text(self.get_specific_subnodes(n, 'name')) self.add_text(['\n* ', '`', name, '`', ' : ']) self.add_text(['`', self.extract_text(self.get_specific_subnodes(n, 'type')), '`']) self.add_text(' \n') restrict = ['briefdescription', 'detaileddescription'] self.subnode_parse(n, pieces=[''], indent=4, restrict=restrict) def get_memberdef_nodes_and_signatures(self, node, kind): """Collects the memberdef nodes and corresponding signatures that correspond to public function entries that are at most depth 2 deeper than the current (compounddef) node. Returns a dictionary with function signatures (what swig expects after the %feature directive) as keys, and a list of corresponding memberdef nodes as values.""" sig_dict = {} sig_prefix = '' if kind in ('file', 'namespace'): ns_node = node.getElementsByTagName('innernamespace') if not ns_node and kind == 'namespace': ns_node = node.getElementsByTagName('compoundname') if ns_node: sig_prefix = self.extract_text(ns_node[0]) + '::' elif kind in ('class', 'struct'): # Get the full function name. cn_node = node.getElementsByTagName('compoundname') sig_prefix = self.extract_text(cn_node[0]) + '::' md_nodes = self.get_specific_subnodes(node, 'memberdef', recursive=2) for n in md_nodes: if n.attributes['prot'].value != 'public': continue if n.attributes['kind'].value in ['variable', 'typedef']: continue if not self.get_specific_subnodes(n, 'definition'): continue name = self.extract_text(self.get_specific_subnodes(n, 'name')) if name[:8] == 'operator': continue sig = sig_prefix + name if sig in sig_dict: sig_dict[sig].append(n) else: sig_dict[sig] = [n] return sig_dict def handle_typical_memberdefs(self, signature, memberdef_nodes): """Produces docstring entries containing an "Overloaded function" section with the documentation for each overload, if the function is overloaded and self.with_overloaded_functions is set. Else, produce normal documentation. """ if len(memberdef_nodes) == 1 or not self.with_overloaded_functions: self.handle_typical_memberdefs_no_overload(signature, memberdef_nodes) return self.add_text(['\n', '%feature("docstring") ', signature, ' "', '\n']) if self.with_function_signature: for n in memberdef_nodes: self.add_line_with_subsequent_indent(self.get_function_signature(n)) self.add_text('\n') self.add_text(['Overloaded function', '\n', '-------------------']) for n in memberdef_nodes: self.add_text('\n') self.add_line_with_subsequent_indent('* ' + self.get_function_signature(n)) self.subnode_parse(n, pieces=[], indent=4, ignore=['definition', 'name']) self.add_text(['";', '\n']) # MARK: Tag handlers def do_linebreak(self, node): self.add_text(' ') def do_ndash(self, node): self.add_text('--') def do_mdash(self, node): self.add_text('---') def do_emphasis(self, node): self.surround_parse(node, '*', '*') def do_bold(self, node): self.surround_parse(node, '**', '**') def do_computeroutput(self, node): self.surround_parse(node, '`', '`') def do_heading(self, node): self.start_new_paragraph() pieces, self.pieces = self.pieces, [''] level = int(node.attributes['level'].value) self.subnode_parse(node) if level == 1: self.pieces.insert(0, '\n') self.add_text(['\n', len(''.join(self.pieces).strip()) * '=']) elif level == 2: self.add_text(['\n', len(''.join(self.pieces).strip()) * '-']) elif level >= 3: self.pieces.insert(0, level * '#' + ' ') # make following text have no gap to the heading: pieces.extend([''.join(self.pieces) + ' \n', '']) self.pieces = pieces def do_verbatim(self, node): self.start_new_paragraph() self.subnode_parse(node, pieces=[''], indent=4) def do_blockquote(self, node): self.start_new_paragraph() self.subnode_parse(node, pieces=[''], indent='> ') def do_hruler(self, node): self.start_new_paragraph() self.add_text('* * * * * \n') def do_includes(self, node): self.add_text('\nC++ includes: ') self.subnode_parse(node) self.add_text('\n') # MARK: Para tag handler def do_para(self, node): """This is the only place where text wrapping is automatically performed. Generally, this function parses the node (locally), wraps the text, and then adds the result to self.pieces. However, it may be convenient to allow the previous content of self.pieces to be included in the text wrapping. For this, use the following *convention*: If self.pieces ends with '', treat the _previous_ entry as part of the current paragraph. Else, insert new-line and start a new paragraph and "wrapping context". Paragraphs always end with ' \n', but if the parsed content ends with the special symbol '', this is passed on. """ if self.pieces[-1:] == ['']: pieces, self.pieces = self.pieces[:-2], self.pieces[-2:-1] else: self.add_text('\n') pieces, self.pieces = self.pieces, [''] self.subnode_parse(node) dont_end_paragraph = self.pieces[-1:] == [''] # Now do the text wrapping: width = self.textwidth - self.indent wrapped_para = [] for line in ''.join(self.pieces).splitlines(): keep_markdown_newline = line[-2:] == ' ' w_line = textwrap.wrap(line, width=width, break_long_words=False) if w_line == []: w_line = [''] if keep_markdown_newline: w_line[-1] = w_line[-1] + ' ' for wl in w_line: wrapped_para.append(wl + '\n') if wrapped_para: if wrapped_para[-1][-3:] != ' \n': wrapped_para[-1] = wrapped_para[-1][:-1] + ' \n' if dont_end_paragraph: wrapped_para.append('') pieces.extend(wrapped_para) self.pieces = pieces # MARK: List tag handlers def do_itemizedlist(self, node): if self.listitem == '': self.start_new_paragraph() elif self.pieces != [] and self.pieces[-1:] != ['']: self.add_text('\n') listitem = self.listitem if self.listitem in ['*', '-']: self.listitem = '-' else: self.listitem = '*' self.subnode_parse(node) self.listitem = listitem def do_orderedlist(self, node): if self.listitem == '': self.start_new_paragraph() elif self.pieces != [] and self.pieces[-1:] != ['']: self.add_text('\n') listitem = self.listitem self.listitem = 0 self.subnode_parse(node) self.listitem = listitem def do_listitem(self, node): try: self.listitem = int(self.listitem) + 1 item = str(self.listitem) + '. ' except: item = str(self.listitem) + ' ' self.subnode_parse(node, item, indent=4) # MARK: Parameter list tag handlers def do_parameterlist(self, node): self.start_new_paragraph() text = 'unknown' for key, val in node.attributes.items(): if key == 'kind': if val == 'param': text = 'Parameters' elif val == 'exception': text = 'Exceptions' elif val == 'retval': text = 'Returns' else: text = val break if self.indent == 0: self.add_text([text, '\n', len(text) * '-', '\n']) else: self.add_text([text, ': \n']) self.subnode_parse(node) def do_parameteritem(self, node): self.subnode_parse(node, pieces=['* ', '']) def do_parameternamelist(self, node): self.subnode_parse(node) self.add_text([' :', ' \n']) def do_parametername(self, node): if self.pieces != [] and self.pieces != ['* ', '']: self.add_text(', ') data = self.extract_text(node) self.add_text(['`', data, '`']) def do_parameterdescription(self, node): self.subnode_parse(node, pieces=[''], indent=4) # MARK: Section tag handler def do_simplesect(self, node): kind = node.attributes['kind'].value if kind in ('date', 'rcs', 'version'): return self.start_new_paragraph() if kind == 'warning': self.subnode_parse(node, pieces=['**Warning**: ',''], indent=4) elif kind == 'see': self.subnode_parse(node, pieces=['See also: ',''], indent=4) elif kind == 'return': if self.indent == 0: pieces = ['Returns', '\n', len('Returns') * '-', '\n', ''] else: pieces = ['Returns:', '\n', ''] self.subnode_parse(node, pieces=pieces) else: self.subnode_parse(node, pieces=[kind + ': ',''], indent=4) # MARK: %feature("docstring") producing tag handlers def do_compounddef(self, node): """This produces %feature("docstring") entries for classes, and handles class, namespace and file memberdef entries specially to allow for overloaded functions. For other cases, passes parsing on to standard handlers (which may produce unexpected results). """ kind = node.attributes['kind'].value if kind in ('class', 'struct'): prot = node.attributes['prot'].value if prot != 'public': return self.add_text('\n\n') classdefn = self.extract_text(self.get_specific_subnodes(node, 'compoundname')) classname = classdefn.split('::')[-1] self.add_text('%%feature("docstring") %s "\n' % classdefn) if self.with_constructor_list: constructor_nodes = [] for n in self.get_specific_subnodes(node, 'memberdef', recursive=2): if n.attributes['prot'].value == 'public': if self.extract_text(self.get_specific_subnodes(n, 'definition')) == classdefn + '::' + classname: constructor_nodes.append(n) for n in constructor_nodes: self.add_line_with_subsequent_indent(self.get_function_signature(n)) names = ('briefdescription','detaileddescription') sub_dict = self.get_specific_nodes(node, names) for n in ('briefdescription','detaileddescription'): if n in sub_dict: self.parse(sub_dict[n]) if self.with_constructor_list: self.make_constructor_list(constructor_nodes, classname) if self.with_attribute_list: self.make_attribute_list(node) sub_list = self.get_specific_subnodes(node, 'includes') if sub_list: self.parse(sub_list[0]) self.add_text(['";', '\n']) names = ['compoundname', 'briefdescription','detaileddescription', 'includes'] self.subnode_parse(node, ignore = names) elif kind in ('file', 'namespace'): nodes = node.getElementsByTagName('sectiondef') for n in nodes: self.parse(n) # now explicitely handle possibly overloaded member functions. if kind in ['class', 'struct','file', 'namespace']: md_nodes = self.get_memberdef_nodes_and_signatures(node, kind) for sig in md_nodes: self.handle_typical_memberdefs(sig, md_nodes[sig]) def do_memberdef(self, node): """Handle cases outside of class, struct, file or namespace. These are now dealt with by `handle_overloaded_memberfunction`. Do these even exist??? """ prot = node.attributes['prot'].value id = node.attributes['id'].value kind = node.attributes['kind'].value tmp = node.parentNode.parentNode.parentNode compdef = tmp.getElementsByTagName('compounddef')[0] cdef_kind = compdef.attributes['kind'].value if cdef_kind in ('file', 'namespace', 'class', 'struct'): # These cases are now handled by `handle_typical_memberdefs` return if prot != 'public': return first = self.get_specific_nodes(node, ('definition', 'name')) name = self.extract_text(first['name']) if name[:8] == 'operator': # Don't handle operators yet. return if not 'definition' in first or kind in ['variable', 'typedef']: return data = self.extract_text(first['definition']) self.add_text('\n') self.add_text(['/* where did this entry come from??? */', '\n']) self.add_text('%feature("docstring") %s "\n%s' % (data, data)) for n in node.childNodes: if n not in first.values(): self.parse(n) self.add_text(['";', '\n']) # MARK: Entry tag handlers (dont print anything meaningful) def do_sectiondef(self, node): kind = node.attributes['kind'].value if kind in ('public-func', 'func', 'user-defined', ''): self.subnode_parse(node) def do_header(self, node): """For a user defined section def a header field is present which should not be printed as such, so we comment it in the output.""" data = self.extract_text(node) self.add_text('\n/*\n %s \n*/\n' % data) # If our immediate sibling is a 'description' node then we # should comment that out also and remove it from the parent # node's children. parent = node.parentNode idx = parent.childNodes.index(node) if len(parent.childNodes) >= idx + 2: nd = parent.childNodes[idx + 2] if nd.nodeName == 'description': nd = parent.removeChild(nd) self.add_text('\n/*') self.subnode_parse(nd) self.add_text('\n*/\n') def do_member(self, node): kind = node.attributes['kind'].value refid = node.attributes['refid'].value if kind == 'function' and refid[:9] == 'namespace': self.subnode_parse(node) def do_doxygenindex(self, node): self.multi = 1 comps = node.getElementsByTagName('compound') for c in comps: refid = c.attributes['refid'].value fname = refid + '.xml' if not os.path.exists(fname): fname = os.path.join(self.my_dir, fname) if not self.quiet: print("parsing file: %s" % fname) p = Doxy2SWIG(fname, with_function_signature = self.with_function_signature, with_type_info = self.with_type_info, with_constructor_list = self.with_constructor_list, with_attribute_list = self.with_attribute_list, with_overloaded_functions = self.with_overloaded_functions, textwidth = self.textwidth, quiet = self.quiet) p.generate() self.pieces.extend(p.pieces)
basler/pypylon
scripts/builddoxy2swig/doxy2swig/doxy2swig.py
Doxy2SWIG.handle_typical_memberdefs
python
def handle_typical_memberdefs(self, signature, memberdef_nodes): if len(memberdef_nodes) == 1 or not self.with_overloaded_functions: self.handle_typical_memberdefs_no_overload(signature, memberdef_nodes) return self.add_text(['\n', '%feature("docstring") ', signature, ' "', '\n']) if self.with_function_signature: for n in memberdef_nodes: self.add_line_with_subsequent_indent(self.get_function_signature(n)) self.add_text('\n') self.add_text(['Overloaded function', '\n', '-------------------']) for n in memberdef_nodes: self.add_text('\n') self.add_line_with_subsequent_indent('* ' + self.get_function_signature(n)) self.subnode_parse(n, pieces=[], indent=4, ignore=['definition', 'name']) self.add_text(['";', '\n'])
Produces docstring entries containing an "Overloaded function" section with the documentation for each overload, if the function is overloaded and self.with_overloaded_functions is set. Else, produce normal documentation.
train
https://github.com/basler/pypylon/blob/d3510fa419b1c2b17f3f0b80a5fbb720c7b84008/scripts/builddoxy2swig/doxy2swig/doxy2swig.py#L440-L461
[ "def subnode_parse(self, node, pieces=None, indent=0, ignore=[], restrict=None):\n \"\"\"Parse the subnodes of a given node. Subnodes with tags in the\n `ignore` list are ignored. If pieces is given, use this as target for\n the parse results instead of self.pieces. Indent all lines by the amount\n given in `indent`. Note that the initial content in `pieces` is not\n indented. The final result is in any case added to self.pieces.\"\"\"\n if pieces is not None:\n old_pieces, self.pieces = self.pieces, pieces\n else:\n old_pieces = []\n if type(indent) is int:\n indent = indent * ' '\n if len(indent) > 0:\n pieces = ''.join(self.pieces)\n i_piece = pieces[:len(indent)]\n if self.pieces[-1:] == ['']:\n self.pieces = [pieces[len(indent):]] + ['']\n elif self.pieces != []:\n self.pieces = [pieces[len(indent):]]\n self.indent += len(indent)\n for n in node.childNodes:\n if restrict is not None:\n if n.nodeType == n.ELEMENT_NODE and n.tagName in restrict:\n self.parse(n)\n elif n.nodeType != n.ELEMENT_NODE or n.tagName not in ignore:\n self.parse(n)\n if len(indent) > 0:\n self.pieces = shift(self.pieces, indent, i_piece)\n self.indent -= len(indent)\n old_pieces.extend(self.pieces)\n self.pieces = old_pieces\n", "def add_text(self, value):\n \"\"\"Adds text corresponding to `value` into `self.pieces`.\"\"\"\n if isinstance(value, (list, tuple)):\n self.pieces.extend(value)\n else:\n self.pieces.append(value)\n", "def add_line_with_subsequent_indent(self, line, indent=4):\n \"\"\"Add line of text and wrap such that subsequent lines are indented\n by `indent` spaces.\n \"\"\"\n if isinstance(line, (list, tuple)):\n line = ''.join(line)\n line = line.strip()\n width = self.textwidth-self.indent-indent\n wrapped_lines = textwrap.wrap(line[indent:], width=width)\n for i in range(len(wrapped_lines)):\n if wrapped_lines[i] != '':\n wrapped_lines[i] = indent * ' ' + wrapped_lines[i]\n self.pieces.append(line[:indent] + '\\n'.join(wrapped_lines)[indent:] + ' \\n')\n", "def get_function_signature(self, node):\n \"\"\"Returns the function signature string for memberdef nodes.\"\"\"\n name = self.extract_text(self.get_specific_subnodes(node, 'name'))\n if self.with_type_info:\n argsstring = self.extract_text(self.get_specific_subnodes(node, 'argsstring'))\n else:\n argsstring = []\n param_id = 1\n for n_param in self.get_specific_subnodes(node, 'param'):\n declname = self.extract_text(self.get_specific_subnodes(n_param, 'declname'))\n if not declname:\n declname = 'arg' + str(param_id)\n defval = self.extract_text(self.get_specific_subnodes(n_param, 'defval'))\n if defval:\n defval = '=' + defval\n argsstring.append(declname + defval)\n param_id = param_id + 1\n argsstring = '(' + ', '.join(argsstring) + ')'\n type = self.extract_text(self.get_specific_subnodes(node, 'type'))\n function_definition = name + argsstring\n if type != '' and type != 'void':\n function_definition = function_definition + ' -> ' + type\n return '`' + function_definition + '` '\n", "def handle_typical_memberdefs_no_overload(self, signature, memberdef_nodes):\n \"\"\"Produce standard documentation for memberdef_nodes.\"\"\"\n for n in memberdef_nodes:\n self.add_text(['\\n', '%feature(\"docstring\") ', signature, ' \"', '\\n'])\n if self.with_function_signature:\n self.add_line_with_subsequent_indent(self.get_function_signature(n))\n self.subnode_parse(n, pieces=[], ignore=['definition', 'name'])\n self.add_text(['\";', '\\n'])\n" ]
class Doxy2SWIG: """Converts Doxygen generated XML files into a file containing docstrings that can be used by SWIG-1.3.x that have support for feature("docstring"). Once the data is parsed it is stored in self.pieces. """ def __init__(self, src, with_function_signature = False, with_type_info = False, with_constructor_list = False, with_attribute_list = False, with_overloaded_functions = False, textwidth = 80, quiet = False): """Initialize the instance given a source object. `src` can be a file or filename. If you do not want to include function definitions from doxygen then set `include_function_definition` to `False`. This is handy since this allows you to use the swig generated function definition using %feature("autodoc", [0,1]). """ # options: self.with_function_signature = with_function_signature self.with_type_info = with_type_info self.with_constructor_list = with_constructor_list self.with_attribute_list = with_attribute_list self.with_overloaded_functions = with_overloaded_functions self.textwidth = textwidth self.quiet = quiet # state: self.indent = 0 self.listitem = '' self.pieces = [] f = my_open_read(src) self.my_dir = os.path.dirname(f.name) self.xmldoc = minidom.parse(f).documentElement f.close() self.pieces.append('\n// File: %s\n' % os.path.basename(f.name)) self.space_re = re.compile(r'\s+') self.lead_spc = re.compile(r'^(%feature\S+\s+\S+\s*?)"\s+(\S)') self.multi = 0 self.ignores = ['inheritancegraph', 'param', 'listofallmembers', 'innerclass', 'name', 'declname', 'incdepgraph', 'invincdepgraph', 'programlisting', 'type', 'references', 'referencedby', 'location', 'collaborationgraph', 'reimplements', 'reimplementedby', 'derivedcompoundref', 'basecompoundref', 'argsstring', 'definition', 'exceptions'] #self.generics = [] def generate(self): """Parses the file set in the initialization. The resulting data is stored in `self.pieces`. """ self.parse(self.xmldoc) def write(self, fname): o = my_open_write(fname) o.write(''.join(self.pieces)) o.write('\n') o.close() def parse(self, node): """Parse a given node. This function in turn calls the `parse_<nodeType>` functions which handle the respective nodes. """ pm = getattr(self, "parse_%s" % node.__class__.__name__) pm(node) def parse_Document(self, node): self.parse(node.documentElement) def parse_Text(self, node): txt = node.data if txt == ' ': # this can happen when two tags follow in a text, e.g., # " ...</emph> <formaula>$..." etc. # here we want to keep the space. self.add_text(txt) return txt = txt.replace('\\', r'\\') txt = txt.replace('"', r'\"') # ignore pure whitespace m = self.space_re.match(txt) if m and len(m.group()) == len(txt): pass else: self.add_text(txt) def parse_Comment(self, node): """Parse a `COMMENT_NODE`. This does nothing for now.""" return def parse_Element(self, node): """Parse an `ELEMENT_NODE`. This calls specific `do_<tagName>` handers for different elements. If no handler is available the `subnode_parse` method is called. All tagNames specified in `self.ignores` are simply ignored. """ name = node.tagName ignores = self.ignores if name in ignores: return attr = "do_%s" % name if hasattr(self, attr): handlerMethod = getattr(self, attr) handlerMethod(node) else: self.subnode_parse(node) #if name not in self.generics: self.generics.append(name) # MARK: Special format parsing def subnode_parse(self, node, pieces=None, indent=0, ignore=[], restrict=None): """Parse the subnodes of a given node. Subnodes with tags in the `ignore` list are ignored. If pieces is given, use this as target for the parse results instead of self.pieces. Indent all lines by the amount given in `indent`. Note that the initial content in `pieces` is not indented. The final result is in any case added to self.pieces.""" if pieces is not None: old_pieces, self.pieces = self.pieces, pieces else: old_pieces = [] if type(indent) is int: indent = indent * ' ' if len(indent) > 0: pieces = ''.join(self.pieces) i_piece = pieces[:len(indent)] if self.pieces[-1:] == ['']: self.pieces = [pieces[len(indent):]] + [''] elif self.pieces != []: self.pieces = [pieces[len(indent):]] self.indent += len(indent) for n in node.childNodes: if restrict is not None: if n.nodeType == n.ELEMENT_NODE and n.tagName in restrict: self.parse(n) elif n.nodeType != n.ELEMENT_NODE or n.tagName not in ignore: self.parse(n) if len(indent) > 0: self.pieces = shift(self.pieces, indent, i_piece) self.indent -= len(indent) old_pieces.extend(self.pieces) self.pieces = old_pieces def surround_parse(self, node, pre_char, post_char): """Parse the subnodes of a given node. Subnodes with tags in the `ignore` list are ignored. Prepend `pre_char` and append `post_char` to the output in self.pieces.""" self.add_text(pre_char) self.subnode_parse(node) self.add_text(post_char) # MARK: Helper functions def get_specific_subnodes(self, node, name, recursive=0): """Given a node and a name, return a list of child `ELEMENT_NODEs`, that have a `tagName` matching the `name`. Search recursively for `recursive` levels. """ children = [x for x in node.childNodes if x.nodeType == x.ELEMENT_NODE] ret = [x for x in children if x.tagName == name] if recursive > 0: for x in children: ret.extend(self.get_specific_subnodes(x, name, recursive-1)) return ret def get_specific_nodes(self, node, names): """Given a node and a sequence of strings in `names`, return a dictionary containing the names as keys and child `ELEMENT_NODEs`, that have a `tagName` equal to the name. """ nodes = [(x.tagName, x) for x in node.childNodes if x.nodeType == x.ELEMENT_NODE and x.tagName in names] return dict(nodes) def add_text(self, value): """Adds text corresponding to `value` into `self.pieces`.""" if isinstance(value, (list, tuple)): self.pieces.extend(value) else: self.pieces.append(value) def start_new_paragraph(self): """Make sure to create an empty line. This is overridden, if the previous text ends with the special marker ''. In that case, nothing is done. """ if self.pieces[-1:] == ['']: # respect special marker return elif self.pieces == []: # first paragraph, add '\n', override with '' self.pieces = ['\n'] elif self.pieces[-1][-1:] != '\n': # previous line not ended self.pieces.extend([' \n' ,'\n']) else: #default self.pieces.append('\n') def add_line_with_subsequent_indent(self, line, indent=4): """Add line of text and wrap such that subsequent lines are indented by `indent` spaces. """ if isinstance(line, (list, tuple)): line = ''.join(line) line = line.strip() width = self.textwidth-self.indent-indent wrapped_lines = textwrap.wrap(line[indent:], width=width) for i in range(len(wrapped_lines)): if wrapped_lines[i] != '': wrapped_lines[i] = indent * ' ' + wrapped_lines[i] self.pieces.append(line[:indent] + '\n'.join(wrapped_lines)[indent:] + ' \n') def extract_text(self, node): """Return the string representation of the node or list of nodes by parsing the subnodes, but returning the result as a string instead of adding it to `self.pieces`. Note that this allows extracting text even if the node is in the ignore list. """ if not isinstance(node, (list, tuple)): node = [node] pieces, self.pieces = self.pieces, [''] for n in node: for sn in n.childNodes: self.parse(sn) ret = ''.join(self.pieces) self.pieces = pieces return ret def get_function_signature(self, node): """Returns the function signature string for memberdef nodes.""" name = self.extract_text(self.get_specific_subnodes(node, 'name')) if self.with_type_info: argsstring = self.extract_text(self.get_specific_subnodes(node, 'argsstring')) else: argsstring = [] param_id = 1 for n_param in self.get_specific_subnodes(node, 'param'): declname = self.extract_text(self.get_specific_subnodes(n_param, 'declname')) if not declname: declname = 'arg' + str(param_id) defval = self.extract_text(self.get_specific_subnodes(n_param, 'defval')) if defval: defval = '=' + defval argsstring.append(declname + defval) param_id = param_id + 1 argsstring = '(' + ', '.join(argsstring) + ')' type = self.extract_text(self.get_specific_subnodes(node, 'type')) function_definition = name + argsstring if type != '' and type != 'void': function_definition = function_definition + ' -> ' + type return '`' + function_definition + '` ' # MARK: Special parsing tasks (need to be called manually) def make_constructor_list(self, constructor_nodes, classname): """Produces the "Constructors" section and the constructor signatures (since swig does not do so for classes) for class docstrings.""" if constructor_nodes == []: return self.add_text(['\n', 'Constructors', '\n', '------------']) for n in constructor_nodes: self.add_text('\n') self.add_line_with_subsequent_indent('* ' + self.get_function_signature(n)) self.subnode_parse(n, pieces = [], indent=4, ignore=['definition', 'name']) def make_attribute_list(self, node): """Produces the "Attributes" section in class docstrings for public member variables (attributes). """ atr_nodes = [] for n in self.get_specific_subnodes(node, 'memberdef', recursive=2): if n.attributes['kind'].value == 'variable' and n.attributes['prot'].value == 'public': atr_nodes.append(n) if not atr_nodes: return self.add_text(['\n', 'Attributes', '\n', '----------']) for n in atr_nodes: name = self.extract_text(self.get_specific_subnodes(n, 'name')) self.add_text(['\n* ', '`', name, '`', ' : ']) self.add_text(['`', self.extract_text(self.get_specific_subnodes(n, 'type')), '`']) self.add_text(' \n') restrict = ['briefdescription', 'detaileddescription'] self.subnode_parse(n, pieces=[''], indent=4, restrict=restrict) def get_memberdef_nodes_and_signatures(self, node, kind): """Collects the memberdef nodes and corresponding signatures that correspond to public function entries that are at most depth 2 deeper than the current (compounddef) node. Returns a dictionary with function signatures (what swig expects after the %feature directive) as keys, and a list of corresponding memberdef nodes as values.""" sig_dict = {} sig_prefix = '' if kind in ('file', 'namespace'): ns_node = node.getElementsByTagName('innernamespace') if not ns_node and kind == 'namespace': ns_node = node.getElementsByTagName('compoundname') if ns_node: sig_prefix = self.extract_text(ns_node[0]) + '::' elif kind in ('class', 'struct'): # Get the full function name. cn_node = node.getElementsByTagName('compoundname') sig_prefix = self.extract_text(cn_node[0]) + '::' md_nodes = self.get_specific_subnodes(node, 'memberdef', recursive=2) for n in md_nodes: if n.attributes['prot'].value != 'public': continue if n.attributes['kind'].value in ['variable', 'typedef']: continue if not self.get_specific_subnodes(n, 'definition'): continue name = self.extract_text(self.get_specific_subnodes(n, 'name')) if name[:8] == 'operator': continue sig = sig_prefix + name if sig in sig_dict: sig_dict[sig].append(n) else: sig_dict[sig] = [n] return sig_dict def handle_typical_memberdefs_no_overload(self, signature, memberdef_nodes): """Produce standard documentation for memberdef_nodes.""" for n in memberdef_nodes: self.add_text(['\n', '%feature("docstring") ', signature, ' "', '\n']) if self.with_function_signature: self.add_line_with_subsequent_indent(self.get_function_signature(n)) self.subnode_parse(n, pieces=[], ignore=['definition', 'name']) self.add_text(['";', '\n']) # MARK: Tag handlers def do_linebreak(self, node): self.add_text(' ') def do_ndash(self, node): self.add_text('--') def do_mdash(self, node): self.add_text('---') def do_emphasis(self, node): self.surround_parse(node, '*', '*') def do_bold(self, node): self.surround_parse(node, '**', '**') def do_computeroutput(self, node): self.surround_parse(node, '`', '`') def do_heading(self, node): self.start_new_paragraph() pieces, self.pieces = self.pieces, [''] level = int(node.attributes['level'].value) self.subnode_parse(node) if level == 1: self.pieces.insert(0, '\n') self.add_text(['\n', len(''.join(self.pieces).strip()) * '=']) elif level == 2: self.add_text(['\n', len(''.join(self.pieces).strip()) * '-']) elif level >= 3: self.pieces.insert(0, level * '#' + ' ') # make following text have no gap to the heading: pieces.extend([''.join(self.pieces) + ' \n', '']) self.pieces = pieces def do_verbatim(self, node): self.start_new_paragraph() self.subnode_parse(node, pieces=[''], indent=4) def do_blockquote(self, node): self.start_new_paragraph() self.subnode_parse(node, pieces=[''], indent='> ') def do_hruler(self, node): self.start_new_paragraph() self.add_text('* * * * * \n') def do_includes(self, node): self.add_text('\nC++ includes: ') self.subnode_parse(node) self.add_text('\n') # MARK: Para tag handler def do_para(self, node): """This is the only place where text wrapping is automatically performed. Generally, this function parses the node (locally), wraps the text, and then adds the result to self.pieces. However, it may be convenient to allow the previous content of self.pieces to be included in the text wrapping. For this, use the following *convention*: If self.pieces ends with '', treat the _previous_ entry as part of the current paragraph. Else, insert new-line and start a new paragraph and "wrapping context". Paragraphs always end with ' \n', but if the parsed content ends with the special symbol '', this is passed on. """ if self.pieces[-1:] == ['']: pieces, self.pieces = self.pieces[:-2], self.pieces[-2:-1] else: self.add_text('\n') pieces, self.pieces = self.pieces, [''] self.subnode_parse(node) dont_end_paragraph = self.pieces[-1:] == [''] # Now do the text wrapping: width = self.textwidth - self.indent wrapped_para = [] for line in ''.join(self.pieces).splitlines(): keep_markdown_newline = line[-2:] == ' ' w_line = textwrap.wrap(line, width=width, break_long_words=False) if w_line == []: w_line = [''] if keep_markdown_newline: w_line[-1] = w_line[-1] + ' ' for wl in w_line: wrapped_para.append(wl + '\n') if wrapped_para: if wrapped_para[-1][-3:] != ' \n': wrapped_para[-1] = wrapped_para[-1][:-1] + ' \n' if dont_end_paragraph: wrapped_para.append('') pieces.extend(wrapped_para) self.pieces = pieces # MARK: List tag handlers def do_itemizedlist(self, node): if self.listitem == '': self.start_new_paragraph() elif self.pieces != [] and self.pieces[-1:] != ['']: self.add_text('\n') listitem = self.listitem if self.listitem in ['*', '-']: self.listitem = '-' else: self.listitem = '*' self.subnode_parse(node) self.listitem = listitem def do_orderedlist(self, node): if self.listitem == '': self.start_new_paragraph() elif self.pieces != [] and self.pieces[-1:] != ['']: self.add_text('\n') listitem = self.listitem self.listitem = 0 self.subnode_parse(node) self.listitem = listitem def do_listitem(self, node): try: self.listitem = int(self.listitem) + 1 item = str(self.listitem) + '. ' except: item = str(self.listitem) + ' ' self.subnode_parse(node, item, indent=4) # MARK: Parameter list tag handlers def do_parameterlist(self, node): self.start_new_paragraph() text = 'unknown' for key, val in node.attributes.items(): if key == 'kind': if val == 'param': text = 'Parameters' elif val == 'exception': text = 'Exceptions' elif val == 'retval': text = 'Returns' else: text = val break if self.indent == 0: self.add_text([text, '\n', len(text) * '-', '\n']) else: self.add_text([text, ': \n']) self.subnode_parse(node) def do_parameteritem(self, node): self.subnode_parse(node, pieces=['* ', '']) def do_parameternamelist(self, node): self.subnode_parse(node) self.add_text([' :', ' \n']) def do_parametername(self, node): if self.pieces != [] and self.pieces != ['* ', '']: self.add_text(', ') data = self.extract_text(node) self.add_text(['`', data, '`']) def do_parameterdescription(self, node): self.subnode_parse(node, pieces=[''], indent=4) # MARK: Section tag handler def do_simplesect(self, node): kind = node.attributes['kind'].value if kind in ('date', 'rcs', 'version'): return self.start_new_paragraph() if kind == 'warning': self.subnode_parse(node, pieces=['**Warning**: ',''], indent=4) elif kind == 'see': self.subnode_parse(node, pieces=['See also: ',''], indent=4) elif kind == 'return': if self.indent == 0: pieces = ['Returns', '\n', len('Returns') * '-', '\n', ''] else: pieces = ['Returns:', '\n', ''] self.subnode_parse(node, pieces=pieces) else: self.subnode_parse(node, pieces=[kind + ': ',''], indent=4) # MARK: %feature("docstring") producing tag handlers def do_compounddef(self, node): """This produces %feature("docstring") entries for classes, and handles class, namespace and file memberdef entries specially to allow for overloaded functions. For other cases, passes parsing on to standard handlers (which may produce unexpected results). """ kind = node.attributes['kind'].value if kind in ('class', 'struct'): prot = node.attributes['prot'].value if prot != 'public': return self.add_text('\n\n') classdefn = self.extract_text(self.get_specific_subnodes(node, 'compoundname')) classname = classdefn.split('::')[-1] self.add_text('%%feature("docstring") %s "\n' % classdefn) if self.with_constructor_list: constructor_nodes = [] for n in self.get_specific_subnodes(node, 'memberdef', recursive=2): if n.attributes['prot'].value == 'public': if self.extract_text(self.get_specific_subnodes(n, 'definition')) == classdefn + '::' + classname: constructor_nodes.append(n) for n in constructor_nodes: self.add_line_with_subsequent_indent(self.get_function_signature(n)) names = ('briefdescription','detaileddescription') sub_dict = self.get_specific_nodes(node, names) for n in ('briefdescription','detaileddescription'): if n in sub_dict: self.parse(sub_dict[n]) if self.with_constructor_list: self.make_constructor_list(constructor_nodes, classname) if self.with_attribute_list: self.make_attribute_list(node) sub_list = self.get_specific_subnodes(node, 'includes') if sub_list: self.parse(sub_list[0]) self.add_text(['";', '\n']) names = ['compoundname', 'briefdescription','detaileddescription', 'includes'] self.subnode_parse(node, ignore = names) elif kind in ('file', 'namespace'): nodes = node.getElementsByTagName('sectiondef') for n in nodes: self.parse(n) # now explicitely handle possibly overloaded member functions. if kind in ['class', 'struct','file', 'namespace']: md_nodes = self.get_memberdef_nodes_and_signatures(node, kind) for sig in md_nodes: self.handle_typical_memberdefs(sig, md_nodes[sig]) def do_memberdef(self, node): """Handle cases outside of class, struct, file or namespace. These are now dealt with by `handle_overloaded_memberfunction`. Do these even exist??? """ prot = node.attributes['prot'].value id = node.attributes['id'].value kind = node.attributes['kind'].value tmp = node.parentNode.parentNode.parentNode compdef = tmp.getElementsByTagName('compounddef')[0] cdef_kind = compdef.attributes['kind'].value if cdef_kind in ('file', 'namespace', 'class', 'struct'): # These cases are now handled by `handle_typical_memberdefs` return if prot != 'public': return first = self.get_specific_nodes(node, ('definition', 'name')) name = self.extract_text(first['name']) if name[:8] == 'operator': # Don't handle operators yet. return if not 'definition' in first or kind in ['variable', 'typedef']: return data = self.extract_text(first['definition']) self.add_text('\n') self.add_text(['/* where did this entry come from??? */', '\n']) self.add_text('%feature("docstring") %s "\n%s' % (data, data)) for n in node.childNodes: if n not in first.values(): self.parse(n) self.add_text(['";', '\n']) # MARK: Entry tag handlers (dont print anything meaningful) def do_sectiondef(self, node): kind = node.attributes['kind'].value if kind in ('public-func', 'func', 'user-defined', ''): self.subnode_parse(node) def do_header(self, node): """For a user defined section def a header field is present which should not be printed as such, so we comment it in the output.""" data = self.extract_text(node) self.add_text('\n/*\n %s \n*/\n' % data) # If our immediate sibling is a 'description' node then we # should comment that out also and remove it from the parent # node's children. parent = node.parentNode idx = parent.childNodes.index(node) if len(parent.childNodes) >= idx + 2: nd = parent.childNodes[idx + 2] if nd.nodeName == 'description': nd = parent.removeChild(nd) self.add_text('\n/*') self.subnode_parse(nd) self.add_text('\n*/\n') def do_member(self, node): kind = node.attributes['kind'].value refid = node.attributes['refid'].value if kind == 'function' and refid[:9] == 'namespace': self.subnode_parse(node) def do_doxygenindex(self, node): self.multi = 1 comps = node.getElementsByTagName('compound') for c in comps: refid = c.attributes['refid'].value fname = refid + '.xml' if not os.path.exists(fname): fname = os.path.join(self.my_dir, fname) if not self.quiet: print("parsing file: %s" % fname) p = Doxy2SWIG(fname, with_function_signature = self.with_function_signature, with_type_info = self.with_type_info, with_constructor_list = self.with_constructor_list, with_attribute_list = self.with_attribute_list, with_overloaded_functions = self.with_overloaded_functions, textwidth = self.textwidth, quiet = self.quiet) p.generate() self.pieces.extend(p.pieces)
basler/pypylon
scripts/builddoxy2swig/doxy2swig/doxy2swig.py
Doxy2SWIG.do_para
python
def do_para(self, node): if self.pieces[-1:] == ['']: pieces, self.pieces = self.pieces[:-2], self.pieces[-2:-1] else: self.add_text('\n') pieces, self.pieces = self.pieces, [''] self.subnode_parse(node) dont_end_paragraph = self.pieces[-1:] == [''] # Now do the text wrapping: width = self.textwidth - self.indent wrapped_para = [] for line in ''.join(self.pieces).splitlines(): keep_markdown_newline = line[-2:] == ' ' w_line = textwrap.wrap(line, width=width, break_long_words=False) if w_line == []: w_line = [''] if keep_markdown_newline: w_line[-1] = w_line[-1] + ' ' for wl in w_line: wrapped_para.append(wl + '\n') if wrapped_para: if wrapped_para[-1][-3:] != ' \n': wrapped_para[-1] = wrapped_para[-1][:-1] + ' \n' if dont_end_paragraph: wrapped_para.append('') pieces.extend(wrapped_para) self.pieces = pieces
This is the only place where text wrapping is automatically performed. Generally, this function parses the node (locally), wraps the text, and then adds the result to self.pieces. However, it may be convenient to allow the previous content of self.pieces to be included in the text wrapping. For this, use the following *convention*: If self.pieces ends with '', treat the _previous_ entry as part of the current paragraph. Else, insert new-line and start a new paragraph and "wrapping context". Paragraphs always end with ' \n', but if the parsed content ends with the special symbol '', this is passed on.
train
https://github.com/basler/pypylon/blob/d3510fa419b1c2b17f3f0b80a5fbb720c7b84008/scripts/builddoxy2swig/doxy2swig/doxy2swig.py#L517-L554
[ "def subnode_parse(self, node, pieces=None, indent=0, ignore=[], restrict=None):\n \"\"\"Parse the subnodes of a given node. Subnodes with tags in the\n `ignore` list are ignored. If pieces is given, use this as target for\n the parse results instead of self.pieces. Indent all lines by the amount\n given in `indent`. Note that the initial content in `pieces` is not\n indented. The final result is in any case added to self.pieces.\"\"\"\n if pieces is not None:\n old_pieces, self.pieces = self.pieces, pieces\n else:\n old_pieces = []\n if type(indent) is int:\n indent = indent * ' '\n if len(indent) > 0:\n pieces = ''.join(self.pieces)\n i_piece = pieces[:len(indent)]\n if self.pieces[-1:] == ['']:\n self.pieces = [pieces[len(indent):]] + ['']\n elif self.pieces != []:\n self.pieces = [pieces[len(indent):]]\n self.indent += len(indent)\n for n in node.childNodes:\n if restrict is not None:\n if n.nodeType == n.ELEMENT_NODE and n.tagName in restrict:\n self.parse(n)\n elif n.nodeType != n.ELEMENT_NODE or n.tagName not in ignore:\n self.parse(n)\n if len(indent) > 0:\n self.pieces = shift(self.pieces, indent, i_piece)\n self.indent -= len(indent)\n old_pieces.extend(self.pieces)\n self.pieces = old_pieces\n", "def add_text(self, value):\n \"\"\"Adds text corresponding to `value` into `self.pieces`.\"\"\"\n if isinstance(value, (list, tuple)):\n self.pieces.extend(value)\n else:\n self.pieces.append(value)\n" ]
class Doxy2SWIG: """Converts Doxygen generated XML files into a file containing docstrings that can be used by SWIG-1.3.x that have support for feature("docstring"). Once the data is parsed it is stored in self.pieces. """ def __init__(self, src, with_function_signature = False, with_type_info = False, with_constructor_list = False, with_attribute_list = False, with_overloaded_functions = False, textwidth = 80, quiet = False): """Initialize the instance given a source object. `src` can be a file or filename. If you do not want to include function definitions from doxygen then set `include_function_definition` to `False`. This is handy since this allows you to use the swig generated function definition using %feature("autodoc", [0,1]). """ # options: self.with_function_signature = with_function_signature self.with_type_info = with_type_info self.with_constructor_list = with_constructor_list self.with_attribute_list = with_attribute_list self.with_overloaded_functions = with_overloaded_functions self.textwidth = textwidth self.quiet = quiet # state: self.indent = 0 self.listitem = '' self.pieces = [] f = my_open_read(src) self.my_dir = os.path.dirname(f.name) self.xmldoc = minidom.parse(f).documentElement f.close() self.pieces.append('\n// File: %s\n' % os.path.basename(f.name)) self.space_re = re.compile(r'\s+') self.lead_spc = re.compile(r'^(%feature\S+\s+\S+\s*?)"\s+(\S)') self.multi = 0 self.ignores = ['inheritancegraph', 'param', 'listofallmembers', 'innerclass', 'name', 'declname', 'incdepgraph', 'invincdepgraph', 'programlisting', 'type', 'references', 'referencedby', 'location', 'collaborationgraph', 'reimplements', 'reimplementedby', 'derivedcompoundref', 'basecompoundref', 'argsstring', 'definition', 'exceptions'] #self.generics = [] def generate(self): """Parses the file set in the initialization. The resulting data is stored in `self.pieces`. """ self.parse(self.xmldoc) def write(self, fname): o = my_open_write(fname) o.write(''.join(self.pieces)) o.write('\n') o.close() def parse(self, node): """Parse a given node. This function in turn calls the `parse_<nodeType>` functions which handle the respective nodes. """ pm = getattr(self, "parse_%s" % node.__class__.__name__) pm(node) def parse_Document(self, node): self.parse(node.documentElement) def parse_Text(self, node): txt = node.data if txt == ' ': # this can happen when two tags follow in a text, e.g., # " ...</emph> <formaula>$..." etc. # here we want to keep the space. self.add_text(txt) return txt = txt.replace('\\', r'\\') txt = txt.replace('"', r'\"') # ignore pure whitespace m = self.space_re.match(txt) if m and len(m.group()) == len(txt): pass else: self.add_text(txt) def parse_Comment(self, node): """Parse a `COMMENT_NODE`. This does nothing for now.""" return def parse_Element(self, node): """Parse an `ELEMENT_NODE`. This calls specific `do_<tagName>` handers for different elements. If no handler is available the `subnode_parse` method is called. All tagNames specified in `self.ignores` are simply ignored. """ name = node.tagName ignores = self.ignores if name in ignores: return attr = "do_%s" % name if hasattr(self, attr): handlerMethod = getattr(self, attr) handlerMethod(node) else: self.subnode_parse(node) #if name not in self.generics: self.generics.append(name) # MARK: Special format parsing def subnode_parse(self, node, pieces=None, indent=0, ignore=[], restrict=None): """Parse the subnodes of a given node. Subnodes with tags in the `ignore` list are ignored. If pieces is given, use this as target for the parse results instead of self.pieces. Indent all lines by the amount given in `indent`. Note that the initial content in `pieces` is not indented. The final result is in any case added to self.pieces.""" if pieces is not None: old_pieces, self.pieces = self.pieces, pieces else: old_pieces = [] if type(indent) is int: indent = indent * ' ' if len(indent) > 0: pieces = ''.join(self.pieces) i_piece = pieces[:len(indent)] if self.pieces[-1:] == ['']: self.pieces = [pieces[len(indent):]] + [''] elif self.pieces != []: self.pieces = [pieces[len(indent):]] self.indent += len(indent) for n in node.childNodes: if restrict is not None: if n.nodeType == n.ELEMENT_NODE and n.tagName in restrict: self.parse(n) elif n.nodeType != n.ELEMENT_NODE or n.tagName not in ignore: self.parse(n) if len(indent) > 0: self.pieces = shift(self.pieces, indent, i_piece) self.indent -= len(indent) old_pieces.extend(self.pieces) self.pieces = old_pieces def surround_parse(self, node, pre_char, post_char): """Parse the subnodes of a given node. Subnodes with tags in the `ignore` list are ignored. Prepend `pre_char` and append `post_char` to the output in self.pieces.""" self.add_text(pre_char) self.subnode_parse(node) self.add_text(post_char) # MARK: Helper functions def get_specific_subnodes(self, node, name, recursive=0): """Given a node and a name, return a list of child `ELEMENT_NODEs`, that have a `tagName` matching the `name`. Search recursively for `recursive` levels. """ children = [x for x in node.childNodes if x.nodeType == x.ELEMENT_NODE] ret = [x for x in children if x.tagName == name] if recursive > 0: for x in children: ret.extend(self.get_specific_subnodes(x, name, recursive-1)) return ret def get_specific_nodes(self, node, names): """Given a node and a sequence of strings in `names`, return a dictionary containing the names as keys and child `ELEMENT_NODEs`, that have a `tagName` equal to the name. """ nodes = [(x.tagName, x) for x in node.childNodes if x.nodeType == x.ELEMENT_NODE and x.tagName in names] return dict(nodes) def add_text(self, value): """Adds text corresponding to `value` into `self.pieces`.""" if isinstance(value, (list, tuple)): self.pieces.extend(value) else: self.pieces.append(value) def start_new_paragraph(self): """Make sure to create an empty line. This is overridden, if the previous text ends with the special marker ''. In that case, nothing is done. """ if self.pieces[-1:] == ['']: # respect special marker return elif self.pieces == []: # first paragraph, add '\n', override with '' self.pieces = ['\n'] elif self.pieces[-1][-1:] != '\n': # previous line not ended self.pieces.extend([' \n' ,'\n']) else: #default self.pieces.append('\n') def add_line_with_subsequent_indent(self, line, indent=4): """Add line of text and wrap such that subsequent lines are indented by `indent` spaces. """ if isinstance(line, (list, tuple)): line = ''.join(line) line = line.strip() width = self.textwidth-self.indent-indent wrapped_lines = textwrap.wrap(line[indent:], width=width) for i in range(len(wrapped_lines)): if wrapped_lines[i] != '': wrapped_lines[i] = indent * ' ' + wrapped_lines[i] self.pieces.append(line[:indent] + '\n'.join(wrapped_lines)[indent:] + ' \n') def extract_text(self, node): """Return the string representation of the node or list of nodes by parsing the subnodes, but returning the result as a string instead of adding it to `self.pieces`. Note that this allows extracting text even if the node is in the ignore list. """ if not isinstance(node, (list, tuple)): node = [node] pieces, self.pieces = self.pieces, [''] for n in node: for sn in n.childNodes: self.parse(sn) ret = ''.join(self.pieces) self.pieces = pieces return ret def get_function_signature(self, node): """Returns the function signature string for memberdef nodes.""" name = self.extract_text(self.get_specific_subnodes(node, 'name')) if self.with_type_info: argsstring = self.extract_text(self.get_specific_subnodes(node, 'argsstring')) else: argsstring = [] param_id = 1 for n_param in self.get_specific_subnodes(node, 'param'): declname = self.extract_text(self.get_specific_subnodes(n_param, 'declname')) if not declname: declname = 'arg' + str(param_id) defval = self.extract_text(self.get_specific_subnodes(n_param, 'defval')) if defval: defval = '=' + defval argsstring.append(declname + defval) param_id = param_id + 1 argsstring = '(' + ', '.join(argsstring) + ')' type = self.extract_text(self.get_specific_subnodes(node, 'type')) function_definition = name + argsstring if type != '' and type != 'void': function_definition = function_definition + ' -> ' + type return '`' + function_definition + '` ' # MARK: Special parsing tasks (need to be called manually) def make_constructor_list(self, constructor_nodes, classname): """Produces the "Constructors" section and the constructor signatures (since swig does not do so for classes) for class docstrings.""" if constructor_nodes == []: return self.add_text(['\n', 'Constructors', '\n', '------------']) for n in constructor_nodes: self.add_text('\n') self.add_line_with_subsequent_indent('* ' + self.get_function_signature(n)) self.subnode_parse(n, pieces = [], indent=4, ignore=['definition', 'name']) def make_attribute_list(self, node): """Produces the "Attributes" section in class docstrings for public member variables (attributes). """ atr_nodes = [] for n in self.get_specific_subnodes(node, 'memberdef', recursive=2): if n.attributes['kind'].value == 'variable' and n.attributes['prot'].value == 'public': atr_nodes.append(n) if not atr_nodes: return self.add_text(['\n', 'Attributes', '\n', '----------']) for n in atr_nodes: name = self.extract_text(self.get_specific_subnodes(n, 'name')) self.add_text(['\n* ', '`', name, '`', ' : ']) self.add_text(['`', self.extract_text(self.get_specific_subnodes(n, 'type')), '`']) self.add_text(' \n') restrict = ['briefdescription', 'detaileddescription'] self.subnode_parse(n, pieces=[''], indent=4, restrict=restrict) def get_memberdef_nodes_and_signatures(self, node, kind): """Collects the memberdef nodes and corresponding signatures that correspond to public function entries that are at most depth 2 deeper than the current (compounddef) node. Returns a dictionary with function signatures (what swig expects after the %feature directive) as keys, and a list of corresponding memberdef nodes as values.""" sig_dict = {} sig_prefix = '' if kind in ('file', 'namespace'): ns_node = node.getElementsByTagName('innernamespace') if not ns_node and kind == 'namespace': ns_node = node.getElementsByTagName('compoundname') if ns_node: sig_prefix = self.extract_text(ns_node[0]) + '::' elif kind in ('class', 'struct'): # Get the full function name. cn_node = node.getElementsByTagName('compoundname') sig_prefix = self.extract_text(cn_node[0]) + '::' md_nodes = self.get_specific_subnodes(node, 'memberdef', recursive=2) for n in md_nodes: if n.attributes['prot'].value != 'public': continue if n.attributes['kind'].value in ['variable', 'typedef']: continue if not self.get_specific_subnodes(n, 'definition'): continue name = self.extract_text(self.get_specific_subnodes(n, 'name')) if name[:8] == 'operator': continue sig = sig_prefix + name if sig in sig_dict: sig_dict[sig].append(n) else: sig_dict[sig] = [n] return sig_dict def handle_typical_memberdefs_no_overload(self, signature, memberdef_nodes): """Produce standard documentation for memberdef_nodes.""" for n in memberdef_nodes: self.add_text(['\n', '%feature("docstring") ', signature, ' "', '\n']) if self.with_function_signature: self.add_line_with_subsequent_indent(self.get_function_signature(n)) self.subnode_parse(n, pieces=[], ignore=['definition', 'name']) self.add_text(['";', '\n']) def handle_typical_memberdefs(self, signature, memberdef_nodes): """Produces docstring entries containing an "Overloaded function" section with the documentation for each overload, if the function is overloaded and self.with_overloaded_functions is set. Else, produce normal documentation. """ if len(memberdef_nodes) == 1 or not self.with_overloaded_functions: self.handle_typical_memberdefs_no_overload(signature, memberdef_nodes) return self.add_text(['\n', '%feature("docstring") ', signature, ' "', '\n']) if self.with_function_signature: for n in memberdef_nodes: self.add_line_with_subsequent_indent(self.get_function_signature(n)) self.add_text('\n') self.add_text(['Overloaded function', '\n', '-------------------']) for n in memberdef_nodes: self.add_text('\n') self.add_line_with_subsequent_indent('* ' + self.get_function_signature(n)) self.subnode_parse(n, pieces=[], indent=4, ignore=['definition', 'name']) self.add_text(['";', '\n']) # MARK: Tag handlers def do_linebreak(self, node): self.add_text(' ') def do_ndash(self, node): self.add_text('--') def do_mdash(self, node): self.add_text('---') def do_emphasis(self, node): self.surround_parse(node, '*', '*') def do_bold(self, node): self.surround_parse(node, '**', '**') def do_computeroutput(self, node): self.surround_parse(node, '`', '`') def do_heading(self, node): self.start_new_paragraph() pieces, self.pieces = self.pieces, [''] level = int(node.attributes['level'].value) self.subnode_parse(node) if level == 1: self.pieces.insert(0, '\n') self.add_text(['\n', len(''.join(self.pieces).strip()) * '=']) elif level == 2: self.add_text(['\n', len(''.join(self.pieces).strip()) * '-']) elif level >= 3: self.pieces.insert(0, level * '#' + ' ') # make following text have no gap to the heading: pieces.extend([''.join(self.pieces) + ' \n', '']) self.pieces = pieces def do_verbatim(self, node): self.start_new_paragraph() self.subnode_parse(node, pieces=[''], indent=4) def do_blockquote(self, node): self.start_new_paragraph() self.subnode_parse(node, pieces=[''], indent='> ') def do_hruler(self, node): self.start_new_paragraph() self.add_text('* * * * * \n') def do_includes(self, node): self.add_text('\nC++ includes: ') self.subnode_parse(node) self.add_text('\n') # MARK: Para tag handler # MARK: List tag handlers def do_itemizedlist(self, node): if self.listitem == '': self.start_new_paragraph() elif self.pieces != [] and self.pieces[-1:] != ['']: self.add_text('\n') listitem = self.listitem if self.listitem in ['*', '-']: self.listitem = '-' else: self.listitem = '*' self.subnode_parse(node) self.listitem = listitem def do_orderedlist(self, node): if self.listitem == '': self.start_new_paragraph() elif self.pieces != [] and self.pieces[-1:] != ['']: self.add_text('\n') listitem = self.listitem self.listitem = 0 self.subnode_parse(node) self.listitem = listitem def do_listitem(self, node): try: self.listitem = int(self.listitem) + 1 item = str(self.listitem) + '. ' except: item = str(self.listitem) + ' ' self.subnode_parse(node, item, indent=4) # MARK: Parameter list tag handlers def do_parameterlist(self, node): self.start_new_paragraph() text = 'unknown' for key, val in node.attributes.items(): if key == 'kind': if val == 'param': text = 'Parameters' elif val == 'exception': text = 'Exceptions' elif val == 'retval': text = 'Returns' else: text = val break if self.indent == 0: self.add_text([text, '\n', len(text) * '-', '\n']) else: self.add_text([text, ': \n']) self.subnode_parse(node) def do_parameteritem(self, node): self.subnode_parse(node, pieces=['* ', '']) def do_parameternamelist(self, node): self.subnode_parse(node) self.add_text([' :', ' \n']) def do_parametername(self, node): if self.pieces != [] and self.pieces != ['* ', '']: self.add_text(', ') data = self.extract_text(node) self.add_text(['`', data, '`']) def do_parameterdescription(self, node): self.subnode_parse(node, pieces=[''], indent=4) # MARK: Section tag handler def do_simplesect(self, node): kind = node.attributes['kind'].value if kind in ('date', 'rcs', 'version'): return self.start_new_paragraph() if kind == 'warning': self.subnode_parse(node, pieces=['**Warning**: ',''], indent=4) elif kind == 'see': self.subnode_parse(node, pieces=['See also: ',''], indent=4) elif kind == 'return': if self.indent == 0: pieces = ['Returns', '\n', len('Returns') * '-', '\n', ''] else: pieces = ['Returns:', '\n', ''] self.subnode_parse(node, pieces=pieces) else: self.subnode_parse(node, pieces=[kind + ': ',''], indent=4) # MARK: %feature("docstring") producing tag handlers def do_compounddef(self, node): """This produces %feature("docstring") entries for classes, and handles class, namespace and file memberdef entries specially to allow for overloaded functions. For other cases, passes parsing on to standard handlers (which may produce unexpected results). """ kind = node.attributes['kind'].value if kind in ('class', 'struct'): prot = node.attributes['prot'].value if prot != 'public': return self.add_text('\n\n') classdefn = self.extract_text(self.get_specific_subnodes(node, 'compoundname')) classname = classdefn.split('::')[-1] self.add_text('%%feature("docstring") %s "\n' % classdefn) if self.with_constructor_list: constructor_nodes = [] for n in self.get_specific_subnodes(node, 'memberdef', recursive=2): if n.attributes['prot'].value == 'public': if self.extract_text(self.get_specific_subnodes(n, 'definition')) == classdefn + '::' + classname: constructor_nodes.append(n) for n in constructor_nodes: self.add_line_with_subsequent_indent(self.get_function_signature(n)) names = ('briefdescription','detaileddescription') sub_dict = self.get_specific_nodes(node, names) for n in ('briefdescription','detaileddescription'): if n in sub_dict: self.parse(sub_dict[n]) if self.with_constructor_list: self.make_constructor_list(constructor_nodes, classname) if self.with_attribute_list: self.make_attribute_list(node) sub_list = self.get_specific_subnodes(node, 'includes') if sub_list: self.parse(sub_list[0]) self.add_text(['";', '\n']) names = ['compoundname', 'briefdescription','detaileddescription', 'includes'] self.subnode_parse(node, ignore = names) elif kind in ('file', 'namespace'): nodes = node.getElementsByTagName('sectiondef') for n in nodes: self.parse(n) # now explicitely handle possibly overloaded member functions. if kind in ['class', 'struct','file', 'namespace']: md_nodes = self.get_memberdef_nodes_and_signatures(node, kind) for sig in md_nodes: self.handle_typical_memberdefs(sig, md_nodes[sig]) def do_memberdef(self, node): """Handle cases outside of class, struct, file or namespace. These are now dealt with by `handle_overloaded_memberfunction`. Do these even exist??? """ prot = node.attributes['prot'].value id = node.attributes['id'].value kind = node.attributes['kind'].value tmp = node.parentNode.parentNode.parentNode compdef = tmp.getElementsByTagName('compounddef')[0] cdef_kind = compdef.attributes['kind'].value if cdef_kind in ('file', 'namespace', 'class', 'struct'): # These cases are now handled by `handle_typical_memberdefs` return if prot != 'public': return first = self.get_specific_nodes(node, ('definition', 'name')) name = self.extract_text(first['name']) if name[:8] == 'operator': # Don't handle operators yet. return if not 'definition' in first or kind in ['variable', 'typedef']: return data = self.extract_text(first['definition']) self.add_text('\n') self.add_text(['/* where did this entry come from??? */', '\n']) self.add_text('%feature("docstring") %s "\n%s' % (data, data)) for n in node.childNodes: if n not in first.values(): self.parse(n) self.add_text(['";', '\n']) # MARK: Entry tag handlers (dont print anything meaningful) def do_sectiondef(self, node): kind = node.attributes['kind'].value if kind in ('public-func', 'func', 'user-defined', ''): self.subnode_parse(node) def do_header(self, node): """For a user defined section def a header field is present which should not be printed as such, so we comment it in the output.""" data = self.extract_text(node) self.add_text('\n/*\n %s \n*/\n' % data) # If our immediate sibling is a 'description' node then we # should comment that out also and remove it from the parent # node's children. parent = node.parentNode idx = parent.childNodes.index(node) if len(parent.childNodes) >= idx + 2: nd = parent.childNodes[idx + 2] if nd.nodeName == 'description': nd = parent.removeChild(nd) self.add_text('\n/*') self.subnode_parse(nd) self.add_text('\n*/\n') def do_member(self, node): kind = node.attributes['kind'].value refid = node.attributes['refid'].value if kind == 'function' and refid[:9] == 'namespace': self.subnode_parse(node) def do_doxygenindex(self, node): self.multi = 1 comps = node.getElementsByTagName('compound') for c in comps: refid = c.attributes['refid'].value fname = refid + '.xml' if not os.path.exists(fname): fname = os.path.join(self.my_dir, fname) if not self.quiet: print("parsing file: %s" % fname) p = Doxy2SWIG(fname, with_function_signature = self.with_function_signature, with_type_info = self.with_type_info, with_constructor_list = self.with_constructor_list, with_attribute_list = self.with_attribute_list, with_overloaded_functions = self.with_overloaded_functions, textwidth = self.textwidth, quiet = self.quiet) p.generate() self.pieces.extend(p.pieces)
basler/pypylon
scripts/builddoxy2swig/doxy2swig/doxy2swig.py
Doxy2SWIG.do_compounddef
python
def do_compounddef(self, node): kind = node.attributes['kind'].value if kind in ('class', 'struct'): prot = node.attributes['prot'].value if prot != 'public': return self.add_text('\n\n') classdefn = self.extract_text(self.get_specific_subnodes(node, 'compoundname')) classname = classdefn.split('::')[-1] self.add_text('%%feature("docstring") %s "\n' % classdefn) if self.with_constructor_list: constructor_nodes = [] for n in self.get_specific_subnodes(node, 'memberdef', recursive=2): if n.attributes['prot'].value == 'public': if self.extract_text(self.get_specific_subnodes(n, 'definition')) == classdefn + '::' + classname: constructor_nodes.append(n) for n in constructor_nodes: self.add_line_with_subsequent_indent(self.get_function_signature(n)) names = ('briefdescription','detaileddescription') sub_dict = self.get_specific_nodes(node, names) for n in ('briefdescription','detaileddescription'): if n in sub_dict: self.parse(sub_dict[n]) if self.with_constructor_list: self.make_constructor_list(constructor_nodes, classname) if self.with_attribute_list: self.make_attribute_list(node) sub_list = self.get_specific_subnodes(node, 'includes') if sub_list: self.parse(sub_list[0]) self.add_text(['";', '\n']) names = ['compoundname', 'briefdescription','detaileddescription', 'includes'] self.subnode_parse(node, ignore = names) elif kind in ('file', 'namespace'): nodes = node.getElementsByTagName('sectiondef') for n in nodes: self.parse(n) # now explicitely handle possibly overloaded member functions. if kind in ['class', 'struct','file', 'namespace']: md_nodes = self.get_memberdef_nodes_and_signatures(node, kind) for sig in md_nodes: self.handle_typical_memberdefs(sig, md_nodes[sig])
This produces %feature("docstring") entries for classes, and handles class, namespace and file memberdef entries specially to allow for overloaded functions. For other cases, passes parsing on to standard handlers (which may produce unexpected results).
train
https://github.com/basler/pypylon/blob/d3510fa419b1c2b17f3f0b80a5fbb720c7b84008/scripts/builddoxy2swig/doxy2swig/doxy2swig.py#L645-L697
[ "def parse(self, node):\n \"\"\"Parse a given node. This function in turn calls the\n `parse_<nodeType>` functions which handle the respective\n nodes.\n\n \"\"\"\n pm = getattr(self, \"parse_%s\" % node.__class__.__name__)\n pm(node)\n", "def subnode_parse(self, node, pieces=None, indent=0, ignore=[], restrict=None):\n \"\"\"Parse the subnodes of a given node. Subnodes with tags in the\n `ignore` list are ignored. If pieces is given, use this as target for\n the parse results instead of self.pieces. Indent all lines by the amount\n given in `indent`. Note that the initial content in `pieces` is not\n indented. The final result is in any case added to self.pieces.\"\"\"\n if pieces is not None:\n old_pieces, self.pieces = self.pieces, pieces\n else:\n old_pieces = []\n if type(indent) is int:\n indent = indent * ' '\n if len(indent) > 0:\n pieces = ''.join(self.pieces)\n i_piece = pieces[:len(indent)]\n if self.pieces[-1:] == ['']:\n self.pieces = [pieces[len(indent):]] + ['']\n elif self.pieces != []:\n self.pieces = [pieces[len(indent):]]\n self.indent += len(indent)\n for n in node.childNodes:\n if restrict is not None:\n if n.nodeType == n.ELEMENT_NODE and n.tagName in restrict:\n self.parse(n)\n elif n.nodeType != n.ELEMENT_NODE or n.tagName not in ignore:\n self.parse(n)\n if len(indent) > 0:\n self.pieces = shift(self.pieces, indent, i_piece)\n self.indent -= len(indent)\n old_pieces.extend(self.pieces)\n self.pieces = old_pieces\n", "def get_specific_subnodes(self, node, name, recursive=0):\n \"\"\"Given a node and a name, return a list of child `ELEMENT_NODEs`, that\n have a `tagName` matching the `name`. Search recursively for `recursive`\n levels.\n \"\"\"\n children = [x for x in node.childNodes if x.nodeType == x.ELEMENT_NODE]\n ret = [x for x in children if x.tagName == name]\n if recursive > 0:\n for x in children:\n ret.extend(self.get_specific_subnodes(x, name, recursive-1))\n return ret\n", "def get_specific_nodes(self, node, names):\n \"\"\"Given a node and a sequence of strings in `names`, return a\n dictionary containing the names as keys and child\n `ELEMENT_NODEs`, that have a `tagName` equal to the name.\n\n \"\"\"\n nodes = [(x.tagName, x) for x in node.childNodes\n if x.nodeType == x.ELEMENT_NODE and\n x.tagName in names]\n return dict(nodes)\n", "def add_text(self, value):\n \"\"\"Adds text corresponding to `value` into `self.pieces`.\"\"\"\n if isinstance(value, (list, tuple)):\n self.pieces.extend(value)\n else:\n self.pieces.append(value)\n", "def add_line_with_subsequent_indent(self, line, indent=4):\n \"\"\"Add line of text and wrap such that subsequent lines are indented\n by `indent` spaces.\n \"\"\"\n if isinstance(line, (list, tuple)):\n line = ''.join(line)\n line = line.strip()\n width = self.textwidth-self.indent-indent\n wrapped_lines = textwrap.wrap(line[indent:], width=width)\n for i in range(len(wrapped_lines)):\n if wrapped_lines[i] != '':\n wrapped_lines[i] = indent * ' ' + wrapped_lines[i]\n self.pieces.append(line[:indent] + '\\n'.join(wrapped_lines)[indent:] + ' \\n')\n", "def extract_text(self, node):\n \"\"\"Return the string representation of the node or list of nodes by parsing the\n subnodes, but returning the result as a string instead of adding it to `self.pieces`.\n Note that this allows extracting text even if the node is in the ignore list.\n \"\"\"\n if not isinstance(node, (list, tuple)):\n node = [node]\n pieces, self.pieces = self.pieces, ['']\n for n in node:\n for sn in n.childNodes:\n self.parse(sn)\n ret = ''.join(self.pieces)\n self.pieces = pieces\n return ret\n", "def get_function_signature(self, node):\n \"\"\"Returns the function signature string for memberdef nodes.\"\"\"\n name = self.extract_text(self.get_specific_subnodes(node, 'name'))\n if self.with_type_info:\n argsstring = self.extract_text(self.get_specific_subnodes(node, 'argsstring'))\n else:\n argsstring = []\n param_id = 1\n for n_param in self.get_specific_subnodes(node, 'param'):\n declname = self.extract_text(self.get_specific_subnodes(n_param, 'declname'))\n if not declname:\n declname = 'arg' + str(param_id)\n defval = self.extract_text(self.get_specific_subnodes(n_param, 'defval'))\n if defval:\n defval = '=' + defval\n argsstring.append(declname + defval)\n param_id = param_id + 1\n argsstring = '(' + ', '.join(argsstring) + ')'\n type = self.extract_text(self.get_specific_subnodes(node, 'type'))\n function_definition = name + argsstring\n if type != '' and type != 'void':\n function_definition = function_definition + ' -> ' + type\n return '`' + function_definition + '` '\n", "def make_constructor_list(self, constructor_nodes, classname):\n \"\"\"Produces the \"Constructors\" section and the constructor signatures\n (since swig does not do so for classes) for class docstrings.\"\"\"\n if constructor_nodes == []:\n return\n self.add_text(['\\n', 'Constructors',\n '\\n', '------------'])\n for n in constructor_nodes:\n self.add_text('\\n')\n self.add_line_with_subsequent_indent('* ' + self.get_function_signature(n))\n self.subnode_parse(n, pieces = [], indent=4, ignore=['definition', 'name'])\n", "def make_attribute_list(self, node):\n \"\"\"Produces the \"Attributes\" section in class docstrings for public\n member variables (attributes).\n \"\"\"\n atr_nodes = []\n for n in self.get_specific_subnodes(node, 'memberdef', recursive=2):\n if n.attributes['kind'].value == 'variable' and n.attributes['prot'].value == 'public':\n atr_nodes.append(n)\n if not atr_nodes:\n return\n self.add_text(['\\n', 'Attributes',\n '\\n', '----------'])\n for n in atr_nodes:\n name = self.extract_text(self.get_specific_subnodes(n, 'name'))\n self.add_text(['\\n* ', '`', name, '`', ' : '])\n self.add_text(['`', self.extract_text(self.get_specific_subnodes(n, 'type')), '`'])\n self.add_text(' \\n')\n restrict = ['briefdescription', 'detaileddescription']\n self.subnode_parse(n, pieces=[''], indent=4, restrict=restrict)\n", "def get_memberdef_nodes_and_signatures(self, node, kind):\n \"\"\"Collects the memberdef nodes and corresponding signatures that\n correspond to public function entries that are at most depth 2 deeper\n than the current (compounddef) node. Returns a dictionary with \n function signatures (what swig expects after the %feature directive)\n as keys, and a list of corresponding memberdef nodes as values.\"\"\"\n sig_dict = {}\n sig_prefix = ''\n if kind in ('file', 'namespace'):\n ns_node = node.getElementsByTagName('innernamespace')\n if not ns_node and kind == 'namespace':\n ns_node = node.getElementsByTagName('compoundname')\n if ns_node:\n sig_prefix = self.extract_text(ns_node[0]) + '::'\n elif kind in ('class', 'struct'):\n # Get the full function name.\n cn_node = node.getElementsByTagName('compoundname')\n sig_prefix = self.extract_text(cn_node[0]) + '::'\n\n md_nodes = self.get_specific_subnodes(node, 'memberdef', recursive=2)\n for n in md_nodes:\n if n.attributes['prot'].value != 'public':\n continue\n if n.attributes['kind'].value in ['variable', 'typedef']:\n continue\n if not self.get_specific_subnodes(n, 'definition'):\n continue\n name = self.extract_text(self.get_specific_subnodes(n, 'name'))\n if name[:8] == 'operator':\n continue\n sig = sig_prefix + name\n if sig in sig_dict:\n sig_dict[sig].append(n)\n else:\n sig_dict[sig] = [n]\n return sig_dict\n", "def handle_typical_memberdefs(self, signature, memberdef_nodes):\n \"\"\"Produces docstring entries containing an \"Overloaded function\"\n section with the documentation for each overload, if the function is\n overloaded and self.with_overloaded_functions is set. Else, produce\n normal documentation.\n \"\"\"\n if len(memberdef_nodes) == 1 or not self.with_overloaded_functions:\n self.handle_typical_memberdefs_no_overload(signature, memberdef_nodes)\n return\n\n self.add_text(['\\n', '%feature(\"docstring\") ', signature, ' \"', '\\n'])\n if self.with_function_signature:\n for n in memberdef_nodes:\n self.add_line_with_subsequent_indent(self.get_function_signature(n))\n self.add_text('\\n')\n self.add_text(['Overloaded function', '\\n',\n '-------------------'])\n for n in memberdef_nodes:\n self.add_text('\\n')\n self.add_line_with_subsequent_indent('* ' + self.get_function_signature(n))\n self.subnode_parse(n, pieces=[], indent=4, ignore=['definition', 'name'])\n self.add_text(['\";', '\\n'])\n" ]
class Doxy2SWIG: """Converts Doxygen generated XML files into a file containing docstrings that can be used by SWIG-1.3.x that have support for feature("docstring"). Once the data is parsed it is stored in self.pieces. """ def __init__(self, src, with_function_signature = False, with_type_info = False, with_constructor_list = False, with_attribute_list = False, with_overloaded_functions = False, textwidth = 80, quiet = False): """Initialize the instance given a source object. `src` can be a file or filename. If you do not want to include function definitions from doxygen then set `include_function_definition` to `False`. This is handy since this allows you to use the swig generated function definition using %feature("autodoc", [0,1]). """ # options: self.with_function_signature = with_function_signature self.with_type_info = with_type_info self.with_constructor_list = with_constructor_list self.with_attribute_list = with_attribute_list self.with_overloaded_functions = with_overloaded_functions self.textwidth = textwidth self.quiet = quiet # state: self.indent = 0 self.listitem = '' self.pieces = [] f = my_open_read(src) self.my_dir = os.path.dirname(f.name) self.xmldoc = minidom.parse(f).documentElement f.close() self.pieces.append('\n// File: %s\n' % os.path.basename(f.name)) self.space_re = re.compile(r'\s+') self.lead_spc = re.compile(r'^(%feature\S+\s+\S+\s*?)"\s+(\S)') self.multi = 0 self.ignores = ['inheritancegraph', 'param', 'listofallmembers', 'innerclass', 'name', 'declname', 'incdepgraph', 'invincdepgraph', 'programlisting', 'type', 'references', 'referencedby', 'location', 'collaborationgraph', 'reimplements', 'reimplementedby', 'derivedcompoundref', 'basecompoundref', 'argsstring', 'definition', 'exceptions'] #self.generics = [] def generate(self): """Parses the file set in the initialization. The resulting data is stored in `self.pieces`. """ self.parse(self.xmldoc) def write(self, fname): o = my_open_write(fname) o.write(''.join(self.pieces)) o.write('\n') o.close() def parse(self, node): """Parse a given node. This function in turn calls the `parse_<nodeType>` functions which handle the respective nodes. """ pm = getattr(self, "parse_%s" % node.__class__.__name__) pm(node) def parse_Document(self, node): self.parse(node.documentElement) def parse_Text(self, node): txt = node.data if txt == ' ': # this can happen when two tags follow in a text, e.g., # " ...</emph> <formaula>$..." etc. # here we want to keep the space. self.add_text(txt) return txt = txt.replace('\\', r'\\') txt = txt.replace('"', r'\"') # ignore pure whitespace m = self.space_re.match(txt) if m and len(m.group()) == len(txt): pass else: self.add_text(txt) def parse_Comment(self, node): """Parse a `COMMENT_NODE`. This does nothing for now.""" return def parse_Element(self, node): """Parse an `ELEMENT_NODE`. This calls specific `do_<tagName>` handers for different elements. If no handler is available the `subnode_parse` method is called. All tagNames specified in `self.ignores` are simply ignored. """ name = node.tagName ignores = self.ignores if name in ignores: return attr = "do_%s" % name if hasattr(self, attr): handlerMethod = getattr(self, attr) handlerMethod(node) else: self.subnode_parse(node) #if name not in self.generics: self.generics.append(name) # MARK: Special format parsing def subnode_parse(self, node, pieces=None, indent=0, ignore=[], restrict=None): """Parse the subnodes of a given node. Subnodes with tags in the `ignore` list are ignored. If pieces is given, use this as target for the parse results instead of self.pieces. Indent all lines by the amount given in `indent`. Note that the initial content in `pieces` is not indented. The final result is in any case added to self.pieces.""" if pieces is not None: old_pieces, self.pieces = self.pieces, pieces else: old_pieces = [] if type(indent) is int: indent = indent * ' ' if len(indent) > 0: pieces = ''.join(self.pieces) i_piece = pieces[:len(indent)] if self.pieces[-1:] == ['']: self.pieces = [pieces[len(indent):]] + [''] elif self.pieces != []: self.pieces = [pieces[len(indent):]] self.indent += len(indent) for n in node.childNodes: if restrict is not None: if n.nodeType == n.ELEMENT_NODE and n.tagName in restrict: self.parse(n) elif n.nodeType != n.ELEMENT_NODE or n.tagName not in ignore: self.parse(n) if len(indent) > 0: self.pieces = shift(self.pieces, indent, i_piece) self.indent -= len(indent) old_pieces.extend(self.pieces) self.pieces = old_pieces def surround_parse(self, node, pre_char, post_char): """Parse the subnodes of a given node. Subnodes with tags in the `ignore` list are ignored. Prepend `pre_char` and append `post_char` to the output in self.pieces.""" self.add_text(pre_char) self.subnode_parse(node) self.add_text(post_char) # MARK: Helper functions def get_specific_subnodes(self, node, name, recursive=0): """Given a node and a name, return a list of child `ELEMENT_NODEs`, that have a `tagName` matching the `name`. Search recursively for `recursive` levels. """ children = [x for x in node.childNodes if x.nodeType == x.ELEMENT_NODE] ret = [x for x in children if x.tagName == name] if recursive > 0: for x in children: ret.extend(self.get_specific_subnodes(x, name, recursive-1)) return ret def get_specific_nodes(self, node, names): """Given a node and a sequence of strings in `names`, return a dictionary containing the names as keys and child `ELEMENT_NODEs`, that have a `tagName` equal to the name. """ nodes = [(x.tagName, x) for x in node.childNodes if x.nodeType == x.ELEMENT_NODE and x.tagName in names] return dict(nodes) def add_text(self, value): """Adds text corresponding to `value` into `self.pieces`.""" if isinstance(value, (list, tuple)): self.pieces.extend(value) else: self.pieces.append(value) def start_new_paragraph(self): """Make sure to create an empty line. This is overridden, if the previous text ends with the special marker ''. In that case, nothing is done. """ if self.pieces[-1:] == ['']: # respect special marker return elif self.pieces == []: # first paragraph, add '\n', override with '' self.pieces = ['\n'] elif self.pieces[-1][-1:] != '\n': # previous line not ended self.pieces.extend([' \n' ,'\n']) else: #default self.pieces.append('\n') def add_line_with_subsequent_indent(self, line, indent=4): """Add line of text and wrap such that subsequent lines are indented by `indent` spaces. """ if isinstance(line, (list, tuple)): line = ''.join(line) line = line.strip() width = self.textwidth-self.indent-indent wrapped_lines = textwrap.wrap(line[indent:], width=width) for i in range(len(wrapped_lines)): if wrapped_lines[i] != '': wrapped_lines[i] = indent * ' ' + wrapped_lines[i] self.pieces.append(line[:indent] + '\n'.join(wrapped_lines)[indent:] + ' \n') def extract_text(self, node): """Return the string representation of the node or list of nodes by parsing the subnodes, but returning the result as a string instead of adding it to `self.pieces`. Note that this allows extracting text even if the node is in the ignore list. """ if not isinstance(node, (list, tuple)): node = [node] pieces, self.pieces = self.pieces, [''] for n in node: for sn in n.childNodes: self.parse(sn) ret = ''.join(self.pieces) self.pieces = pieces return ret def get_function_signature(self, node): """Returns the function signature string for memberdef nodes.""" name = self.extract_text(self.get_specific_subnodes(node, 'name')) if self.with_type_info: argsstring = self.extract_text(self.get_specific_subnodes(node, 'argsstring')) else: argsstring = [] param_id = 1 for n_param in self.get_specific_subnodes(node, 'param'): declname = self.extract_text(self.get_specific_subnodes(n_param, 'declname')) if not declname: declname = 'arg' + str(param_id) defval = self.extract_text(self.get_specific_subnodes(n_param, 'defval')) if defval: defval = '=' + defval argsstring.append(declname + defval) param_id = param_id + 1 argsstring = '(' + ', '.join(argsstring) + ')' type = self.extract_text(self.get_specific_subnodes(node, 'type')) function_definition = name + argsstring if type != '' and type != 'void': function_definition = function_definition + ' -> ' + type return '`' + function_definition + '` ' # MARK: Special parsing tasks (need to be called manually) def make_constructor_list(self, constructor_nodes, classname): """Produces the "Constructors" section and the constructor signatures (since swig does not do so for classes) for class docstrings.""" if constructor_nodes == []: return self.add_text(['\n', 'Constructors', '\n', '------------']) for n in constructor_nodes: self.add_text('\n') self.add_line_with_subsequent_indent('* ' + self.get_function_signature(n)) self.subnode_parse(n, pieces = [], indent=4, ignore=['definition', 'name']) def make_attribute_list(self, node): """Produces the "Attributes" section in class docstrings for public member variables (attributes). """ atr_nodes = [] for n in self.get_specific_subnodes(node, 'memberdef', recursive=2): if n.attributes['kind'].value == 'variable' and n.attributes['prot'].value == 'public': atr_nodes.append(n) if not atr_nodes: return self.add_text(['\n', 'Attributes', '\n', '----------']) for n in atr_nodes: name = self.extract_text(self.get_specific_subnodes(n, 'name')) self.add_text(['\n* ', '`', name, '`', ' : ']) self.add_text(['`', self.extract_text(self.get_specific_subnodes(n, 'type')), '`']) self.add_text(' \n') restrict = ['briefdescription', 'detaileddescription'] self.subnode_parse(n, pieces=[''], indent=4, restrict=restrict) def get_memberdef_nodes_and_signatures(self, node, kind): """Collects the memberdef nodes and corresponding signatures that correspond to public function entries that are at most depth 2 deeper than the current (compounddef) node. Returns a dictionary with function signatures (what swig expects after the %feature directive) as keys, and a list of corresponding memberdef nodes as values.""" sig_dict = {} sig_prefix = '' if kind in ('file', 'namespace'): ns_node = node.getElementsByTagName('innernamespace') if not ns_node and kind == 'namespace': ns_node = node.getElementsByTagName('compoundname') if ns_node: sig_prefix = self.extract_text(ns_node[0]) + '::' elif kind in ('class', 'struct'): # Get the full function name. cn_node = node.getElementsByTagName('compoundname') sig_prefix = self.extract_text(cn_node[0]) + '::' md_nodes = self.get_specific_subnodes(node, 'memberdef', recursive=2) for n in md_nodes: if n.attributes['prot'].value != 'public': continue if n.attributes['kind'].value in ['variable', 'typedef']: continue if not self.get_specific_subnodes(n, 'definition'): continue name = self.extract_text(self.get_specific_subnodes(n, 'name')) if name[:8] == 'operator': continue sig = sig_prefix + name if sig in sig_dict: sig_dict[sig].append(n) else: sig_dict[sig] = [n] return sig_dict def handle_typical_memberdefs_no_overload(self, signature, memberdef_nodes): """Produce standard documentation for memberdef_nodes.""" for n in memberdef_nodes: self.add_text(['\n', '%feature("docstring") ', signature, ' "', '\n']) if self.with_function_signature: self.add_line_with_subsequent_indent(self.get_function_signature(n)) self.subnode_parse(n, pieces=[], ignore=['definition', 'name']) self.add_text(['";', '\n']) def handle_typical_memberdefs(self, signature, memberdef_nodes): """Produces docstring entries containing an "Overloaded function" section with the documentation for each overload, if the function is overloaded and self.with_overloaded_functions is set. Else, produce normal documentation. """ if len(memberdef_nodes) == 1 or not self.with_overloaded_functions: self.handle_typical_memberdefs_no_overload(signature, memberdef_nodes) return self.add_text(['\n', '%feature("docstring") ', signature, ' "', '\n']) if self.with_function_signature: for n in memberdef_nodes: self.add_line_with_subsequent_indent(self.get_function_signature(n)) self.add_text('\n') self.add_text(['Overloaded function', '\n', '-------------------']) for n in memberdef_nodes: self.add_text('\n') self.add_line_with_subsequent_indent('* ' + self.get_function_signature(n)) self.subnode_parse(n, pieces=[], indent=4, ignore=['definition', 'name']) self.add_text(['";', '\n']) # MARK: Tag handlers def do_linebreak(self, node): self.add_text(' ') def do_ndash(self, node): self.add_text('--') def do_mdash(self, node): self.add_text('---') def do_emphasis(self, node): self.surround_parse(node, '*', '*') def do_bold(self, node): self.surround_parse(node, '**', '**') def do_computeroutput(self, node): self.surround_parse(node, '`', '`') def do_heading(self, node): self.start_new_paragraph() pieces, self.pieces = self.pieces, [''] level = int(node.attributes['level'].value) self.subnode_parse(node) if level == 1: self.pieces.insert(0, '\n') self.add_text(['\n', len(''.join(self.pieces).strip()) * '=']) elif level == 2: self.add_text(['\n', len(''.join(self.pieces).strip()) * '-']) elif level >= 3: self.pieces.insert(0, level * '#' + ' ') # make following text have no gap to the heading: pieces.extend([''.join(self.pieces) + ' \n', '']) self.pieces = pieces def do_verbatim(self, node): self.start_new_paragraph() self.subnode_parse(node, pieces=[''], indent=4) def do_blockquote(self, node): self.start_new_paragraph() self.subnode_parse(node, pieces=[''], indent='> ') def do_hruler(self, node): self.start_new_paragraph() self.add_text('* * * * * \n') def do_includes(self, node): self.add_text('\nC++ includes: ') self.subnode_parse(node) self.add_text('\n') # MARK: Para tag handler def do_para(self, node): """This is the only place where text wrapping is automatically performed. Generally, this function parses the node (locally), wraps the text, and then adds the result to self.pieces. However, it may be convenient to allow the previous content of self.pieces to be included in the text wrapping. For this, use the following *convention*: If self.pieces ends with '', treat the _previous_ entry as part of the current paragraph. Else, insert new-line and start a new paragraph and "wrapping context". Paragraphs always end with ' \n', but if the parsed content ends with the special symbol '', this is passed on. """ if self.pieces[-1:] == ['']: pieces, self.pieces = self.pieces[:-2], self.pieces[-2:-1] else: self.add_text('\n') pieces, self.pieces = self.pieces, [''] self.subnode_parse(node) dont_end_paragraph = self.pieces[-1:] == [''] # Now do the text wrapping: width = self.textwidth - self.indent wrapped_para = [] for line in ''.join(self.pieces).splitlines(): keep_markdown_newline = line[-2:] == ' ' w_line = textwrap.wrap(line, width=width, break_long_words=False) if w_line == []: w_line = [''] if keep_markdown_newline: w_line[-1] = w_line[-1] + ' ' for wl in w_line: wrapped_para.append(wl + '\n') if wrapped_para: if wrapped_para[-1][-3:] != ' \n': wrapped_para[-1] = wrapped_para[-1][:-1] + ' \n' if dont_end_paragraph: wrapped_para.append('') pieces.extend(wrapped_para) self.pieces = pieces # MARK: List tag handlers def do_itemizedlist(self, node): if self.listitem == '': self.start_new_paragraph() elif self.pieces != [] and self.pieces[-1:] != ['']: self.add_text('\n') listitem = self.listitem if self.listitem in ['*', '-']: self.listitem = '-' else: self.listitem = '*' self.subnode_parse(node) self.listitem = listitem def do_orderedlist(self, node): if self.listitem == '': self.start_new_paragraph() elif self.pieces != [] and self.pieces[-1:] != ['']: self.add_text('\n') listitem = self.listitem self.listitem = 0 self.subnode_parse(node) self.listitem = listitem def do_listitem(self, node): try: self.listitem = int(self.listitem) + 1 item = str(self.listitem) + '. ' except: item = str(self.listitem) + ' ' self.subnode_parse(node, item, indent=4) # MARK: Parameter list tag handlers def do_parameterlist(self, node): self.start_new_paragraph() text = 'unknown' for key, val in node.attributes.items(): if key == 'kind': if val == 'param': text = 'Parameters' elif val == 'exception': text = 'Exceptions' elif val == 'retval': text = 'Returns' else: text = val break if self.indent == 0: self.add_text([text, '\n', len(text) * '-', '\n']) else: self.add_text([text, ': \n']) self.subnode_parse(node) def do_parameteritem(self, node): self.subnode_parse(node, pieces=['* ', '']) def do_parameternamelist(self, node): self.subnode_parse(node) self.add_text([' :', ' \n']) def do_parametername(self, node): if self.pieces != [] and self.pieces != ['* ', '']: self.add_text(', ') data = self.extract_text(node) self.add_text(['`', data, '`']) def do_parameterdescription(self, node): self.subnode_parse(node, pieces=[''], indent=4) # MARK: Section tag handler def do_simplesect(self, node): kind = node.attributes['kind'].value if kind in ('date', 'rcs', 'version'): return self.start_new_paragraph() if kind == 'warning': self.subnode_parse(node, pieces=['**Warning**: ',''], indent=4) elif kind == 'see': self.subnode_parse(node, pieces=['See also: ',''], indent=4) elif kind == 'return': if self.indent == 0: pieces = ['Returns', '\n', len('Returns') * '-', '\n', ''] else: pieces = ['Returns:', '\n', ''] self.subnode_parse(node, pieces=pieces) else: self.subnode_parse(node, pieces=[kind + ': ',''], indent=4) # MARK: %feature("docstring") producing tag handlers def do_memberdef(self, node): """Handle cases outside of class, struct, file or namespace. These are now dealt with by `handle_overloaded_memberfunction`. Do these even exist??? """ prot = node.attributes['prot'].value id = node.attributes['id'].value kind = node.attributes['kind'].value tmp = node.parentNode.parentNode.parentNode compdef = tmp.getElementsByTagName('compounddef')[0] cdef_kind = compdef.attributes['kind'].value if cdef_kind in ('file', 'namespace', 'class', 'struct'): # These cases are now handled by `handle_typical_memberdefs` return if prot != 'public': return first = self.get_specific_nodes(node, ('definition', 'name')) name = self.extract_text(first['name']) if name[:8] == 'operator': # Don't handle operators yet. return if not 'definition' in first or kind in ['variable', 'typedef']: return data = self.extract_text(first['definition']) self.add_text('\n') self.add_text(['/* where did this entry come from??? */', '\n']) self.add_text('%feature("docstring") %s "\n%s' % (data, data)) for n in node.childNodes: if n not in first.values(): self.parse(n) self.add_text(['";', '\n']) # MARK: Entry tag handlers (dont print anything meaningful) def do_sectiondef(self, node): kind = node.attributes['kind'].value if kind in ('public-func', 'func', 'user-defined', ''): self.subnode_parse(node) def do_header(self, node): """For a user defined section def a header field is present which should not be printed as such, so we comment it in the output.""" data = self.extract_text(node) self.add_text('\n/*\n %s \n*/\n' % data) # If our immediate sibling is a 'description' node then we # should comment that out also and remove it from the parent # node's children. parent = node.parentNode idx = parent.childNodes.index(node) if len(parent.childNodes) >= idx + 2: nd = parent.childNodes[idx + 2] if nd.nodeName == 'description': nd = parent.removeChild(nd) self.add_text('\n/*') self.subnode_parse(nd) self.add_text('\n*/\n') def do_member(self, node): kind = node.attributes['kind'].value refid = node.attributes['refid'].value if kind == 'function' and refid[:9] == 'namespace': self.subnode_parse(node) def do_doxygenindex(self, node): self.multi = 1 comps = node.getElementsByTagName('compound') for c in comps: refid = c.attributes['refid'].value fname = refid + '.xml' if not os.path.exists(fname): fname = os.path.join(self.my_dir, fname) if not self.quiet: print("parsing file: %s" % fname) p = Doxy2SWIG(fname, with_function_signature = self.with_function_signature, with_type_info = self.with_type_info, with_constructor_list = self.with_constructor_list, with_attribute_list = self.with_attribute_list, with_overloaded_functions = self.with_overloaded_functions, textwidth = self.textwidth, quiet = self.quiet) p.generate() self.pieces.extend(p.pieces)
basler/pypylon
scripts/builddoxy2swig/doxy2swig/doxy2swig.py
Doxy2SWIG.do_memberdef
python
def do_memberdef(self, node): prot = node.attributes['prot'].value id = node.attributes['id'].value kind = node.attributes['kind'].value tmp = node.parentNode.parentNode.parentNode compdef = tmp.getElementsByTagName('compounddef')[0] cdef_kind = compdef.attributes['kind'].value if cdef_kind in ('file', 'namespace', 'class', 'struct'): # These cases are now handled by `handle_typical_memberdefs` return if prot != 'public': return first = self.get_specific_nodes(node, ('definition', 'name')) name = self.extract_text(first['name']) if name[:8] == 'operator': # Don't handle operators yet. return if not 'definition' in first or kind in ['variable', 'typedef']: return data = self.extract_text(first['definition']) self.add_text('\n') self.add_text(['/* where did this entry come from??? */', '\n']) self.add_text('%feature("docstring") %s "\n%s' % (data, data)) for n in node.childNodes: if n not in first.values(): self.parse(n) self.add_text(['";', '\n'])
Handle cases outside of class, struct, file or namespace. These are now dealt with by `handle_overloaded_memberfunction`. Do these even exist???
train
https://github.com/basler/pypylon/blob/d3510fa419b1c2b17f3f0b80a5fbb720c7b84008/scripts/builddoxy2swig/doxy2swig/doxy2swig.py#L699-L730
[ "def parse(self, node):\n \"\"\"Parse a given node. This function in turn calls the\n `parse_<nodeType>` functions which handle the respective\n nodes.\n\n \"\"\"\n pm = getattr(self, \"parse_%s\" % node.__class__.__name__)\n pm(node)\n", "def get_specific_nodes(self, node, names):\n \"\"\"Given a node and a sequence of strings in `names`, return a\n dictionary containing the names as keys and child\n `ELEMENT_NODEs`, that have a `tagName` equal to the name.\n\n \"\"\"\n nodes = [(x.tagName, x) for x in node.childNodes\n if x.nodeType == x.ELEMENT_NODE and\n x.tagName in names]\n return dict(nodes)\n", "def add_text(self, value):\n \"\"\"Adds text corresponding to `value` into `self.pieces`.\"\"\"\n if isinstance(value, (list, tuple)):\n self.pieces.extend(value)\n else:\n self.pieces.append(value)\n", "def extract_text(self, node):\n \"\"\"Return the string representation of the node or list of nodes by parsing the\n subnodes, but returning the result as a string instead of adding it to `self.pieces`.\n Note that this allows extracting text even if the node is in the ignore list.\n \"\"\"\n if not isinstance(node, (list, tuple)):\n node = [node]\n pieces, self.pieces = self.pieces, ['']\n for n in node:\n for sn in n.childNodes:\n self.parse(sn)\n ret = ''.join(self.pieces)\n self.pieces = pieces\n return ret\n" ]
class Doxy2SWIG: """Converts Doxygen generated XML files into a file containing docstrings that can be used by SWIG-1.3.x that have support for feature("docstring"). Once the data is parsed it is stored in self.pieces. """ def __init__(self, src, with_function_signature = False, with_type_info = False, with_constructor_list = False, with_attribute_list = False, with_overloaded_functions = False, textwidth = 80, quiet = False): """Initialize the instance given a source object. `src` can be a file or filename. If you do not want to include function definitions from doxygen then set `include_function_definition` to `False`. This is handy since this allows you to use the swig generated function definition using %feature("autodoc", [0,1]). """ # options: self.with_function_signature = with_function_signature self.with_type_info = with_type_info self.with_constructor_list = with_constructor_list self.with_attribute_list = with_attribute_list self.with_overloaded_functions = with_overloaded_functions self.textwidth = textwidth self.quiet = quiet # state: self.indent = 0 self.listitem = '' self.pieces = [] f = my_open_read(src) self.my_dir = os.path.dirname(f.name) self.xmldoc = minidom.parse(f).documentElement f.close() self.pieces.append('\n// File: %s\n' % os.path.basename(f.name)) self.space_re = re.compile(r'\s+') self.lead_spc = re.compile(r'^(%feature\S+\s+\S+\s*?)"\s+(\S)') self.multi = 0 self.ignores = ['inheritancegraph', 'param', 'listofallmembers', 'innerclass', 'name', 'declname', 'incdepgraph', 'invincdepgraph', 'programlisting', 'type', 'references', 'referencedby', 'location', 'collaborationgraph', 'reimplements', 'reimplementedby', 'derivedcompoundref', 'basecompoundref', 'argsstring', 'definition', 'exceptions'] #self.generics = [] def generate(self): """Parses the file set in the initialization. The resulting data is stored in `self.pieces`. """ self.parse(self.xmldoc) def write(self, fname): o = my_open_write(fname) o.write(''.join(self.pieces)) o.write('\n') o.close() def parse(self, node): """Parse a given node. This function in turn calls the `parse_<nodeType>` functions which handle the respective nodes. """ pm = getattr(self, "parse_%s" % node.__class__.__name__) pm(node) def parse_Document(self, node): self.parse(node.documentElement) def parse_Text(self, node): txt = node.data if txt == ' ': # this can happen when two tags follow in a text, e.g., # " ...</emph> <formaula>$..." etc. # here we want to keep the space. self.add_text(txt) return txt = txt.replace('\\', r'\\') txt = txt.replace('"', r'\"') # ignore pure whitespace m = self.space_re.match(txt) if m and len(m.group()) == len(txt): pass else: self.add_text(txt) def parse_Comment(self, node): """Parse a `COMMENT_NODE`. This does nothing for now.""" return def parse_Element(self, node): """Parse an `ELEMENT_NODE`. This calls specific `do_<tagName>` handers for different elements. If no handler is available the `subnode_parse` method is called. All tagNames specified in `self.ignores` are simply ignored. """ name = node.tagName ignores = self.ignores if name in ignores: return attr = "do_%s" % name if hasattr(self, attr): handlerMethod = getattr(self, attr) handlerMethod(node) else: self.subnode_parse(node) #if name not in self.generics: self.generics.append(name) # MARK: Special format parsing def subnode_parse(self, node, pieces=None, indent=0, ignore=[], restrict=None): """Parse the subnodes of a given node. Subnodes with tags in the `ignore` list are ignored. If pieces is given, use this as target for the parse results instead of self.pieces. Indent all lines by the amount given in `indent`. Note that the initial content in `pieces` is not indented. The final result is in any case added to self.pieces.""" if pieces is not None: old_pieces, self.pieces = self.pieces, pieces else: old_pieces = [] if type(indent) is int: indent = indent * ' ' if len(indent) > 0: pieces = ''.join(self.pieces) i_piece = pieces[:len(indent)] if self.pieces[-1:] == ['']: self.pieces = [pieces[len(indent):]] + [''] elif self.pieces != []: self.pieces = [pieces[len(indent):]] self.indent += len(indent) for n in node.childNodes: if restrict is not None: if n.nodeType == n.ELEMENT_NODE and n.tagName in restrict: self.parse(n) elif n.nodeType != n.ELEMENT_NODE or n.tagName not in ignore: self.parse(n) if len(indent) > 0: self.pieces = shift(self.pieces, indent, i_piece) self.indent -= len(indent) old_pieces.extend(self.pieces) self.pieces = old_pieces def surround_parse(self, node, pre_char, post_char): """Parse the subnodes of a given node. Subnodes with tags in the `ignore` list are ignored. Prepend `pre_char` and append `post_char` to the output in self.pieces.""" self.add_text(pre_char) self.subnode_parse(node) self.add_text(post_char) # MARK: Helper functions def get_specific_subnodes(self, node, name, recursive=0): """Given a node and a name, return a list of child `ELEMENT_NODEs`, that have a `tagName` matching the `name`. Search recursively for `recursive` levels. """ children = [x for x in node.childNodes if x.nodeType == x.ELEMENT_NODE] ret = [x for x in children if x.tagName == name] if recursive > 0: for x in children: ret.extend(self.get_specific_subnodes(x, name, recursive-1)) return ret def get_specific_nodes(self, node, names): """Given a node and a sequence of strings in `names`, return a dictionary containing the names as keys and child `ELEMENT_NODEs`, that have a `tagName` equal to the name. """ nodes = [(x.tagName, x) for x in node.childNodes if x.nodeType == x.ELEMENT_NODE and x.tagName in names] return dict(nodes) def add_text(self, value): """Adds text corresponding to `value` into `self.pieces`.""" if isinstance(value, (list, tuple)): self.pieces.extend(value) else: self.pieces.append(value) def start_new_paragraph(self): """Make sure to create an empty line. This is overridden, if the previous text ends with the special marker ''. In that case, nothing is done. """ if self.pieces[-1:] == ['']: # respect special marker return elif self.pieces == []: # first paragraph, add '\n', override with '' self.pieces = ['\n'] elif self.pieces[-1][-1:] != '\n': # previous line not ended self.pieces.extend([' \n' ,'\n']) else: #default self.pieces.append('\n') def add_line_with_subsequent_indent(self, line, indent=4): """Add line of text and wrap such that subsequent lines are indented by `indent` spaces. """ if isinstance(line, (list, tuple)): line = ''.join(line) line = line.strip() width = self.textwidth-self.indent-indent wrapped_lines = textwrap.wrap(line[indent:], width=width) for i in range(len(wrapped_lines)): if wrapped_lines[i] != '': wrapped_lines[i] = indent * ' ' + wrapped_lines[i] self.pieces.append(line[:indent] + '\n'.join(wrapped_lines)[indent:] + ' \n') def extract_text(self, node): """Return the string representation of the node or list of nodes by parsing the subnodes, but returning the result as a string instead of adding it to `self.pieces`. Note that this allows extracting text even if the node is in the ignore list. """ if not isinstance(node, (list, tuple)): node = [node] pieces, self.pieces = self.pieces, [''] for n in node: for sn in n.childNodes: self.parse(sn) ret = ''.join(self.pieces) self.pieces = pieces return ret def get_function_signature(self, node): """Returns the function signature string for memberdef nodes.""" name = self.extract_text(self.get_specific_subnodes(node, 'name')) if self.with_type_info: argsstring = self.extract_text(self.get_specific_subnodes(node, 'argsstring')) else: argsstring = [] param_id = 1 for n_param in self.get_specific_subnodes(node, 'param'): declname = self.extract_text(self.get_specific_subnodes(n_param, 'declname')) if not declname: declname = 'arg' + str(param_id) defval = self.extract_text(self.get_specific_subnodes(n_param, 'defval')) if defval: defval = '=' + defval argsstring.append(declname + defval) param_id = param_id + 1 argsstring = '(' + ', '.join(argsstring) + ')' type = self.extract_text(self.get_specific_subnodes(node, 'type')) function_definition = name + argsstring if type != '' and type != 'void': function_definition = function_definition + ' -> ' + type return '`' + function_definition + '` ' # MARK: Special parsing tasks (need to be called manually) def make_constructor_list(self, constructor_nodes, classname): """Produces the "Constructors" section and the constructor signatures (since swig does not do so for classes) for class docstrings.""" if constructor_nodes == []: return self.add_text(['\n', 'Constructors', '\n', '------------']) for n in constructor_nodes: self.add_text('\n') self.add_line_with_subsequent_indent('* ' + self.get_function_signature(n)) self.subnode_parse(n, pieces = [], indent=4, ignore=['definition', 'name']) def make_attribute_list(self, node): """Produces the "Attributes" section in class docstrings for public member variables (attributes). """ atr_nodes = [] for n in self.get_specific_subnodes(node, 'memberdef', recursive=2): if n.attributes['kind'].value == 'variable' and n.attributes['prot'].value == 'public': atr_nodes.append(n) if not atr_nodes: return self.add_text(['\n', 'Attributes', '\n', '----------']) for n in atr_nodes: name = self.extract_text(self.get_specific_subnodes(n, 'name')) self.add_text(['\n* ', '`', name, '`', ' : ']) self.add_text(['`', self.extract_text(self.get_specific_subnodes(n, 'type')), '`']) self.add_text(' \n') restrict = ['briefdescription', 'detaileddescription'] self.subnode_parse(n, pieces=[''], indent=4, restrict=restrict) def get_memberdef_nodes_and_signatures(self, node, kind): """Collects the memberdef nodes and corresponding signatures that correspond to public function entries that are at most depth 2 deeper than the current (compounddef) node. Returns a dictionary with function signatures (what swig expects after the %feature directive) as keys, and a list of corresponding memberdef nodes as values.""" sig_dict = {} sig_prefix = '' if kind in ('file', 'namespace'): ns_node = node.getElementsByTagName('innernamespace') if not ns_node and kind == 'namespace': ns_node = node.getElementsByTagName('compoundname') if ns_node: sig_prefix = self.extract_text(ns_node[0]) + '::' elif kind in ('class', 'struct'): # Get the full function name. cn_node = node.getElementsByTagName('compoundname') sig_prefix = self.extract_text(cn_node[0]) + '::' md_nodes = self.get_specific_subnodes(node, 'memberdef', recursive=2) for n in md_nodes: if n.attributes['prot'].value != 'public': continue if n.attributes['kind'].value in ['variable', 'typedef']: continue if not self.get_specific_subnodes(n, 'definition'): continue name = self.extract_text(self.get_specific_subnodes(n, 'name')) if name[:8] == 'operator': continue sig = sig_prefix + name if sig in sig_dict: sig_dict[sig].append(n) else: sig_dict[sig] = [n] return sig_dict def handle_typical_memberdefs_no_overload(self, signature, memberdef_nodes): """Produce standard documentation for memberdef_nodes.""" for n in memberdef_nodes: self.add_text(['\n', '%feature("docstring") ', signature, ' "', '\n']) if self.with_function_signature: self.add_line_with_subsequent_indent(self.get_function_signature(n)) self.subnode_parse(n, pieces=[], ignore=['definition', 'name']) self.add_text(['";', '\n']) def handle_typical_memberdefs(self, signature, memberdef_nodes): """Produces docstring entries containing an "Overloaded function" section with the documentation for each overload, if the function is overloaded and self.with_overloaded_functions is set. Else, produce normal documentation. """ if len(memberdef_nodes) == 1 or not self.with_overloaded_functions: self.handle_typical_memberdefs_no_overload(signature, memberdef_nodes) return self.add_text(['\n', '%feature("docstring") ', signature, ' "', '\n']) if self.with_function_signature: for n in memberdef_nodes: self.add_line_with_subsequent_indent(self.get_function_signature(n)) self.add_text('\n') self.add_text(['Overloaded function', '\n', '-------------------']) for n in memberdef_nodes: self.add_text('\n') self.add_line_with_subsequent_indent('* ' + self.get_function_signature(n)) self.subnode_parse(n, pieces=[], indent=4, ignore=['definition', 'name']) self.add_text(['";', '\n']) # MARK: Tag handlers def do_linebreak(self, node): self.add_text(' ') def do_ndash(self, node): self.add_text('--') def do_mdash(self, node): self.add_text('---') def do_emphasis(self, node): self.surround_parse(node, '*', '*') def do_bold(self, node): self.surround_parse(node, '**', '**') def do_computeroutput(self, node): self.surround_parse(node, '`', '`') def do_heading(self, node): self.start_new_paragraph() pieces, self.pieces = self.pieces, [''] level = int(node.attributes['level'].value) self.subnode_parse(node) if level == 1: self.pieces.insert(0, '\n') self.add_text(['\n', len(''.join(self.pieces).strip()) * '=']) elif level == 2: self.add_text(['\n', len(''.join(self.pieces).strip()) * '-']) elif level >= 3: self.pieces.insert(0, level * '#' + ' ') # make following text have no gap to the heading: pieces.extend([''.join(self.pieces) + ' \n', '']) self.pieces = pieces def do_verbatim(self, node): self.start_new_paragraph() self.subnode_parse(node, pieces=[''], indent=4) def do_blockquote(self, node): self.start_new_paragraph() self.subnode_parse(node, pieces=[''], indent='> ') def do_hruler(self, node): self.start_new_paragraph() self.add_text('* * * * * \n') def do_includes(self, node): self.add_text('\nC++ includes: ') self.subnode_parse(node) self.add_text('\n') # MARK: Para tag handler def do_para(self, node): """This is the only place where text wrapping is automatically performed. Generally, this function parses the node (locally), wraps the text, and then adds the result to self.pieces. However, it may be convenient to allow the previous content of self.pieces to be included in the text wrapping. For this, use the following *convention*: If self.pieces ends with '', treat the _previous_ entry as part of the current paragraph. Else, insert new-line and start a new paragraph and "wrapping context". Paragraphs always end with ' \n', but if the parsed content ends with the special symbol '', this is passed on. """ if self.pieces[-1:] == ['']: pieces, self.pieces = self.pieces[:-2], self.pieces[-2:-1] else: self.add_text('\n') pieces, self.pieces = self.pieces, [''] self.subnode_parse(node) dont_end_paragraph = self.pieces[-1:] == [''] # Now do the text wrapping: width = self.textwidth - self.indent wrapped_para = [] for line in ''.join(self.pieces).splitlines(): keep_markdown_newline = line[-2:] == ' ' w_line = textwrap.wrap(line, width=width, break_long_words=False) if w_line == []: w_line = [''] if keep_markdown_newline: w_line[-1] = w_line[-1] + ' ' for wl in w_line: wrapped_para.append(wl + '\n') if wrapped_para: if wrapped_para[-1][-3:] != ' \n': wrapped_para[-1] = wrapped_para[-1][:-1] + ' \n' if dont_end_paragraph: wrapped_para.append('') pieces.extend(wrapped_para) self.pieces = pieces # MARK: List tag handlers def do_itemizedlist(self, node): if self.listitem == '': self.start_new_paragraph() elif self.pieces != [] and self.pieces[-1:] != ['']: self.add_text('\n') listitem = self.listitem if self.listitem in ['*', '-']: self.listitem = '-' else: self.listitem = '*' self.subnode_parse(node) self.listitem = listitem def do_orderedlist(self, node): if self.listitem == '': self.start_new_paragraph() elif self.pieces != [] and self.pieces[-1:] != ['']: self.add_text('\n') listitem = self.listitem self.listitem = 0 self.subnode_parse(node) self.listitem = listitem def do_listitem(self, node): try: self.listitem = int(self.listitem) + 1 item = str(self.listitem) + '. ' except: item = str(self.listitem) + ' ' self.subnode_parse(node, item, indent=4) # MARK: Parameter list tag handlers def do_parameterlist(self, node): self.start_new_paragraph() text = 'unknown' for key, val in node.attributes.items(): if key == 'kind': if val == 'param': text = 'Parameters' elif val == 'exception': text = 'Exceptions' elif val == 'retval': text = 'Returns' else: text = val break if self.indent == 0: self.add_text([text, '\n', len(text) * '-', '\n']) else: self.add_text([text, ': \n']) self.subnode_parse(node) def do_parameteritem(self, node): self.subnode_parse(node, pieces=['* ', '']) def do_parameternamelist(self, node): self.subnode_parse(node) self.add_text([' :', ' \n']) def do_parametername(self, node): if self.pieces != [] and self.pieces != ['* ', '']: self.add_text(', ') data = self.extract_text(node) self.add_text(['`', data, '`']) def do_parameterdescription(self, node): self.subnode_parse(node, pieces=[''], indent=4) # MARK: Section tag handler def do_simplesect(self, node): kind = node.attributes['kind'].value if kind in ('date', 'rcs', 'version'): return self.start_new_paragraph() if kind == 'warning': self.subnode_parse(node, pieces=['**Warning**: ',''], indent=4) elif kind == 'see': self.subnode_parse(node, pieces=['See also: ',''], indent=4) elif kind == 'return': if self.indent == 0: pieces = ['Returns', '\n', len('Returns') * '-', '\n', ''] else: pieces = ['Returns:', '\n', ''] self.subnode_parse(node, pieces=pieces) else: self.subnode_parse(node, pieces=[kind + ': ',''], indent=4) # MARK: %feature("docstring") producing tag handlers def do_compounddef(self, node): """This produces %feature("docstring") entries for classes, and handles class, namespace and file memberdef entries specially to allow for overloaded functions. For other cases, passes parsing on to standard handlers (which may produce unexpected results). """ kind = node.attributes['kind'].value if kind in ('class', 'struct'): prot = node.attributes['prot'].value if prot != 'public': return self.add_text('\n\n') classdefn = self.extract_text(self.get_specific_subnodes(node, 'compoundname')) classname = classdefn.split('::')[-1] self.add_text('%%feature("docstring") %s "\n' % classdefn) if self.with_constructor_list: constructor_nodes = [] for n in self.get_specific_subnodes(node, 'memberdef', recursive=2): if n.attributes['prot'].value == 'public': if self.extract_text(self.get_specific_subnodes(n, 'definition')) == classdefn + '::' + classname: constructor_nodes.append(n) for n in constructor_nodes: self.add_line_with_subsequent_indent(self.get_function_signature(n)) names = ('briefdescription','detaileddescription') sub_dict = self.get_specific_nodes(node, names) for n in ('briefdescription','detaileddescription'): if n in sub_dict: self.parse(sub_dict[n]) if self.with_constructor_list: self.make_constructor_list(constructor_nodes, classname) if self.with_attribute_list: self.make_attribute_list(node) sub_list = self.get_specific_subnodes(node, 'includes') if sub_list: self.parse(sub_list[0]) self.add_text(['";', '\n']) names = ['compoundname', 'briefdescription','detaileddescription', 'includes'] self.subnode_parse(node, ignore = names) elif kind in ('file', 'namespace'): nodes = node.getElementsByTagName('sectiondef') for n in nodes: self.parse(n) # now explicitely handle possibly overloaded member functions. if kind in ['class', 'struct','file', 'namespace']: md_nodes = self.get_memberdef_nodes_and_signatures(node, kind) for sig in md_nodes: self.handle_typical_memberdefs(sig, md_nodes[sig]) # MARK: Entry tag handlers (dont print anything meaningful) def do_sectiondef(self, node): kind = node.attributes['kind'].value if kind in ('public-func', 'func', 'user-defined', ''): self.subnode_parse(node) def do_header(self, node): """For a user defined section def a header field is present which should not be printed as such, so we comment it in the output.""" data = self.extract_text(node) self.add_text('\n/*\n %s \n*/\n' % data) # If our immediate sibling is a 'description' node then we # should comment that out also and remove it from the parent # node's children. parent = node.parentNode idx = parent.childNodes.index(node) if len(parent.childNodes) >= idx + 2: nd = parent.childNodes[idx + 2] if nd.nodeName == 'description': nd = parent.removeChild(nd) self.add_text('\n/*') self.subnode_parse(nd) self.add_text('\n*/\n') def do_member(self, node): kind = node.attributes['kind'].value refid = node.attributes['refid'].value if kind == 'function' and refid[:9] == 'namespace': self.subnode_parse(node) def do_doxygenindex(self, node): self.multi = 1 comps = node.getElementsByTagName('compound') for c in comps: refid = c.attributes['refid'].value fname = refid + '.xml' if not os.path.exists(fname): fname = os.path.join(self.my_dir, fname) if not self.quiet: print("parsing file: %s" % fname) p = Doxy2SWIG(fname, with_function_signature = self.with_function_signature, with_type_info = self.with_type_info, with_constructor_list = self.with_constructor_list, with_attribute_list = self.with_attribute_list, with_overloaded_functions = self.with_overloaded_functions, textwidth = self.textwidth, quiet = self.quiet) p.generate() self.pieces.extend(p.pieces)
basler/pypylon
scripts/builddoxy2swig/doxy2swig/doxy2swig.py
Doxy2SWIG.do_header
python
def do_header(self, node): data = self.extract_text(node) self.add_text('\n/*\n %s \n*/\n' % data) # If our immediate sibling is a 'description' node then we # should comment that out also and remove it from the parent # node's children. parent = node.parentNode idx = parent.childNodes.index(node) if len(parent.childNodes) >= idx + 2: nd = parent.childNodes[idx + 2] if nd.nodeName == 'description': nd = parent.removeChild(nd) self.add_text('\n/*') self.subnode_parse(nd) self.add_text('\n*/\n')
For a user defined section def a header field is present which should not be printed as such, so we comment it in the output.
train
https://github.com/basler/pypylon/blob/d3510fa419b1c2b17f3f0b80a5fbb720c7b84008/scripts/builddoxy2swig/doxy2swig/doxy2swig.py#L738-L755
[ "def subnode_parse(self, node, pieces=None, indent=0, ignore=[], restrict=None):\n \"\"\"Parse the subnodes of a given node. Subnodes with tags in the\n `ignore` list are ignored. If pieces is given, use this as target for\n the parse results instead of self.pieces. Indent all lines by the amount\n given in `indent`. Note that the initial content in `pieces` is not\n indented. The final result is in any case added to self.pieces.\"\"\"\n if pieces is not None:\n old_pieces, self.pieces = self.pieces, pieces\n else:\n old_pieces = []\n if type(indent) is int:\n indent = indent * ' '\n if len(indent) > 0:\n pieces = ''.join(self.pieces)\n i_piece = pieces[:len(indent)]\n if self.pieces[-1:] == ['']:\n self.pieces = [pieces[len(indent):]] + ['']\n elif self.pieces != []:\n self.pieces = [pieces[len(indent):]]\n self.indent += len(indent)\n for n in node.childNodes:\n if restrict is not None:\n if n.nodeType == n.ELEMENT_NODE and n.tagName in restrict:\n self.parse(n)\n elif n.nodeType != n.ELEMENT_NODE or n.tagName not in ignore:\n self.parse(n)\n if len(indent) > 0:\n self.pieces = shift(self.pieces, indent, i_piece)\n self.indent -= len(indent)\n old_pieces.extend(self.pieces)\n self.pieces = old_pieces\n", "def add_text(self, value):\n \"\"\"Adds text corresponding to `value` into `self.pieces`.\"\"\"\n if isinstance(value, (list, tuple)):\n self.pieces.extend(value)\n else:\n self.pieces.append(value)\n", "def extract_text(self, node):\n \"\"\"Return the string representation of the node or list of nodes by parsing the\n subnodes, but returning the result as a string instead of adding it to `self.pieces`.\n Note that this allows extracting text even if the node is in the ignore list.\n \"\"\"\n if not isinstance(node, (list, tuple)):\n node = [node]\n pieces, self.pieces = self.pieces, ['']\n for n in node:\n for sn in n.childNodes:\n self.parse(sn)\n ret = ''.join(self.pieces)\n self.pieces = pieces\n return ret\n" ]
class Doxy2SWIG: """Converts Doxygen generated XML files into a file containing docstrings that can be used by SWIG-1.3.x that have support for feature("docstring"). Once the data is parsed it is stored in self.pieces. """ def __init__(self, src, with_function_signature = False, with_type_info = False, with_constructor_list = False, with_attribute_list = False, with_overloaded_functions = False, textwidth = 80, quiet = False): """Initialize the instance given a source object. `src` can be a file or filename. If you do not want to include function definitions from doxygen then set `include_function_definition` to `False`. This is handy since this allows you to use the swig generated function definition using %feature("autodoc", [0,1]). """ # options: self.with_function_signature = with_function_signature self.with_type_info = with_type_info self.with_constructor_list = with_constructor_list self.with_attribute_list = with_attribute_list self.with_overloaded_functions = with_overloaded_functions self.textwidth = textwidth self.quiet = quiet # state: self.indent = 0 self.listitem = '' self.pieces = [] f = my_open_read(src) self.my_dir = os.path.dirname(f.name) self.xmldoc = minidom.parse(f).documentElement f.close() self.pieces.append('\n// File: %s\n' % os.path.basename(f.name)) self.space_re = re.compile(r'\s+') self.lead_spc = re.compile(r'^(%feature\S+\s+\S+\s*?)"\s+(\S)') self.multi = 0 self.ignores = ['inheritancegraph', 'param', 'listofallmembers', 'innerclass', 'name', 'declname', 'incdepgraph', 'invincdepgraph', 'programlisting', 'type', 'references', 'referencedby', 'location', 'collaborationgraph', 'reimplements', 'reimplementedby', 'derivedcompoundref', 'basecompoundref', 'argsstring', 'definition', 'exceptions'] #self.generics = [] def generate(self): """Parses the file set in the initialization. The resulting data is stored in `self.pieces`. """ self.parse(self.xmldoc) def write(self, fname): o = my_open_write(fname) o.write(''.join(self.pieces)) o.write('\n') o.close() def parse(self, node): """Parse a given node. This function in turn calls the `parse_<nodeType>` functions which handle the respective nodes. """ pm = getattr(self, "parse_%s" % node.__class__.__name__) pm(node) def parse_Document(self, node): self.parse(node.documentElement) def parse_Text(self, node): txt = node.data if txt == ' ': # this can happen when two tags follow in a text, e.g., # " ...</emph> <formaula>$..." etc. # here we want to keep the space. self.add_text(txt) return txt = txt.replace('\\', r'\\') txt = txt.replace('"', r'\"') # ignore pure whitespace m = self.space_re.match(txt) if m and len(m.group()) == len(txt): pass else: self.add_text(txt) def parse_Comment(self, node): """Parse a `COMMENT_NODE`. This does nothing for now.""" return def parse_Element(self, node): """Parse an `ELEMENT_NODE`. This calls specific `do_<tagName>` handers for different elements. If no handler is available the `subnode_parse` method is called. All tagNames specified in `self.ignores` are simply ignored. """ name = node.tagName ignores = self.ignores if name in ignores: return attr = "do_%s" % name if hasattr(self, attr): handlerMethod = getattr(self, attr) handlerMethod(node) else: self.subnode_parse(node) #if name not in self.generics: self.generics.append(name) # MARK: Special format parsing def subnode_parse(self, node, pieces=None, indent=0, ignore=[], restrict=None): """Parse the subnodes of a given node. Subnodes with tags in the `ignore` list are ignored. If pieces is given, use this as target for the parse results instead of self.pieces. Indent all lines by the amount given in `indent`. Note that the initial content in `pieces` is not indented. The final result is in any case added to self.pieces.""" if pieces is not None: old_pieces, self.pieces = self.pieces, pieces else: old_pieces = [] if type(indent) is int: indent = indent * ' ' if len(indent) > 0: pieces = ''.join(self.pieces) i_piece = pieces[:len(indent)] if self.pieces[-1:] == ['']: self.pieces = [pieces[len(indent):]] + [''] elif self.pieces != []: self.pieces = [pieces[len(indent):]] self.indent += len(indent) for n in node.childNodes: if restrict is not None: if n.nodeType == n.ELEMENT_NODE and n.tagName in restrict: self.parse(n) elif n.nodeType != n.ELEMENT_NODE or n.tagName not in ignore: self.parse(n) if len(indent) > 0: self.pieces = shift(self.pieces, indent, i_piece) self.indent -= len(indent) old_pieces.extend(self.pieces) self.pieces = old_pieces def surround_parse(self, node, pre_char, post_char): """Parse the subnodes of a given node. Subnodes with tags in the `ignore` list are ignored. Prepend `pre_char` and append `post_char` to the output in self.pieces.""" self.add_text(pre_char) self.subnode_parse(node) self.add_text(post_char) # MARK: Helper functions def get_specific_subnodes(self, node, name, recursive=0): """Given a node and a name, return a list of child `ELEMENT_NODEs`, that have a `tagName` matching the `name`. Search recursively for `recursive` levels. """ children = [x for x in node.childNodes if x.nodeType == x.ELEMENT_NODE] ret = [x for x in children if x.tagName == name] if recursive > 0: for x in children: ret.extend(self.get_specific_subnodes(x, name, recursive-1)) return ret def get_specific_nodes(self, node, names): """Given a node and a sequence of strings in `names`, return a dictionary containing the names as keys and child `ELEMENT_NODEs`, that have a `tagName` equal to the name. """ nodes = [(x.tagName, x) for x in node.childNodes if x.nodeType == x.ELEMENT_NODE and x.tagName in names] return dict(nodes) def add_text(self, value): """Adds text corresponding to `value` into `self.pieces`.""" if isinstance(value, (list, tuple)): self.pieces.extend(value) else: self.pieces.append(value) def start_new_paragraph(self): """Make sure to create an empty line. This is overridden, if the previous text ends with the special marker ''. In that case, nothing is done. """ if self.pieces[-1:] == ['']: # respect special marker return elif self.pieces == []: # first paragraph, add '\n', override with '' self.pieces = ['\n'] elif self.pieces[-1][-1:] != '\n': # previous line not ended self.pieces.extend([' \n' ,'\n']) else: #default self.pieces.append('\n') def add_line_with_subsequent_indent(self, line, indent=4): """Add line of text and wrap such that subsequent lines are indented by `indent` spaces. """ if isinstance(line, (list, tuple)): line = ''.join(line) line = line.strip() width = self.textwidth-self.indent-indent wrapped_lines = textwrap.wrap(line[indent:], width=width) for i in range(len(wrapped_lines)): if wrapped_lines[i] != '': wrapped_lines[i] = indent * ' ' + wrapped_lines[i] self.pieces.append(line[:indent] + '\n'.join(wrapped_lines)[indent:] + ' \n') def extract_text(self, node): """Return the string representation of the node or list of nodes by parsing the subnodes, but returning the result as a string instead of adding it to `self.pieces`. Note that this allows extracting text even if the node is in the ignore list. """ if not isinstance(node, (list, tuple)): node = [node] pieces, self.pieces = self.pieces, [''] for n in node: for sn in n.childNodes: self.parse(sn) ret = ''.join(self.pieces) self.pieces = pieces return ret def get_function_signature(self, node): """Returns the function signature string for memberdef nodes.""" name = self.extract_text(self.get_specific_subnodes(node, 'name')) if self.with_type_info: argsstring = self.extract_text(self.get_specific_subnodes(node, 'argsstring')) else: argsstring = [] param_id = 1 for n_param in self.get_specific_subnodes(node, 'param'): declname = self.extract_text(self.get_specific_subnodes(n_param, 'declname')) if not declname: declname = 'arg' + str(param_id) defval = self.extract_text(self.get_specific_subnodes(n_param, 'defval')) if defval: defval = '=' + defval argsstring.append(declname + defval) param_id = param_id + 1 argsstring = '(' + ', '.join(argsstring) + ')' type = self.extract_text(self.get_specific_subnodes(node, 'type')) function_definition = name + argsstring if type != '' and type != 'void': function_definition = function_definition + ' -> ' + type return '`' + function_definition + '` ' # MARK: Special parsing tasks (need to be called manually) def make_constructor_list(self, constructor_nodes, classname): """Produces the "Constructors" section and the constructor signatures (since swig does not do so for classes) for class docstrings.""" if constructor_nodes == []: return self.add_text(['\n', 'Constructors', '\n', '------------']) for n in constructor_nodes: self.add_text('\n') self.add_line_with_subsequent_indent('* ' + self.get_function_signature(n)) self.subnode_parse(n, pieces = [], indent=4, ignore=['definition', 'name']) def make_attribute_list(self, node): """Produces the "Attributes" section in class docstrings for public member variables (attributes). """ atr_nodes = [] for n in self.get_specific_subnodes(node, 'memberdef', recursive=2): if n.attributes['kind'].value == 'variable' and n.attributes['prot'].value == 'public': atr_nodes.append(n) if not atr_nodes: return self.add_text(['\n', 'Attributes', '\n', '----------']) for n in atr_nodes: name = self.extract_text(self.get_specific_subnodes(n, 'name')) self.add_text(['\n* ', '`', name, '`', ' : ']) self.add_text(['`', self.extract_text(self.get_specific_subnodes(n, 'type')), '`']) self.add_text(' \n') restrict = ['briefdescription', 'detaileddescription'] self.subnode_parse(n, pieces=[''], indent=4, restrict=restrict) def get_memberdef_nodes_and_signatures(self, node, kind): """Collects the memberdef nodes and corresponding signatures that correspond to public function entries that are at most depth 2 deeper than the current (compounddef) node. Returns a dictionary with function signatures (what swig expects after the %feature directive) as keys, and a list of corresponding memberdef nodes as values.""" sig_dict = {} sig_prefix = '' if kind in ('file', 'namespace'): ns_node = node.getElementsByTagName('innernamespace') if not ns_node and kind == 'namespace': ns_node = node.getElementsByTagName('compoundname') if ns_node: sig_prefix = self.extract_text(ns_node[0]) + '::' elif kind in ('class', 'struct'): # Get the full function name. cn_node = node.getElementsByTagName('compoundname') sig_prefix = self.extract_text(cn_node[0]) + '::' md_nodes = self.get_specific_subnodes(node, 'memberdef', recursive=2) for n in md_nodes: if n.attributes['prot'].value != 'public': continue if n.attributes['kind'].value in ['variable', 'typedef']: continue if not self.get_specific_subnodes(n, 'definition'): continue name = self.extract_text(self.get_specific_subnodes(n, 'name')) if name[:8] == 'operator': continue sig = sig_prefix + name if sig in sig_dict: sig_dict[sig].append(n) else: sig_dict[sig] = [n] return sig_dict def handle_typical_memberdefs_no_overload(self, signature, memberdef_nodes): """Produce standard documentation for memberdef_nodes.""" for n in memberdef_nodes: self.add_text(['\n', '%feature("docstring") ', signature, ' "', '\n']) if self.with_function_signature: self.add_line_with_subsequent_indent(self.get_function_signature(n)) self.subnode_parse(n, pieces=[], ignore=['definition', 'name']) self.add_text(['";', '\n']) def handle_typical_memberdefs(self, signature, memberdef_nodes): """Produces docstring entries containing an "Overloaded function" section with the documentation for each overload, if the function is overloaded and self.with_overloaded_functions is set. Else, produce normal documentation. """ if len(memberdef_nodes) == 1 or not self.with_overloaded_functions: self.handle_typical_memberdefs_no_overload(signature, memberdef_nodes) return self.add_text(['\n', '%feature("docstring") ', signature, ' "', '\n']) if self.with_function_signature: for n in memberdef_nodes: self.add_line_with_subsequent_indent(self.get_function_signature(n)) self.add_text('\n') self.add_text(['Overloaded function', '\n', '-------------------']) for n in memberdef_nodes: self.add_text('\n') self.add_line_with_subsequent_indent('* ' + self.get_function_signature(n)) self.subnode_parse(n, pieces=[], indent=4, ignore=['definition', 'name']) self.add_text(['";', '\n']) # MARK: Tag handlers def do_linebreak(self, node): self.add_text(' ') def do_ndash(self, node): self.add_text('--') def do_mdash(self, node): self.add_text('---') def do_emphasis(self, node): self.surround_parse(node, '*', '*') def do_bold(self, node): self.surround_parse(node, '**', '**') def do_computeroutput(self, node): self.surround_parse(node, '`', '`') def do_heading(self, node): self.start_new_paragraph() pieces, self.pieces = self.pieces, [''] level = int(node.attributes['level'].value) self.subnode_parse(node) if level == 1: self.pieces.insert(0, '\n') self.add_text(['\n', len(''.join(self.pieces).strip()) * '=']) elif level == 2: self.add_text(['\n', len(''.join(self.pieces).strip()) * '-']) elif level >= 3: self.pieces.insert(0, level * '#' + ' ') # make following text have no gap to the heading: pieces.extend([''.join(self.pieces) + ' \n', '']) self.pieces = pieces def do_verbatim(self, node): self.start_new_paragraph() self.subnode_parse(node, pieces=[''], indent=4) def do_blockquote(self, node): self.start_new_paragraph() self.subnode_parse(node, pieces=[''], indent='> ') def do_hruler(self, node): self.start_new_paragraph() self.add_text('* * * * * \n') def do_includes(self, node): self.add_text('\nC++ includes: ') self.subnode_parse(node) self.add_text('\n') # MARK: Para tag handler def do_para(self, node): """This is the only place where text wrapping is automatically performed. Generally, this function parses the node (locally), wraps the text, and then adds the result to self.pieces. However, it may be convenient to allow the previous content of self.pieces to be included in the text wrapping. For this, use the following *convention*: If self.pieces ends with '', treat the _previous_ entry as part of the current paragraph. Else, insert new-line and start a new paragraph and "wrapping context". Paragraphs always end with ' \n', but if the parsed content ends with the special symbol '', this is passed on. """ if self.pieces[-1:] == ['']: pieces, self.pieces = self.pieces[:-2], self.pieces[-2:-1] else: self.add_text('\n') pieces, self.pieces = self.pieces, [''] self.subnode_parse(node) dont_end_paragraph = self.pieces[-1:] == [''] # Now do the text wrapping: width = self.textwidth - self.indent wrapped_para = [] for line in ''.join(self.pieces).splitlines(): keep_markdown_newline = line[-2:] == ' ' w_line = textwrap.wrap(line, width=width, break_long_words=False) if w_line == []: w_line = [''] if keep_markdown_newline: w_line[-1] = w_line[-1] + ' ' for wl in w_line: wrapped_para.append(wl + '\n') if wrapped_para: if wrapped_para[-1][-3:] != ' \n': wrapped_para[-1] = wrapped_para[-1][:-1] + ' \n' if dont_end_paragraph: wrapped_para.append('') pieces.extend(wrapped_para) self.pieces = pieces # MARK: List tag handlers def do_itemizedlist(self, node): if self.listitem == '': self.start_new_paragraph() elif self.pieces != [] and self.pieces[-1:] != ['']: self.add_text('\n') listitem = self.listitem if self.listitem in ['*', '-']: self.listitem = '-' else: self.listitem = '*' self.subnode_parse(node) self.listitem = listitem def do_orderedlist(self, node): if self.listitem == '': self.start_new_paragraph() elif self.pieces != [] and self.pieces[-1:] != ['']: self.add_text('\n') listitem = self.listitem self.listitem = 0 self.subnode_parse(node) self.listitem = listitem def do_listitem(self, node): try: self.listitem = int(self.listitem) + 1 item = str(self.listitem) + '. ' except: item = str(self.listitem) + ' ' self.subnode_parse(node, item, indent=4) # MARK: Parameter list tag handlers def do_parameterlist(self, node): self.start_new_paragraph() text = 'unknown' for key, val in node.attributes.items(): if key == 'kind': if val == 'param': text = 'Parameters' elif val == 'exception': text = 'Exceptions' elif val == 'retval': text = 'Returns' else: text = val break if self.indent == 0: self.add_text([text, '\n', len(text) * '-', '\n']) else: self.add_text([text, ': \n']) self.subnode_parse(node) def do_parameteritem(self, node): self.subnode_parse(node, pieces=['* ', '']) def do_parameternamelist(self, node): self.subnode_parse(node) self.add_text([' :', ' \n']) def do_parametername(self, node): if self.pieces != [] and self.pieces != ['* ', '']: self.add_text(', ') data = self.extract_text(node) self.add_text(['`', data, '`']) def do_parameterdescription(self, node): self.subnode_parse(node, pieces=[''], indent=4) # MARK: Section tag handler def do_simplesect(self, node): kind = node.attributes['kind'].value if kind in ('date', 'rcs', 'version'): return self.start_new_paragraph() if kind == 'warning': self.subnode_parse(node, pieces=['**Warning**: ',''], indent=4) elif kind == 'see': self.subnode_parse(node, pieces=['See also: ',''], indent=4) elif kind == 'return': if self.indent == 0: pieces = ['Returns', '\n', len('Returns') * '-', '\n', ''] else: pieces = ['Returns:', '\n', ''] self.subnode_parse(node, pieces=pieces) else: self.subnode_parse(node, pieces=[kind + ': ',''], indent=4) # MARK: %feature("docstring") producing tag handlers def do_compounddef(self, node): """This produces %feature("docstring") entries for classes, and handles class, namespace and file memberdef entries specially to allow for overloaded functions. For other cases, passes parsing on to standard handlers (which may produce unexpected results). """ kind = node.attributes['kind'].value if kind in ('class', 'struct'): prot = node.attributes['prot'].value if prot != 'public': return self.add_text('\n\n') classdefn = self.extract_text(self.get_specific_subnodes(node, 'compoundname')) classname = classdefn.split('::')[-1] self.add_text('%%feature("docstring") %s "\n' % classdefn) if self.with_constructor_list: constructor_nodes = [] for n in self.get_specific_subnodes(node, 'memberdef', recursive=2): if n.attributes['prot'].value == 'public': if self.extract_text(self.get_specific_subnodes(n, 'definition')) == classdefn + '::' + classname: constructor_nodes.append(n) for n in constructor_nodes: self.add_line_with_subsequent_indent(self.get_function_signature(n)) names = ('briefdescription','detaileddescription') sub_dict = self.get_specific_nodes(node, names) for n in ('briefdescription','detaileddescription'): if n in sub_dict: self.parse(sub_dict[n]) if self.with_constructor_list: self.make_constructor_list(constructor_nodes, classname) if self.with_attribute_list: self.make_attribute_list(node) sub_list = self.get_specific_subnodes(node, 'includes') if sub_list: self.parse(sub_list[0]) self.add_text(['";', '\n']) names = ['compoundname', 'briefdescription','detaileddescription', 'includes'] self.subnode_parse(node, ignore = names) elif kind in ('file', 'namespace'): nodes = node.getElementsByTagName('sectiondef') for n in nodes: self.parse(n) # now explicitely handle possibly overloaded member functions. if kind in ['class', 'struct','file', 'namespace']: md_nodes = self.get_memberdef_nodes_and_signatures(node, kind) for sig in md_nodes: self.handle_typical_memberdefs(sig, md_nodes[sig]) def do_memberdef(self, node): """Handle cases outside of class, struct, file or namespace. These are now dealt with by `handle_overloaded_memberfunction`. Do these even exist??? """ prot = node.attributes['prot'].value id = node.attributes['id'].value kind = node.attributes['kind'].value tmp = node.parentNode.parentNode.parentNode compdef = tmp.getElementsByTagName('compounddef')[0] cdef_kind = compdef.attributes['kind'].value if cdef_kind in ('file', 'namespace', 'class', 'struct'): # These cases are now handled by `handle_typical_memberdefs` return if prot != 'public': return first = self.get_specific_nodes(node, ('definition', 'name')) name = self.extract_text(first['name']) if name[:8] == 'operator': # Don't handle operators yet. return if not 'definition' in first or kind in ['variable', 'typedef']: return data = self.extract_text(first['definition']) self.add_text('\n') self.add_text(['/* where did this entry come from??? */', '\n']) self.add_text('%feature("docstring") %s "\n%s' % (data, data)) for n in node.childNodes: if n not in first.values(): self.parse(n) self.add_text(['";', '\n']) # MARK: Entry tag handlers (dont print anything meaningful) def do_sectiondef(self, node): kind = node.attributes['kind'].value if kind in ('public-func', 'func', 'user-defined', ''): self.subnode_parse(node) def do_member(self, node): kind = node.attributes['kind'].value refid = node.attributes['refid'].value if kind == 'function' and refid[:9] == 'namespace': self.subnode_parse(node) def do_doxygenindex(self, node): self.multi = 1 comps = node.getElementsByTagName('compound') for c in comps: refid = c.attributes['refid'].value fname = refid + '.xml' if not os.path.exists(fname): fname = os.path.join(self.my_dir, fname) if not self.quiet: print("parsing file: %s" % fname) p = Doxy2SWIG(fname, with_function_signature = self.with_function_signature, with_type_info = self.with_type_info, with_constructor_list = self.with_constructor_list, with_attribute_list = self.with_attribute_list, with_overloaded_functions = self.with_overloaded_functions, textwidth = self.textwidth, quiet = self.quiet) p.generate() self.pieces.extend(p.pieces)
basler/pypylon
scripts/generatedoc/generatedoc.py
visiblename
python
def visiblename(name, all=None, obj=None): # Certain special names are redundant or internal. # XXX Remove __initializing__? if name in {'__author__', '__builtins__', '__cached__', '__credits__', '__date__', '__doc__', '__file__', '__spec__', '__loader__', '__module__', '__name__', '__package__', '__path__', '__qualname__', '__slots__', '__version__'}: return 0 if name.endswith("_swigregister"): return 0 if name.startswith("__swig"): return 0 # Private names are hidden, but special names are displayed. if name.startswith('__') and name.endswith('__'): return 1 # Namedtuples have public fields and methods with a single leading underscore if name.startswith('_') and hasattr(obj, '_fields'): return True if all is not None: # only document that which the programmer exported in __all__ return name in all else: return not name.startswith('_')
Decide whether to show documentation on a variable.
train
https://github.com/basler/pypylon/blob/d3510fa419b1c2b17f3f0b80a5fbb720c7b84008/scripts/generatedoc/generatedoc.py#L1-L43
null
""" This script generates a HTML doc from the pypylon installation """ if __name__ == '__main__': import pydoc pydoc.visiblename = visiblename from pypylon import pylon, genicam pydoc.writedoc(pylon) pydoc.writedoc(genicam)
miguelgrinberg/Flask-Migrate
flask_migrate/cli.py
revision
python
def revision(directory, message, autogenerate, sql, head, splice, branch_label, version_path, rev_id): _revision(directory, message, autogenerate, sql, head, splice, branch_label, version_path, rev_id)
Create a new revision file.
train
https://github.com/miguelgrinberg/Flask-Migrate/blob/65fbd978681bdf2eddf8940edd04ed7272a94480/flask_migrate/cli.py#L57-L61
null
import click from flask.cli import with_appcontext from flask_migrate import init as _init from flask_migrate import revision as _revision from flask_migrate import migrate as _migrate from flask_migrate import edit as _edit from flask_migrate import merge as _merge from flask_migrate import upgrade as _upgrade from flask_migrate import downgrade as _downgrade from flask_migrate import show as _show from flask_migrate import history as _history from flask_migrate import heads as _heads from flask_migrate import branches as _branches from flask_migrate import current as _current from flask_migrate import stamp as _stamp @click.group() def db(): """Perform database migrations.""" pass @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('--multidb', is_flag=True, help=('Support multiple databases')) @with_appcontext def init(directory, multidb): """Creates a new migration repository.""" _init(directory, multidb) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('-m', '--message', default=None, help='Revision message') @click.option('--autogenerate', is_flag=True, help=('Populate revision script with candidate migration ' 'operations, based on comparison of database to model')) @click.option('--sql', is_flag=True, help=('Don\'t emit SQL to database - dump to standard output ' 'instead')) @click.option('--head', default='head', help=('Specify head revision or <branchname>@head to base new ' 'revision on')) @click.option('--splice', is_flag=True, help=('Allow a non-head revision as the "head" to splice onto')) @click.option('--branch-label', default=None, help=('Specify a branch label to apply to the new revision')) @click.option('--version-path', default=None, help=('Specify specific path from config for version file')) @click.option('--rev-id', default=None, help=('Specify a hardcoded revision id instead of generating ' 'one')) @with_appcontext @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('-m', '--message', default=None, help='Revision message') @click.option('--sql', is_flag=True, help=('Don\'t emit SQL to database - dump to standard output ' 'instead')) @click.option('--head', default='head', help=('Specify head revision or <branchname>@head to base new ' 'revision on')) @click.option('--splice', is_flag=True, help=('Allow a non-head revision as the "head" to splice onto')) @click.option('--branch-label', default=None, help=('Specify a branch label to apply to the new revision')) @click.option('--version-path', default=None, help=('Specify specific path from config for version file')) @click.option('--rev-id', default=None, help=('Specify a hardcoded revision id instead of generating ' 'one')) @click.option('-x', '--x-arg', multiple=True, help='Additional arguments consumed by custom env.py scripts') @with_appcontext def migrate(directory, message, sql, head, splice, branch_label, version_path, rev_id, x_arg): """Autogenerate a new revision file (Alias for 'revision --autogenerate')""" _migrate(directory, message, sql, head, splice, branch_label, version_path, rev_id, x_arg) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.argument('revision', default='head') @with_appcontext def edit(directory, revision): """Edit a revision file""" _edit(directory, revision) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('-m', '--message', default=None, help='Merge revision message') @click.option('--branch-label', default=None, help=('Specify a branch label to apply to the new revision')) @click.option('--rev-id', default=None, help=('Specify a hardcoded revision id instead of generating ' 'one')) @click.argument('revisions', nargs=-1) @with_appcontext def merge(directory, message, branch_label, rev_id, revisions): """Merge two revisions together, creating a new revision file""" _merge(directory, revisions, message, branch_label, rev_id) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('--sql', is_flag=True, help=('Don\'t emit SQL to database - dump to standard output ' 'instead')) @click.option('--tag', default=None, help=('Arbitrary "tag" name - can be used by custom "env.py ' 'scripts')) @click.option('-x', '--x-arg', multiple=True, help='Additional arguments consumed by custom env.py scripts') @click.argument('revision', default='head') @with_appcontext def upgrade(directory, sql, tag, x_arg, revision): """Upgrade to a later version""" _upgrade(directory, revision, sql, tag, x_arg) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('--sql', is_flag=True, help=('Don\'t emit SQL to database - dump to standard output ' 'instead')) @click.option('--tag', default=None, help=('Arbitrary "tag" name - can be used by custom "env.py ' 'scripts')) @click.option('-x', '--x-arg', multiple=True, help='Additional arguments consumed by custom env.py scripts') @click.argument('revision', default='-1') @with_appcontext def downgrade(directory, sql, tag, x_arg, revision): """Revert to a previous version""" _downgrade(directory, revision, sql, tag, x_arg) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.argument('revision', default='head') @with_appcontext def show(directory, revision): """Show the revision denoted by the given symbol.""" _show(directory, revision) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('-r', '--rev-range', default=None, help='Specify a revision range; format is [start]:[end]') @click.option('-v', '--verbose', is_flag=True, help='Use more verbose output') @click.option('-i', '--indicate-current', is_flag=True, help='Indicate current version (Alembic 0.9.9 or greater is required)') @with_appcontext def history(directory, rev_range, verbose, indicate_current): """List changeset scripts in chronological order.""" _history(directory, rev_range, verbose, indicate_current) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('-v', '--verbose', is_flag=True, help='Use more verbose output') @click.option('--resolve-dependencies', is_flag=True, help='Treat dependency versions as down revisions') @with_appcontext def heads(directory, verbose, resolve_dependencies): """Show current available heads in the script directory""" _heads(directory, verbose, resolve_dependencies) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('-v', '--verbose', is_flag=True, help='Use more verbose output') @with_appcontext def branches(directory, verbose): """Show current branch points""" _branches(directory, verbose) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('-v', '--verbose', is_flag=True, help='Use more verbose output') @click.option('--head-only', is_flag=True, help='Deprecated. Use --verbose for additional output') @with_appcontext def current(directory, verbose, head_only): """Display the current revision for each database.""" _current(directory, verbose, head_only) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('--sql', is_flag=True, help=('Don\'t emit SQL to database - dump to standard output ' 'instead')) @click.option('--tag', default=None, help=('Arbitrary "tag" name - can be used by custom "env.py ' 'scripts')) @click.argument('revision', default='head') @with_appcontext def stamp(directory, sql, tag, revision): """'stamp' the revision table with the given revision; don't run any migrations""" _stamp(directory, revision, sql, tag)
miguelgrinberg/Flask-Migrate
flask_migrate/cli.py
migrate
python
def migrate(directory, message, sql, head, splice, branch_label, version_path, rev_id, x_arg): _migrate(directory, message, sql, head, splice, branch_label, version_path, rev_id, x_arg)
Autogenerate a new revision file (Alias for 'revision --autogenerate')
train
https://github.com/miguelgrinberg/Flask-Migrate/blob/65fbd978681bdf2eddf8940edd04ed7272a94480/flask_migrate/cli.py#L86-L90
null
import click from flask.cli import with_appcontext from flask_migrate import init as _init from flask_migrate import revision as _revision from flask_migrate import migrate as _migrate from flask_migrate import edit as _edit from flask_migrate import merge as _merge from flask_migrate import upgrade as _upgrade from flask_migrate import downgrade as _downgrade from flask_migrate import show as _show from flask_migrate import history as _history from flask_migrate import heads as _heads from flask_migrate import branches as _branches from flask_migrate import current as _current from flask_migrate import stamp as _stamp @click.group() def db(): """Perform database migrations.""" pass @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('--multidb', is_flag=True, help=('Support multiple databases')) @with_appcontext def init(directory, multidb): """Creates a new migration repository.""" _init(directory, multidb) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('-m', '--message', default=None, help='Revision message') @click.option('--autogenerate', is_flag=True, help=('Populate revision script with candidate migration ' 'operations, based on comparison of database to model')) @click.option('--sql', is_flag=True, help=('Don\'t emit SQL to database - dump to standard output ' 'instead')) @click.option('--head', default='head', help=('Specify head revision or <branchname>@head to base new ' 'revision on')) @click.option('--splice', is_flag=True, help=('Allow a non-head revision as the "head" to splice onto')) @click.option('--branch-label', default=None, help=('Specify a branch label to apply to the new revision')) @click.option('--version-path', default=None, help=('Specify specific path from config for version file')) @click.option('--rev-id', default=None, help=('Specify a hardcoded revision id instead of generating ' 'one')) @with_appcontext def revision(directory, message, autogenerate, sql, head, splice, branch_label, version_path, rev_id): """Create a new revision file.""" _revision(directory, message, autogenerate, sql, head, splice, branch_label, version_path, rev_id) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('-m', '--message', default=None, help='Revision message') @click.option('--sql', is_flag=True, help=('Don\'t emit SQL to database - dump to standard output ' 'instead')) @click.option('--head', default='head', help=('Specify head revision or <branchname>@head to base new ' 'revision on')) @click.option('--splice', is_flag=True, help=('Allow a non-head revision as the "head" to splice onto')) @click.option('--branch-label', default=None, help=('Specify a branch label to apply to the new revision')) @click.option('--version-path', default=None, help=('Specify specific path from config for version file')) @click.option('--rev-id', default=None, help=('Specify a hardcoded revision id instead of generating ' 'one')) @click.option('-x', '--x-arg', multiple=True, help='Additional arguments consumed by custom env.py scripts') @with_appcontext @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.argument('revision', default='head') @with_appcontext def edit(directory, revision): """Edit a revision file""" _edit(directory, revision) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('-m', '--message', default=None, help='Merge revision message') @click.option('--branch-label', default=None, help=('Specify a branch label to apply to the new revision')) @click.option('--rev-id', default=None, help=('Specify a hardcoded revision id instead of generating ' 'one')) @click.argument('revisions', nargs=-1) @with_appcontext def merge(directory, message, branch_label, rev_id, revisions): """Merge two revisions together, creating a new revision file""" _merge(directory, revisions, message, branch_label, rev_id) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('--sql', is_flag=True, help=('Don\'t emit SQL to database - dump to standard output ' 'instead')) @click.option('--tag', default=None, help=('Arbitrary "tag" name - can be used by custom "env.py ' 'scripts')) @click.option('-x', '--x-arg', multiple=True, help='Additional arguments consumed by custom env.py scripts') @click.argument('revision', default='head') @with_appcontext def upgrade(directory, sql, tag, x_arg, revision): """Upgrade to a later version""" _upgrade(directory, revision, sql, tag, x_arg) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('--sql', is_flag=True, help=('Don\'t emit SQL to database - dump to standard output ' 'instead')) @click.option('--tag', default=None, help=('Arbitrary "tag" name - can be used by custom "env.py ' 'scripts')) @click.option('-x', '--x-arg', multiple=True, help='Additional arguments consumed by custom env.py scripts') @click.argument('revision', default='-1') @with_appcontext def downgrade(directory, sql, tag, x_arg, revision): """Revert to a previous version""" _downgrade(directory, revision, sql, tag, x_arg) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.argument('revision', default='head') @with_appcontext def show(directory, revision): """Show the revision denoted by the given symbol.""" _show(directory, revision) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('-r', '--rev-range', default=None, help='Specify a revision range; format is [start]:[end]') @click.option('-v', '--verbose', is_flag=True, help='Use more verbose output') @click.option('-i', '--indicate-current', is_flag=True, help='Indicate current version (Alembic 0.9.9 or greater is required)') @with_appcontext def history(directory, rev_range, verbose, indicate_current): """List changeset scripts in chronological order.""" _history(directory, rev_range, verbose, indicate_current) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('-v', '--verbose', is_flag=True, help='Use more verbose output') @click.option('--resolve-dependencies', is_flag=True, help='Treat dependency versions as down revisions') @with_appcontext def heads(directory, verbose, resolve_dependencies): """Show current available heads in the script directory""" _heads(directory, verbose, resolve_dependencies) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('-v', '--verbose', is_flag=True, help='Use more verbose output') @with_appcontext def branches(directory, verbose): """Show current branch points""" _branches(directory, verbose) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('-v', '--verbose', is_flag=True, help='Use more verbose output') @click.option('--head-only', is_flag=True, help='Deprecated. Use --verbose for additional output') @with_appcontext def current(directory, verbose, head_only): """Display the current revision for each database.""" _current(directory, verbose, head_only) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('--sql', is_flag=True, help=('Don\'t emit SQL to database - dump to standard output ' 'instead')) @click.option('--tag', default=None, help=('Arbitrary "tag" name - can be used by custom "env.py ' 'scripts')) @click.argument('revision', default='head') @with_appcontext def stamp(directory, sql, tag, revision): """'stamp' the revision table with the given revision; don't run any migrations""" _stamp(directory, revision, sql, tag)
miguelgrinberg/Flask-Migrate
flask_migrate/cli.py
merge
python
def merge(directory, message, branch_label, rev_id, revisions): _merge(directory, revisions, message, branch_label, rev_id)
Merge two revisions together, creating a new revision file
train
https://github.com/miguelgrinberg/Flask-Migrate/blob/65fbd978681bdf2eddf8940edd04ed7272a94480/flask_migrate/cli.py#L114-L116
null
import click from flask.cli import with_appcontext from flask_migrate import init as _init from flask_migrate import revision as _revision from flask_migrate import migrate as _migrate from flask_migrate import edit as _edit from flask_migrate import merge as _merge from flask_migrate import upgrade as _upgrade from flask_migrate import downgrade as _downgrade from flask_migrate import show as _show from flask_migrate import history as _history from flask_migrate import heads as _heads from flask_migrate import branches as _branches from flask_migrate import current as _current from flask_migrate import stamp as _stamp @click.group() def db(): """Perform database migrations.""" pass @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('--multidb', is_flag=True, help=('Support multiple databases')) @with_appcontext def init(directory, multidb): """Creates a new migration repository.""" _init(directory, multidb) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('-m', '--message', default=None, help='Revision message') @click.option('--autogenerate', is_flag=True, help=('Populate revision script with candidate migration ' 'operations, based on comparison of database to model')) @click.option('--sql', is_flag=True, help=('Don\'t emit SQL to database - dump to standard output ' 'instead')) @click.option('--head', default='head', help=('Specify head revision or <branchname>@head to base new ' 'revision on')) @click.option('--splice', is_flag=True, help=('Allow a non-head revision as the "head" to splice onto')) @click.option('--branch-label', default=None, help=('Specify a branch label to apply to the new revision')) @click.option('--version-path', default=None, help=('Specify specific path from config for version file')) @click.option('--rev-id', default=None, help=('Specify a hardcoded revision id instead of generating ' 'one')) @with_appcontext def revision(directory, message, autogenerate, sql, head, splice, branch_label, version_path, rev_id): """Create a new revision file.""" _revision(directory, message, autogenerate, sql, head, splice, branch_label, version_path, rev_id) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('-m', '--message', default=None, help='Revision message') @click.option('--sql', is_flag=True, help=('Don\'t emit SQL to database - dump to standard output ' 'instead')) @click.option('--head', default='head', help=('Specify head revision or <branchname>@head to base new ' 'revision on')) @click.option('--splice', is_flag=True, help=('Allow a non-head revision as the "head" to splice onto')) @click.option('--branch-label', default=None, help=('Specify a branch label to apply to the new revision')) @click.option('--version-path', default=None, help=('Specify specific path from config for version file')) @click.option('--rev-id', default=None, help=('Specify a hardcoded revision id instead of generating ' 'one')) @click.option('-x', '--x-arg', multiple=True, help='Additional arguments consumed by custom env.py scripts') @with_appcontext def migrate(directory, message, sql, head, splice, branch_label, version_path, rev_id, x_arg): """Autogenerate a new revision file (Alias for 'revision --autogenerate')""" _migrate(directory, message, sql, head, splice, branch_label, version_path, rev_id, x_arg) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.argument('revision', default='head') @with_appcontext def edit(directory, revision): """Edit a revision file""" _edit(directory, revision) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('-m', '--message', default=None, help='Merge revision message') @click.option('--branch-label', default=None, help=('Specify a branch label to apply to the new revision')) @click.option('--rev-id', default=None, help=('Specify a hardcoded revision id instead of generating ' 'one')) @click.argument('revisions', nargs=-1) @with_appcontext @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('--sql', is_flag=True, help=('Don\'t emit SQL to database - dump to standard output ' 'instead')) @click.option('--tag', default=None, help=('Arbitrary "tag" name - can be used by custom "env.py ' 'scripts')) @click.option('-x', '--x-arg', multiple=True, help='Additional arguments consumed by custom env.py scripts') @click.argument('revision', default='head') @with_appcontext def upgrade(directory, sql, tag, x_arg, revision): """Upgrade to a later version""" _upgrade(directory, revision, sql, tag, x_arg) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('--sql', is_flag=True, help=('Don\'t emit SQL to database - dump to standard output ' 'instead')) @click.option('--tag', default=None, help=('Arbitrary "tag" name - can be used by custom "env.py ' 'scripts')) @click.option('-x', '--x-arg', multiple=True, help='Additional arguments consumed by custom env.py scripts') @click.argument('revision', default='-1') @with_appcontext def downgrade(directory, sql, tag, x_arg, revision): """Revert to a previous version""" _downgrade(directory, revision, sql, tag, x_arg) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.argument('revision', default='head') @with_appcontext def show(directory, revision): """Show the revision denoted by the given symbol.""" _show(directory, revision) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('-r', '--rev-range', default=None, help='Specify a revision range; format is [start]:[end]') @click.option('-v', '--verbose', is_flag=True, help='Use more verbose output') @click.option('-i', '--indicate-current', is_flag=True, help='Indicate current version (Alembic 0.9.9 or greater is required)') @with_appcontext def history(directory, rev_range, verbose, indicate_current): """List changeset scripts in chronological order.""" _history(directory, rev_range, verbose, indicate_current) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('-v', '--verbose', is_flag=True, help='Use more verbose output') @click.option('--resolve-dependencies', is_flag=True, help='Treat dependency versions as down revisions') @with_appcontext def heads(directory, verbose, resolve_dependencies): """Show current available heads in the script directory""" _heads(directory, verbose, resolve_dependencies) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('-v', '--verbose', is_flag=True, help='Use more verbose output') @with_appcontext def branches(directory, verbose): """Show current branch points""" _branches(directory, verbose) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('-v', '--verbose', is_flag=True, help='Use more verbose output') @click.option('--head-only', is_flag=True, help='Deprecated. Use --verbose for additional output') @with_appcontext def current(directory, verbose, head_only): """Display the current revision for each database.""" _current(directory, verbose, head_only) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('--sql', is_flag=True, help=('Don\'t emit SQL to database - dump to standard output ' 'instead')) @click.option('--tag', default=None, help=('Arbitrary "tag" name - can be used by custom "env.py ' 'scripts')) @click.argument('revision', default='head') @with_appcontext def stamp(directory, sql, tag, revision): """'stamp' the revision table with the given revision; don't run any migrations""" _stamp(directory, revision, sql, tag)
miguelgrinberg/Flask-Migrate
flask_migrate/cli.py
upgrade
python
def upgrade(directory, sql, tag, x_arg, revision): _upgrade(directory, revision, sql, tag, x_arg)
Upgrade to a later version
train
https://github.com/miguelgrinberg/Flask-Migrate/blob/65fbd978681bdf2eddf8940edd04ed7272a94480/flask_migrate/cli.py#L132-L134
null
import click from flask.cli import with_appcontext from flask_migrate import init as _init from flask_migrate import revision as _revision from flask_migrate import migrate as _migrate from flask_migrate import edit as _edit from flask_migrate import merge as _merge from flask_migrate import upgrade as _upgrade from flask_migrate import downgrade as _downgrade from flask_migrate import show as _show from flask_migrate import history as _history from flask_migrate import heads as _heads from flask_migrate import branches as _branches from flask_migrate import current as _current from flask_migrate import stamp as _stamp @click.group() def db(): """Perform database migrations.""" pass @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('--multidb', is_flag=True, help=('Support multiple databases')) @with_appcontext def init(directory, multidb): """Creates a new migration repository.""" _init(directory, multidb) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('-m', '--message', default=None, help='Revision message') @click.option('--autogenerate', is_flag=True, help=('Populate revision script with candidate migration ' 'operations, based on comparison of database to model')) @click.option('--sql', is_flag=True, help=('Don\'t emit SQL to database - dump to standard output ' 'instead')) @click.option('--head', default='head', help=('Specify head revision or <branchname>@head to base new ' 'revision on')) @click.option('--splice', is_flag=True, help=('Allow a non-head revision as the "head" to splice onto')) @click.option('--branch-label', default=None, help=('Specify a branch label to apply to the new revision')) @click.option('--version-path', default=None, help=('Specify specific path from config for version file')) @click.option('--rev-id', default=None, help=('Specify a hardcoded revision id instead of generating ' 'one')) @with_appcontext def revision(directory, message, autogenerate, sql, head, splice, branch_label, version_path, rev_id): """Create a new revision file.""" _revision(directory, message, autogenerate, sql, head, splice, branch_label, version_path, rev_id) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('-m', '--message', default=None, help='Revision message') @click.option('--sql', is_flag=True, help=('Don\'t emit SQL to database - dump to standard output ' 'instead')) @click.option('--head', default='head', help=('Specify head revision or <branchname>@head to base new ' 'revision on')) @click.option('--splice', is_flag=True, help=('Allow a non-head revision as the "head" to splice onto')) @click.option('--branch-label', default=None, help=('Specify a branch label to apply to the new revision')) @click.option('--version-path', default=None, help=('Specify specific path from config for version file')) @click.option('--rev-id', default=None, help=('Specify a hardcoded revision id instead of generating ' 'one')) @click.option('-x', '--x-arg', multiple=True, help='Additional arguments consumed by custom env.py scripts') @with_appcontext def migrate(directory, message, sql, head, splice, branch_label, version_path, rev_id, x_arg): """Autogenerate a new revision file (Alias for 'revision --autogenerate')""" _migrate(directory, message, sql, head, splice, branch_label, version_path, rev_id, x_arg) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.argument('revision', default='head') @with_appcontext def edit(directory, revision): """Edit a revision file""" _edit(directory, revision) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('-m', '--message', default=None, help='Merge revision message') @click.option('--branch-label', default=None, help=('Specify a branch label to apply to the new revision')) @click.option('--rev-id', default=None, help=('Specify a hardcoded revision id instead of generating ' 'one')) @click.argument('revisions', nargs=-1) @with_appcontext def merge(directory, message, branch_label, rev_id, revisions): """Merge two revisions together, creating a new revision file""" _merge(directory, revisions, message, branch_label, rev_id) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('--sql', is_flag=True, help=('Don\'t emit SQL to database - dump to standard output ' 'instead')) @click.option('--tag', default=None, help=('Arbitrary "tag" name - can be used by custom "env.py ' 'scripts')) @click.option('-x', '--x-arg', multiple=True, help='Additional arguments consumed by custom env.py scripts') @click.argument('revision', default='head') @with_appcontext @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('--sql', is_flag=True, help=('Don\'t emit SQL to database - dump to standard output ' 'instead')) @click.option('--tag', default=None, help=('Arbitrary "tag" name - can be used by custom "env.py ' 'scripts')) @click.option('-x', '--x-arg', multiple=True, help='Additional arguments consumed by custom env.py scripts') @click.argument('revision', default='-1') @with_appcontext def downgrade(directory, sql, tag, x_arg, revision): """Revert to a previous version""" _downgrade(directory, revision, sql, tag, x_arg) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.argument('revision', default='head') @with_appcontext def show(directory, revision): """Show the revision denoted by the given symbol.""" _show(directory, revision) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('-r', '--rev-range', default=None, help='Specify a revision range; format is [start]:[end]') @click.option('-v', '--verbose', is_flag=True, help='Use more verbose output') @click.option('-i', '--indicate-current', is_flag=True, help='Indicate current version (Alembic 0.9.9 or greater is required)') @with_appcontext def history(directory, rev_range, verbose, indicate_current): """List changeset scripts in chronological order.""" _history(directory, rev_range, verbose, indicate_current) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('-v', '--verbose', is_flag=True, help='Use more verbose output') @click.option('--resolve-dependencies', is_flag=True, help='Treat dependency versions as down revisions') @with_appcontext def heads(directory, verbose, resolve_dependencies): """Show current available heads in the script directory""" _heads(directory, verbose, resolve_dependencies) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('-v', '--verbose', is_flag=True, help='Use more verbose output') @with_appcontext def branches(directory, verbose): """Show current branch points""" _branches(directory, verbose) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('-v', '--verbose', is_flag=True, help='Use more verbose output') @click.option('--head-only', is_flag=True, help='Deprecated. Use --verbose for additional output') @with_appcontext def current(directory, verbose, head_only): """Display the current revision for each database.""" _current(directory, verbose, head_only) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('--sql', is_flag=True, help=('Don\'t emit SQL to database - dump to standard output ' 'instead')) @click.option('--tag', default=None, help=('Arbitrary "tag" name - can be used by custom "env.py ' 'scripts')) @click.argument('revision', default='head') @with_appcontext def stamp(directory, sql, tag, revision): """'stamp' the revision table with the given revision; don't run any migrations""" _stamp(directory, revision, sql, tag)
miguelgrinberg/Flask-Migrate
flask_migrate/cli.py
downgrade
python
def downgrade(directory, sql, tag, x_arg, revision): _downgrade(directory, revision, sql, tag, x_arg)
Revert to a previous version
train
https://github.com/miguelgrinberg/Flask-Migrate/blob/65fbd978681bdf2eddf8940edd04ed7272a94480/flask_migrate/cli.py#L150-L152
null
import click from flask.cli import with_appcontext from flask_migrate import init as _init from flask_migrate import revision as _revision from flask_migrate import migrate as _migrate from flask_migrate import edit as _edit from flask_migrate import merge as _merge from flask_migrate import upgrade as _upgrade from flask_migrate import downgrade as _downgrade from flask_migrate import show as _show from flask_migrate import history as _history from flask_migrate import heads as _heads from flask_migrate import branches as _branches from flask_migrate import current as _current from flask_migrate import stamp as _stamp @click.group() def db(): """Perform database migrations.""" pass @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('--multidb', is_flag=True, help=('Support multiple databases')) @with_appcontext def init(directory, multidb): """Creates a new migration repository.""" _init(directory, multidb) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('-m', '--message', default=None, help='Revision message') @click.option('--autogenerate', is_flag=True, help=('Populate revision script with candidate migration ' 'operations, based on comparison of database to model')) @click.option('--sql', is_flag=True, help=('Don\'t emit SQL to database - dump to standard output ' 'instead')) @click.option('--head', default='head', help=('Specify head revision or <branchname>@head to base new ' 'revision on')) @click.option('--splice', is_flag=True, help=('Allow a non-head revision as the "head" to splice onto')) @click.option('--branch-label', default=None, help=('Specify a branch label to apply to the new revision')) @click.option('--version-path', default=None, help=('Specify specific path from config for version file')) @click.option('--rev-id', default=None, help=('Specify a hardcoded revision id instead of generating ' 'one')) @with_appcontext def revision(directory, message, autogenerate, sql, head, splice, branch_label, version_path, rev_id): """Create a new revision file.""" _revision(directory, message, autogenerate, sql, head, splice, branch_label, version_path, rev_id) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('-m', '--message', default=None, help='Revision message') @click.option('--sql', is_flag=True, help=('Don\'t emit SQL to database - dump to standard output ' 'instead')) @click.option('--head', default='head', help=('Specify head revision or <branchname>@head to base new ' 'revision on')) @click.option('--splice', is_flag=True, help=('Allow a non-head revision as the "head" to splice onto')) @click.option('--branch-label', default=None, help=('Specify a branch label to apply to the new revision')) @click.option('--version-path', default=None, help=('Specify specific path from config for version file')) @click.option('--rev-id', default=None, help=('Specify a hardcoded revision id instead of generating ' 'one')) @click.option('-x', '--x-arg', multiple=True, help='Additional arguments consumed by custom env.py scripts') @with_appcontext def migrate(directory, message, sql, head, splice, branch_label, version_path, rev_id, x_arg): """Autogenerate a new revision file (Alias for 'revision --autogenerate')""" _migrate(directory, message, sql, head, splice, branch_label, version_path, rev_id, x_arg) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.argument('revision', default='head') @with_appcontext def edit(directory, revision): """Edit a revision file""" _edit(directory, revision) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('-m', '--message', default=None, help='Merge revision message') @click.option('--branch-label', default=None, help=('Specify a branch label to apply to the new revision')) @click.option('--rev-id', default=None, help=('Specify a hardcoded revision id instead of generating ' 'one')) @click.argument('revisions', nargs=-1) @with_appcontext def merge(directory, message, branch_label, rev_id, revisions): """Merge two revisions together, creating a new revision file""" _merge(directory, revisions, message, branch_label, rev_id) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('--sql', is_flag=True, help=('Don\'t emit SQL to database - dump to standard output ' 'instead')) @click.option('--tag', default=None, help=('Arbitrary "tag" name - can be used by custom "env.py ' 'scripts')) @click.option('-x', '--x-arg', multiple=True, help='Additional arguments consumed by custom env.py scripts') @click.argument('revision', default='head') @with_appcontext def upgrade(directory, sql, tag, x_arg, revision): """Upgrade to a later version""" _upgrade(directory, revision, sql, tag, x_arg) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('--sql', is_flag=True, help=('Don\'t emit SQL to database - dump to standard output ' 'instead')) @click.option('--tag', default=None, help=('Arbitrary "tag" name - can be used by custom "env.py ' 'scripts')) @click.option('-x', '--x-arg', multiple=True, help='Additional arguments consumed by custom env.py scripts') @click.argument('revision', default='-1') @with_appcontext @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.argument('revision', default='head') @with_appcontext def show(directory, revision): """Show the revision denoted by the given symbol.""" _show(directory, revision) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('-r', '--rev-range', default=None, help='Specify a revision range; format is [start]:[end]') @click.option('-v', '--verbose', is_flag=True, help='Use more verbose output') @click.option('-i', '--indicate-current', is_flag=True, help='Indicate current version (Alembic 0.9.9 or greater is required)') @with_appcontext def history(directory, rev_range, verbose, indicate_current): """List changeset scripts in chronological order.""" _history(directory, rev_range, verbose, indicate_current) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('-v', '--verbose', is_flag=True, help='Use more verbose output') @click.option('--resolve-dependencies', is_flag=True, help='Treat dependency versions as down revisions') @with_appcontext def heads(directory, verbose, resolve_dependencies): """Show current available heads in the script directory""" _heads(directory, verbose, resolve_dependencies) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('-v', '--verbose', is_flag=True, help='Use more verbose output') @with_appcontext def branches(directory, verbose): """Show current branch points""" _branches(directory, verbose) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('-v', '--verbose', is_flag=True, help='Use more verbose output') @click.option('--head-only', is_flag=True, help='Deprecated. Use --verbose for additional output') @with_appcontext def current(directory, verbose, head_only): """Display the current revision for each database.""" _current(directory, verbose, head_only) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('--sql', is_flag=True, help=('Don\'t emit SQL to database - dump to standard output ' 'instead')) @click.option('--tag', default=None, help=('Arbitrary "tag" name - can be used by custom "env.py ' 'scripts')) @click.argument('revision', default='head') @with_appcontext def stamp(directory, sql, tag, revision): """'stamp' the revision table with the given revision; don't run any migrations""" _stamp(directory, revision, sql, tag)
miguelgrinberg/Flask-Migrate
flask_migrate/cli.py
history
python
def history(directory, rev_range, verbose, indicate_current): _history(directory, rev_range, verbose, indicate_current)
List changeset scripts in chronological order.
train
https://github.com/miguelgrinberg/Flask-Migrate/blob/65fbd978681bdf2eddf8940edd04ed7272a94480/flask_migrate/cli.py#L173-L175
null
import click from flask.cli import with_appcontext from flask_migrate import init as _init from flask_migrate import revision as _revision from flask_migrate import migrate as _migrate from flask_migrate import edit as _edit from flask_migrate import merge as _merge from flask_migrate import upgrade as _upgrade from flask_migrate import downgrade as _downgrade from flask_migrate import show as _show from flask_migrate import history as _history from flask_migrate import heads as _heads from flask_migrate import branches as _branches from flask_migrate import current as _current from flask_migrate import stamp as _stamp @click.group() def db(): """Perform database migrations.""" pass @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('--multidb', is_flag=True, help=('Support multiple databases')) @with_appcontext def init(directory, multidb): """Creates a new migration repository.""" _init(directory, multidb) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('-m', '--message', default=None, help='Revision message') @click.option('--autogenerate', is_flag=True, help=('Populate revision script with candidate migration ' 'operations, based on comparison of database to model')) @click.option('--sql', is_flag=True, help=('Don\'t emit SQL to database - dump to standard output ' 'instead')) @click.option('--head', default='head', help=('Specify head revision or <branchname>@head to base new ' 'revision on')) @click.option('--splice', is_flag=True, help=('Allow a non-head revision as the "head" to splice onto')) @click.option('--branch-label', default=None, help=('Specify a branch label to apply to the new revision')) @click.option('--version-path', default=None, help=('Specify specific path from config for version file')) @click.option('--rev-id', default=None, help=('Specify a hardcoded revision id instead of generating ' 'one')) @with_appcontext def revision(directory, message, autogenerate, sql, head, splice, branch_label, version_path, rev_id): """Create a new revision file.""" _revision(directory, message, autogenerate, sql, head, splice, branch_label, version_path, rev_id) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('-m', '--message', default=None, help='Revision message') @click.option('--sql', is_flag=True, help=('Don\'t emit SQL to database - dump to standard output ' 'instead')) @click.option('--head', default='head', help=('Specify head revision or <branchname>@head to base new ' 'revision on')) @click.option('--splice', is_flag=True, help=('Allow a non-head revision as the "head" to splice onto')) @click.option('--branch-label', default=None, help=('Specify a branch label to apply to the new revision')) @click.option('--version-path', default=None, help=('Specify specific path from config for version file')) @click.option('--rev-id', default=None, help=('Specify a hardcoded revision id instead of generating ' 'one')) @click.option('-x', '--x-arg', multiple=True, help='Additional arguments consumed by custom env.py scripts') @with_appcontext def migrate(directory, message, sql, head, splice, branch_label, version_path, rev_id, x_arg): """Autogenerate a new revision file (Alias for 'revision --autogenerate')""" _migrate(directory, message, sql, head, splice, branch_label, version_path, rev_id, x_arg) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.argument('revision', default='head') @with_appcontext def edit(directory, revision): """Edit a revision file""" _edit(directory, revision) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('-m', '--message', default=None, help='Merge revision message') @click.option('--branch-label', default=None, help=('Specify a branch label to apply to the new revision')) @click.option('--rev-id', default=None, help=('Specify a hardcoded revision id instead of generating ' 'one')) @click.argument('revisions', nargs=-1) @with_appcontext def merge(directory, message, branch_label, rev_id, revisions): """Merge two revisions together, creating a new revision file""" _merge(directory, revisions, message, branch_label, rev_id) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('--sql', is_flag=True, help=('Don\'t emit SQL to database - dump to standard output ' 'instead')) @click.option('--tag', default=None, help=('Arbitrary "tag" name - can be used by custom "env.py ' 'scripts')) @click.option('-x', '--x-arg', multiple=True, help='Additional arguments consumed by custom env.py scripts') @click.argument('revision', default='head') @with_appcontext def upgrade(directory, sql, tag, x_arg, revision): """Upgrade to a later version""" _upgrade(directory, revision, sql, tag, x_arg) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('--sql', is_flag=True, help=('Don\'t emit SQL to database - dump to standard output ' 'instead')) @click.option('--tag', default=None, help=('Arbitrary "tag" name - can be used by custom "env.py ' 'scripts')) @click.option('-x', '--x-arg', multiple=True, help='Additional arguments consumed by custom env.py scripts') @click.argument('revision', default='-1') @with_appcontext def downgrade(directory, sql, tag, x_arg, revision): """Revert to a previous version""" _downgrade(directory, revision, sql, tag, x_arg) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.argument('revision', default='head') @with_appcontext def show(directory, revision): """Show the revision denoted by the given symbol.""" _show(directory, revision) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('-r', '--rev-range', default=None, help='Specify a revision range; format is [start]:[end]') @click.option('-v', '--verbose', is_flag=True, help='Use more verbose output') @click.option('-i', '--indicate-current', is_flag=True, help='Indicate current version (Alembic 0.9.9 or greater is required)') @with_appcontext @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('-v', '--verbose', is_flag=True, help='Use more verbose output') @click.option('--resolve-dependencies', is_flag=True, help='Treat dependency versions as down revisions') @with_appcontext def heads(directory, verbose, resolve_dependencies): """Show current available heads in the script directory""" _heads(directory, verbose, resolve_dependencies) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('-v', '--verbose', is_flag=True, help='Use more verbose output') @with_appcontext def branches(directory, verbose): """Show current branch points""" _branches(directory, verbose) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('-v', '--verbose', is_flag=True, help='Use more verbose output') @click.option('--head-only', is_flag=True, help='Deprecated. Use --verbose for additional output') @with_appcontext def current(directory, verbose, head_only): """Display the current revision for each database.""" _current(directory, verbose, head_only) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('--sql', is_flag=True, help=('Don\'t emit SQL to database - dump to standard output ' 'instead')) @click.option('--tag', default=None, help=('Arbitrary "tag" name - can be used by custom "env.py ' 'scripts')) @click.argument('revision', default='head') @with_appcontext def stamp(directory, sql, tag, revision): """'stamp' the revision table with the given revision; don't run any migrations""" _stamp(directory, revision, sql, tag)
miguelgrinberg/Flask-Migrate
flask_migrate/cli.py
stamp
python
def stamp(directory, sql, tag, revision): """'stamp' the revision table with the given revision; don't run any migrations""" _stamp(directory, revision, sql, tag)
stamp' the revision table with the given revision; don't run any migrations
train
https://github.com/miguelgrinberg/Flask-Migrate/blob/65fbd978681bdf2eddf8940edd04ed7272a94480/flask_migrate/cli.py#L223-L226
null
import click from flask.cli import with_appcontext from flask_migrate import init as _init from flask_migrate import revision as _revision from flask_migrate import migrate as _migrate from flask_migrate import edit as _edit from flask_migrate import merge as _merge from flask_migrate import upgrade as _upgrade from flask_migrate import downgrade as _downgrade from flask_migrate import show as _show from flask_migrate import history as _history from flask_migrate import heads as _heads from flask_migrate import branches as _branches from flask_migrate import current as _current from flask_migrate import stamp as _stamp @click.group() def db(): """Perform database migrations.""" pass @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('--multidb', is_flag=True, help=('Support multiple databases')) @with_appcontext def init(directory, multidb): """Creates a new migration repository.""" _init(directory, multidb) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('-m', '--message', default=None, help='Revision message') @click.option('--autogenerate', is_flag=True, help=('Populate revision script with candidate migration ' 'operations, based on comparison of database to model')) @click.option('--sql', is_flag=True, help=('Don\'t emit SQL to database - dump to standard output ' 'instead')) @click.option('--head', default='head', help=('Specify head revision or <branchname>@head to base new ' 'revision on')) @click.option('--splice', is_flag=True, help=('Allow a non-head revision as the "head" to splice onto')) @click.option('--branch-label', default=None, help=('Specify a branch label to apply to the new revision')) @click.option('--version-path', default=None, help=('Specify specific path from config for version file')) @click.option('--rev-id', default=None, help=('Specify a hardcoded revision id instead of generating ' 'one')) @with_appcontext def revision(directory, message, autogenerate, sql, head, splice, branch_label, version_path, rev_id): """Create a new revision file.""" _revision(directory, message, autogenerate, sql, head, splice, branch_label, version_path, rev_id) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('-m', '--message', default=None, help='Revision message') @click.option('--sql', is_flag=True, help=('Don\'t emit SQL to database - dump to standard output ' 'instead')) @click.option('--head', default='head', help=('Specify head revision or <branchname>@head to base new ' 'revision on')) @click.option('--splice', is_flag=True, help=('Allow a non-head revision as the "head" to splice onto')) @click.option('--branch-label', default=None, help=('Specify a branch label to apply to the new revision')) @click.option('--version-path', default=None, help=('Specify specific path from config for version file')) @click.option('--rev-id', default=None, help=('Specify a hardcoded revision id instead of generating ' 'one')) @click.option('-x', '--x-arg', multiple=True, help='Additional arguments consumed by custom env.py scripts') @with_appcontext def migrate(directory, message, sql, head, splice, branch_label, version_path, rev_id, x_arg): """Autogenerate a new revision file (Alias for 'revision --autogenerate')""" _migrate(directory, message, sql, head, splice, branch_label, version_path, rev_id, x_arg) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.argument('revision', default='head') @with_appcontext def edit(directory, revision): """Edit a revision file""" _edit(directory, revision) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('-m', '--message', default=None, help='Merge revision message') @click.option('--branch-label', default=None, help=('Specify a branch label to apply to the new revision')) @click.option('--rev-id', default=None, help=('Specify a hardcoded revision id instead of generating ' 'one')) @click.argument('revisions', nargs=-1) @with_appcontext def merge(directory, message, branch_label, rev_id, revisions): """Merge two revisions together, creating a new revision file""" _merge(directory, revisions, message, branch_label, rev_id) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('--sql', is_flag=True, help=('Don\'t emit SQL to database - dump to standard output ' 'instead')) @click.option('--tag', default=None, help=('Arbitrary "tag" name - can be used by custom "env.py ' 'scripts')) @click.option('-x', '--x-arg', multiple=True, help='Additional arguments consumed by custom env.py scripts') @click.argument('revision', default='head') @with_appcontext def upgrade(directory, sql, tag, x_arg, revision): """Upgrade to a later version""" _upgrade(directory, revision, sql, tag, x_arg) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('--sql', is_flag=True, help=('Don\'t emit SQL to database - dump to standard output ' 'instead')) @click.option('--tag', default=None, help=('Arbitrary "tag" name - can be used by custom "env.py ' 'scripts')) @click.option('-x', '--x-arg', multiple=True, help='Additional arguments consumed by custom env.py scripts') @click.argument('revision', default='-1') @with_appcontext def downgrade(directory, sql, tag, x_arg, revision): """Revert to a previous version""" _downgrade(directory, revision, sql, tag, x_arg) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.argument('revision', default='head') @with_appcontext def show(directory, revision): """Show the revision denoted by the given symbol.""" _show(directory, revision) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('-r', '--rev-range', default=None, help='Specify a revision range; format is [start]:[end]') @click.option('-v', '--verbose', is_flag=True, help='Use more verbose output') @click.option('-i', '--indicate-current', is_flag=True, help='Indicate current version (Alembic 0.9.9 or greater is required)') @with_appcontext def history(directory, rev_range, verbose, indicate_current): """List changeset scripts in chronological order.""" _history(directory, rev_range, verbose, indicate_current) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('-v', '--verbose', is_flag=True, help='Use more verbose output') @click.option('--resolve-dependencies', is_flag=True, help='Treat dependency versions as down revisions') @with_appcontext def heads(directory, verbose, resolve_dependencies): """Show current available heads in the script directory""" _heads(directory, verbose, resolve_dependencies) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('-v', '--verbose', is_flag=True, help='Use more verbose output') @with_appcontext def branches(directory, verbose): """Show current branch points""" _branches(directory, verbose) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('-v', '--verbose', is_flag=True, help='Use more verbose output') @click.option('--head-only', is_flag=True, help='Deprecated. Use --verbose for additional output') @with_appcontext def current(directory, verbose, head_only): """Display the current revision for each database.""" _current(directory, verbose, head_only) @db.command() @click.option('-d', '--directory', default=None, help=('migration script directory (default is "migrations")')) @click.option('--sql', is_flag=True, help=('Don\'t emit SQL to database - dump to standard output ' 'instead')) @click.option('--tag', default=None, help=('Arbitrary "tag" name - can be used by custom "env.py ' 'scripts')) @click.argument('revision', default='head') @with_appcontext
miguelgrinberg/Flask-Migrate
flask_migrate/templates/flask/env.py
run_migrations_offline
python
def run_migrations_offline(): url = config.get_main_option("sqlalchemy.url") context.configure( url=url, target_metadata=target_metadata, literal_binds=True ) with context.begin_transaction(): context.run_migrations()
Run migrations in 'offline' mode. This configures the context with just a URL and not an Engine, though an Engine is acceptable here as well. By skipping the Engine creation we don't even need a DBAPI to be available. Calls to context.execute() here emit the given string to the script output.
train
https://github.com/miguelgrinberg/Flask-Migrate/blob/65fbd978681bdf2eddf8940edd04ed7272a94480/flask_migrate/templates/flask/env.py#L35-L53
null
from __future__ import with_statement import logging from logging.config import fileConfig from sqlalchemy import engine_from_config from sqlalchemy import pool from alembic import context # this is the Alembic Config object, which provides # access to the values within the .ini file in use. config = context.config # Interpret the config file for Python logging. # This line sets up loggers basically. fileConfig(config.config_file_name) logger = logging.getLogger('alembic.env') # add your model's MetaData object here # for 'autogenerate' support # from myapp import mymodel # target_metadata = mymodel.Base.metadata from flask import current_app config.set_main_option('sqlalchemy.url', current_app.config.get('SQLALCHEMY_DATABASE_URI')) target_metadata = current_app.extensions['migrate'].db.metadata # other values from the config, defined by the needs of env.py, # can be acquired: # my_important_option = config.get_main_option("my_important_option") # ... etc. def run_migrations_online(): """Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context. """ # this callback is used to prevent an auto-migration from being generated # when there are no changes to the schema # reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html def process_revision_directives(context, revision, directives): if getattr(config.cmd_opts, 'autogenerate', False): script = directives[0] if script.upgrade_ops.is_empty(): directives[:] = [] logger.info('No changes in schema detected.') connectable = engine_from_config( config.get_section(config.config_ini_section), prefix='sqlalchemy.', poolclass=pool.NullPool, ) with connectable.connect() as connection: context.configure( connection=connection, target_metadata=target_metadata, process_revision_directives=process_revision_directives, **current_app.extensions['migrate'].configure_args ) with context.begin_transaction(): context.run_migrations() if context.is_offline_mode(): run_migrations_offline() else: run_migrations_online()
miguelgrinberg/Flask-Migrate
flask_migrate/templates/flask-multidb/env.py
get_metadata
python
def get_metadata(bind): if bind == '': bind = None m = MetaData() for t in target_metadata.tables.values(): if t.info.get('bind_key') == bind: t.tometadata(m) return m
Return the metadata for a bind.
train
https://github.com/miguelgrinberg/Flask-Migrate/blob/65fbd978681bdf2eddf8940edd04ed7272a94480/flask_migrate/templates/flask-multidb/env.py#L44-L52
null
from __future__ import with_statement import logging from logging.config import fileConfig import re from sqlalchemy import engine_from_config from sqlalchemy import MetaData from sqlalchemy import pool from flask import current_app from alembic import context USE_TWOPHASE = False # this is the Alembic Config object, which provides # access to the values within the .ini file in use. config = context.config # Interpret the config file for Python logging. # This line sets up loggers basically. fileConfig(config.config_file_name) logger = logging.getLogger('alembic.env') # add your model's MetaData object here # for 'autogenerate' support # from myapp import mymodel # target_metadata = mymodel.Base.metadata config.set_main_option('sqlalchemy.url', current_app.config.get('SQLALCHEMY_DATABASE_URI')) bind_names = [] for name, url in current_app.config.get("SQLALCHEMY_BINDS").items(): context.config.set_section_option(name, "sqlalchemy.url", url) bind_names.append(name) target_metadata = current_app.extensions['migrate'].db.metadata # other values from the config, defined by the needs of env.py, # can be acquired: # my_important_option = config.get_main_option("my_important_option") # ... etc. def run_migrations_offline(): """Run migrations in 'offline' mode. This configures the context with just a URL and not an Engine, though an Engine is acceptable here as well. By skipping the Engine creation we don't even need a DBAPI to be available. Calls to context.execute() here emit the given string to the script output. """ # for the --sql use case, run migrations for each URL into # individual files. engines = { '': { 'url': context.config.get_main_option('sqlalchemy.url') } } for name in bind_names: engines[name] = rec = {} rec['url'] = context.config.get_section_option(name, "sqlalchemy.url") for name, rec in engines.items(): logger.info("Migrating database %s" % (name or '<default>')) file_ = "%s.sql" % name logger.info("Writing output to %s" % file_) with open(file_, 'w') as buffer: context.configure( url=rec['url'], output_buffer=buffer, target_metadata=get_metadata(name), literal_binds=True, ) with context.begin_transaction(): context.run_migrations(engine_name=name) def run_migrations_online(): """Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context. """ # this callback is used to prevent an auto-migration from being generated # when there are no changes to the schema # reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html def process_revision_directives(context, revision, directives): if getattr(config.cmd_opts, 'autogenerate', False): script = directives[0] if len(script.upgrade_ops_list) >= len(bind_names) + 1: empty = True for upgrade_ops in script.upgrade_ops_list: if not upgrade_ops.is_empty(): empty = False if empty: directives[:] = [] logger.info('No changes in schema detected.') # for the direct-to-DB use case, start a transaction on all # engines, then run all migrations, then commit all transactions. engines = { '': { 'engine': engine_from_config( config.get_section(config.config_ini_section), prefix='sqlalchemy.', poolclass=pool.NullPool, ) } } for name in bind_names: engines[name] = rec = {} rec['engine'] = engine_from_config( context.config.get_section(name), prefix='sqlalchemy.', poolclass=pool.NullPool) for name, rec in engines.items(): engine = rec['engine'] rec['connection'] = conn = engine.connect() if USE_TWOPHASE: rec['transaction'] = conn.begin_twophase() else: rec['transaction'] = conn.begin() try: for name, rec in engines.items(): logger.info("Migrating database %s" % (name or '<default>')) context.configure( connection=rec['connection'], upgrade_token="%s_upgrades" % name, downgrade_token="%s_downgrades" % name, target_metadata=get_metadata(name), process_revision_directives=process_revision_directives, **current_app.extensions['migrate'].configure_args ) context.run_migrations(engine_name=name) if USE_TWOPHASE: for rec in engines.values(): rec['transaction'].prepare() for rec in engines.values(): rec['transaction'].commit() except: for rec in engines.values(): rec['transaction'].rollback() raise finally: for rec in engines.values(): rec['connection'].close() if context.is_offline_mode(): run_migrations_offline() else: run_migrations_online()
miguelgrinberg/Flask-Migrate
flask_migrate/templates/flask-multidb/env.py
run_migrations_offline
python
def run_migrations_offline(): # for the --sql use case, run migrations for each URL into # individual files. engines = { '': { 'url': context.config.get_main_option('sqlalchemy.url') } } for name in bind_names: engines[name] = rec = {} rec['url'] = context.config.get_section_option(name, "sqlalchemy.url") for name, rec in engines.items(): logger.info("Migrating database %s" % (name or '<default>')) file_ = "%s.sql" % name logger.info("Writing output to %s" % file_) with open(file_, 'w') as buffer: context.configure( url=rec['url'], output_buffer=buffer, target_metadata=get_metadata(name), literal_binds=True, ) with context.begin_transaction(): context.run_migrations(engine_name=name)
Run migrations in 'offline' mode. This configures the context with just a URL and not an Engine, though an Engine is acceptable here as well. By skipping the Engine creation we don't even need a DBAPI to be available. Calls to context.execute() here emit the given string to the script output.
train
https://github.com/miguelgrinberg/Flask-Migrate/blob/65fbd978681bdf2eddf8940edd04ed7272a94480/flask_migrate/templates/flask-multidb/env.py#L55-L91
[ "def get_metadata(bind):\n \"\"\"Return the metadata for a bind.\"\"\"\n if bind == '':\n bind = None\n m = MetaData()\n for t in target_metadata.tables.values():\n if t.info.get('bind_key') == bind:\n t.tometadata(m)\n return m\n" ]
from __future__ import with_statement import logging from logging.config import fileConfig import re from sqlalchemy import engine_from_config from sqlalchemy import MetaData from sqlalchemy import pool from flask import current_app from alembic import context USE_TWOPHASE = False # this is the Alembic Config object, which provides # access to the values within the .ini file in use. config = context.config # Interpret the config file for Python logging. # This line sets up loggers basically. fileConfig(config.config_file_name) logger = logging.getLogger('alembic.env') # add your model's MetaData object here # for 'autogenerate' support # from myapp import mymodel # target_metadata = mymodel.Base.metadata config.set_main_option('sqlalchemy.url', current_app.config.get('SQLALCHEMY_DATABASE_URI')) bind_names = [] for name, url in current_app.config.get("SQLALCHEMY_BINDS").items(): context.config.set_section_option(name, "sqlalchemy.url", url) bind_names.append(name) target_metadata = current_app.extensions['migrate'].db.metadata # other values from the config, defined by the needs of env.py, # can be acquired: # my_important_option = config.get_main_option("my_important_option") # ... etc. def get_metadata(bind): """Return the metadata for a bind.""" if bind == '': bind = None m = MetaData() for t in target_metadata.tables.values(): if t.info.get('bind_key') == bind: t.tometadata(m) return m def run_migrations_online(): """Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context. """ # this callback is used to prevent an auto-migration from being generated # when there are no changes to the schema # reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html def process_revision_directives(context, revision, directives): if getattr(config.cmd_opts, 'autogenerate', False): script = directives[0] if len(script.upgrade_ops_list) >= len(bind_names) + 1: empty = True for upgrade_ops in script.upgrade_ops_list: if not upgrade_ops.is_empty(): empty = False if empty: directives[:] = [] logger.info('No changes in schema detected.') # for the direct-to-DB use case, start a transaction on all # engines, then run all migrations, then commit all transactions. engines = { '': { 'engine': engine_from_config( config.get_section(config.config_ini_section), prefix='sqlalchemy.', poolclass=pool.NullPool, ) } } for name in bind_names: engines[name] = rec = {} rec['engine'] = engine_from_config( context.config.get_section(name), prefix='sqlalchemy.', poolclass=pool.NullPool) for name, rec in engines.items(): engine = rec['engine'] rec['connection'] = conn = engine.connect() if USE_TWOPHASE: rec['transaction'] = conn.begin_twophase() else: rec['transaction'] = conn.begin() try: for name, rec in engines.items(): logger.info("Migrating database %s" % (name or '<default>')) context.configure( connection=rec['connection'], upgrade_token="%s_upgrades" % name, downgrade_token="%s_downgrades" % name, target_metadata=get_metadata(name), process_revision_directives=process_revision_directives, **current_app.extensions['migrate'].configure_args ) context.run_migrations(engine_name=name) if USE_TWOPHASE: for rec in engines.values(): rec['transaction'].prepare() for rec in engines.values(): rec['transaction'].commit() except: for rec in engines.values(): rec['transaction'].rollback() raise finally: for rec in engines.values(): rec['connection'].close() if context.is_offline_mode(): run_migrations_offline() else: run_migrations_online()
miguelgrinberg/Flask-Migrate
flask_migrate/templates/flask-multidb/env.py
run_migrations_online
python
def run_migrations_online(): # this callback is used to prevent an auto-migration from being generated # when there are no changes to the schema # reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html def process_revision_directives(context, revision, directives): if getattr(config.cmd_opts, 'autogenerate', False): script = directives[0] if len(script.upgrade_ops_list) >= len(bind_names) + 1: empty = True for upgrade_ops in script.upgrade_ops_list: if not upgrade_ops.is_empty(): empty = False if empty: directives[:] = [] logger.info('No changes in schema detected.') # for the direct-to-DB use case, start a transaction on all # engines, then run all migrations, then commit all transactions. engines = { '': { 'engine': engine_from_config( config.get_section(config.config_ini_section), prefix='sqlalchemy.', poolclass=pool.NullPool, ) } } for name in bind_names: engines[name] = rec = {} rec['engine'] = engine_from_config( context.config.get_section(name), prefix='sqlalchemy.', poolclass=pool.NullPool) for name, rec in engines.items(): engine = rec['engine'] rec['connection'] = conn = engine.connect() if USE_TWOPHASE: rec['transaction'] = conn.begin_twophase() else: rec['transaction'] = conn.begin() try: for name, rec in engines.items(): logger.info("Migrating database %s" % (name or '<default>')) context.configure( connection=rec['connection'], upgrade_token="%s_upgrades" % name, downgrade_token="%s_downgrades" % name, target_metadata=get_metadata(name), process_revision_directives=process_revision_directives, **current_app.extensions['migrate'].configure_args ) context.run_migrations(engine_name=name) if USE_TWOPHASE: for rec in engines.values(): rec['transaction'].prepare() for rec in engines.values(): rec['transaction'].commit() except: for rec in engines.values(): rec['transaction'].rollback() raise finally: for rec in engines.values(): rec['connection'].close()
Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context.
train
https://github.com/miguelgrinberg/Flask-Migrate/blob/65fbd978681bdf2eddf8940edd04ed7272a94480/flask_migrate/templates/flask-multidb/env.py#L94-L169
[ "def get_metadata(bind):\n \"\"\"Return the metadata for a bind.\"\"\"\n if bind == '':\n bind = None\n m = MetaData()\n for t in target_metadata.tables.values():\n if t.info.get('bind_key') == bind:\n t.tometadata(m)\n return m\n" ]
from __future__ import with_statement import logging from logging.config import fileConfig import re from sqlalchemy import engine_from_config from sqlalchemy import MetaData from sqlalchemy import pool from flask import current_app from alembic import context USE_TWOPHASE = False # this is the Alembic Config object, which provides # access to the values within the .ini file in use. config = context.config # Interpret the config file for Python logging. # This line sets up loggers basically. fileConfig(config.config_file_name) logger = logging.getLogger('alembic.env') # add your model's MetaData object here # for 'autogenerate' support # from myapp import mymodel # target_metadata = mymodel.Base.metadata config.set_main_option('sqlalchemy.url', current_app.config.get('SQLALCHEMY_DATABASE_URI')) bind_names = [] for name, url in current_app.config.get("SQLALCHEMY_BINDS").items(): context.config.set_section_option(name, "sqlalchemy.url", url) bind_names.append(name) target_metadata = current_app.extensions['migrate'].db.metadata # other values from the config, defined by the needs of env.py, # can be acquired: # my_important_option = config.get_main_option("my_important_option") # ... etc. def get_metadata(bind): """Return the metadata for a bind.""" if bind == '': bind = None m = MetaData() for t in target_metadata.tables.values(): if t.info.get('bind_key') == bind: t.tometadata(m) return m def run_migrations_offline(): """Run migrations in 'offline' mode. This configures the context with just a URL and not an Engine, though an Engine is acceptable here as well. By skipping the Engine creation we don't even need a DBAPI to be available. Calls to context.execute() here emit the given string to the script output. """ # for the --sql use case, run migrations for each URL into # individual files. engines = { '': { 'url': context.config.get_main_option('sqlalchemy.url') } } for name in bind_names: engines[name] = rec = {} rec['url'] = context.config.get_section_option(name, "sqlalchemy.url") for name, rec in engines.items(): logger.info("Migrating database %s" % (name or '<default>')) file_ = "%s.sql" % name logger.info("Writing output to %s" % file_) with open(file_, 'w') as buffer: context.configure( url=rec['url'], output_buffer=buffer, target_metadata=get_metadata(name), literal_binds=True, ) with context.begin_transaction(): context.run_migrations(engine_name=name) if context.is_offline_mode(): run_migrations_offline() else: run_migrations_online()
miguelgrinberg/Flask-Migrate
flask_migrate/__init__.py
init
python
def init(directory=None, multidb=False): if directory is None: directory = current_app.extensions['migrate'].directory config = Config() config.set_main_option('script_location', directory) config.config_file_name = os.path.join(directory, 'alembic.ini') config = current_app.extensions['migrate'].\ migrate.call_configure_callbacks(config) if multidb: command.init(config, directory, 'flask-multidb') else: command.init(config, directory, 'flask')
Creates a new migration repository
train
https://github.com/miguelgrinberg/Flask-Migrate/blob/65fbd978681bdf2eddf8940edd04ed7272a94480/flask_migrate/__init__.py#L122-L134
null
import argparse from functools import wraps import logging import os import sys from flask import current_app try: from flask_script import Manager except ImportError: Manager = None from alembic import __version__ as __alembic_version__ from alembic.config import Config as AlembicConfig from alembic import command from alembic.util import CommandError alembic_version = tuple([int(v) for v in __alembic_version__.split('.')[0:3]]) log = logging.getLogger() class _MigrateConfig(object): def __init__(self, migrate, db, **kwargs): self.migrate = migrate self.db = db self.directory = migrate.directory self.configure_args = kwargs @property def metadata(self): """ Backwards compatibility, in old releases app.extensions['migrate'] was set to db, and env.py accessed app.extensions['migrate'].metadata """ return self.db.metadata class Config(AlembicConfig): def get_template_directory(self): package_dir = os.path.abspath(os.path.dirname(__file__)) return os.path.join(package_dir, 'templates') class Migrate(object): def __init__(self, app=None, db=None, directory='migrations', **kwargs): self.configure_callbacks = [] self.db = db self.directory = directory self.alembic_ctx_kwargs = kwargs if app is not None and db is not None: self.init_app(app, db, directory) def init_app(self, app, db=None, directory=None, **kwargs): self.db = db or self.db self.directory = directory or self.directory self.alembic_ctx_kwargs.update(kwargs) if not hasattr(app, 'extensions'): app.extensions = {} app.extensions['migrate'] = _MigrateConfig(self, self.db, **self.alembic_ctx_kwargs) def configure(self, f): self.configure_callbacks.append(f) return f def call_configure_callbacks(self, config): for f in self.configure_callbacks: config = f(config) return config def get_config(self, directory=None, x_arg=None, opts=None): if directory is None: directory = self.directory config = Config(os.path.join(directory, 'alembic.ini')) config.set_main_option('script_location', directory) if config.cmd_opts is None: config.cmd_opts = argparse.Namespace() for opt in opts or []: setattr(config.cmd_opts, opt, True) if not hasattr(config.cmd_opts, 'x'): if x_arg is not None: setattr(config.cmd_opts, 'x', []) if isinstance(x_arg, list) or isinstance(x_arg, tuple): for x in x_arg: config.cmd_opts.x.append(x) else: config.cmd_opts.x.append(x_arg) else: setattr(config.cmd_opts, 'x', None) return self.call_configure_callbacks(config) def catch_errors(f): @wraps(f) def wrapped(*args, **kwargs): try: f(*args, **kwargs) except (CommandError, RuntimeError) as exc: log.error('Error: ' + str(exc)) sys.exit(1) return wrapped if Manager is not None: MigrateCommand = Manager(usage='Perform database migrations') else: class FakeCommand(object): def option(self, *args, **kwargs): def decorator(f): return f return decorator MigrateCommand = FakeCommand() @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @MigrateCommand.option('--multidb', dest='multidb', action='store_true', default=False, help=("Multiple databases migraton (default is " "False)")) @catch_errors @MigrateCommand.option('--rev-id', dest='rev_id', default=None, help=('Specify a hardcoded revision id instead of ' 'generating one')) @MigrateCommand.option('--version-path', dest='version_path', default=None, help=('Specify specific path from config for version ' 'file')) @MigrateCommand.option('--branch-label', dest='branch_label', default=None, help=('Specify a branch label to apply to the new ' 'revision')) @MigrateCommand.option('--splice', dest='splice', action='store_true', default=False, help=('Allow a non-head revision as the "head" to ' 'splice onto')) @MigrateCommand.option('--head', dest='head', default='head', help=('Specify head revision or <branchname>@head to ' 'base new revision on')) @MigrateCommand.option('--sql', dest='sql', action='store_true', default=False, help=("Don't emit SQL to database - dump to standard " "output instead")) @MigrateCommand.option('--autogenerate', dest='autogenerate', action='store_true', default=False, help=('Populate revision script with candidate ' 'migration operations, based on comparison of ' 'database to model')) @MigrateCommand.option('-m', '--message', dest='message', default=None, help='Revision message') @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def revision(directory=None, message=None, autogenerate=False, sql=False, head='head', splice=False, branch_label=None, version_path=None, rev_id=None): """Create a new revision file.""" config = current_app.extensions['migrate'].migrate.get_config(directory) if alembic_version >= (0, 7, 0): command.revision(config, message, autogenerate=autogenerate, sql=sql, head=head, splice=splice, branch_label=branch_label, version_path=version_path, rev_id=rev_id) else: command.revision(config, message, autogenerate=autogenerate, sql=sql) @MigrateCommand.option('--rev-id', dest='rev_id', default=None, help=('Specify a hardcoded revision id instead of ' 'generating one')) @MigrateCommand.option('--version-path', dest='version_path', default=None, help=('Specify specific path from config for version ' 'file')) @MigrateCommand.option('--branch-label', dest='branch_label', default=None, help=('Specify a branch label to apply to the new ' 'revision')) @MigrateCommand.option('--splice', dest='splice', action='store_true', default=False, help=('Allow a non-head revision as the "head" to ' 'splice onto')) @MigrateCommand.option('--head', dest='head', default='head', help=('Specify head revision or <branchname>@head to ' 'base new revision on')) @MigrateCommand.option('--sql', dest='sql', action='store_true', default=False, help=("Don't emit SQL to database - dump to standard " "output instead")) @MigrateCommand.option('-m', '--message', dest='message', default=None) @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @MigrateCommand.option('-x', '--x-arg', dest='x_arg', default=None, action='append', help=("Additional arguments consumed " "by custom env.py scripts")) @catch_errors def migrate(directory=None, message=None, sql=False, head='head', splice=False, branch_label=None, version_path=None, rev_id=None, x_arg=None): """Alias for 'revision --autogenerate'""" config = current_app.extensions['migrate'].migrate.get_config( directory, opts=['autogenerate'], x_arg=x_arg) if alembic_version >= (0, 7, 0): command.revision(config, message, autogenerate=True, sql=sql, head=head, splice=splice, branch_label=branch_label, version_path=version_path, rev_id=rev_id) else: command.revision(config, message, autogenerate=True, sql=sql) @MigrateCommand.option('revision', nargs='?', default='head', help="revision identifier") @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def edit(directory=None, revision='current'): """Edit current revision.""" if alembic_version >= (0, 8, 0): config = current_app.extensions['migrate'].migrate.get_config( directory) command.edit(config, revision) else: raise RuntimeError('Alembic 0.8.0 or greater is required') @MigrateCommand.option('--rev-id', dest='rev_id', default=None, help=('Specify a hardcoded revision id instead of ' 'generating one')) @MigrateCommand.option('--branch-label', dest='branch_label', default=None, help=('Specify a branch label to apply to the new ' 'revision')) @MigrateCommand.option('-m', '--message', dest='message', default=None) @MigrateCommand.option('revisions', nargs='+', help='one or more revisions, or "heads" for all heads') @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def merge(directory=None, revisions='', message=None, branch_label=None, rev_id=None): """Merge two revisions together. Creates a new migration file""" if alembic_version >= (0, 7, 0): config = current_app.extensions['migrate'].migrate.get_config( directory) command.merge(config, revisions, message=message, branch_label=branch_label, rev_id=rev_id) else: raise RuntimeError('Alembic 0.7.0 or greater is required') @MigrateCommand.option('--tag', dest='tag', default=None, help=("Arbitrary 'tag' name - can be used by custom " "env.py scripts")) @MigrateCommand.option('--sql', dest='sql', action='store_true', default=False, help=("Don't emit SQL to database - dump to standard " "output instead")) @MigrateCommand.option('revision', nargs='?', default='head', help="revision identifier") @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @MigrateCommand.option('-x', '--x-arg', dest='x_arg', default=None, action='append', help=("Additional arguments consumed " "by custom env.py scripts")) @catch_errors def upgrade(directory=None, revision='head', sql=False, tag=None, x_arg=None): """Upgrade to a later version""" config = current_app.extensions['migrate'].migrate.get_config(directory, x_arg=x_arg) command.upgrade(config, revision, sql=sql, tag=tag) @MigrateCommand.option('--tag', dest='tag', default=None, help=("Arbitrary 'tag' name - can be used by custom " "env.py scripts")) @MigrateCommand.option('--sql', dest='sql', action='store_true', default=False, help=("Don't emit SQL to database - dump to standard " "output instead")) @MigrateCommand.option('revision', nargs='?', default="-1", help="revision identifier") @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @MigrateCommand.option('-x', '--x-arg', dest='x_arg', default=None, action='append', help=("Additional arguments consumed " "by custom env.py scripts")) @catch_errors def downgrade(directory=None, revision='-1', sql=False, tag=None, x_arg=None): """Revert to a previous version""" config = current_app.extensions['migrate'].migrate.get_config(directory, x_arg=x_arg) if sql and revision == '-1': revision = 'head:-1' command.downgrade(config, revision, sql=sql, tag=tag) @MigrateCommand.option('revision', nargs='?', default="head", help="revision identifier") @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def show(directory=None, revision='head'): """Show the revision denoted by the given symbol.""" if alembic_version >= (0, 7, 0): config = current_app.extensions['migrate'].migrate.get_config( directory) command.show(config, revision) else: raise RuntimeError('Alembic 0.7.0 or greater is required') @MigrateCommand.option('-i', '--indicate-current', dest='indicate_current', action='store_true', default=False, help='Indicate current version (Alembic 0.9.9 or greater is required)') @MigrateCommand.option('-v', '--verbose', dest='verbose', action='store_true', default=False, help='Use more verbose output') @MigrateCommand.option('-r', '--rev-range', dest='rev_range', default=None, help='Specify a revision range; format is [start]:[end]') @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def history(directory=None, rev_range=None, verbose=False, indicate_current=False): """List changeset scripts in chronological order.""" config = current_app.extensions['migrate'].migrate.get_config(directory) if alembic_version >= (0, 9, 9): command.history(config, rev_range, verbose=verbose, indicate_current=indicate_current) elif alembic_version >= (0, 7, 0): command.history(config, rev_range, verbose=verbose) else: command.history(config, rev_range) @MigrateCommand.option('--resolve-dependencies', dest='resolve_dependencies', action='store_true', default=False, help='Treat dependency versions as down revisions') @MigrateCommand.option('-v', '--verbose', dest='verbose', action='store_true', default=False, help='Use more verbose output') @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def heads(directory=None, verbose=False, resolve_dependencies=False): """Show current available heads in the script directory""" if alembic_version >= (0, 7, 0): config = current_app.extensions['migrate'].migrate.get_config( directory) command.heads(config, verbose=verbose, resolve_dependencies=resolve_dependencies) else: raise RuntimeError('Alembic 0.7.0 or greater is required') @MigrateCommand.option('-v', '--verbose', dest='verbose', action='store_true', default=False, help='Use more verbose output') @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def branches(directory=None, verbose=False): """Show current branch points""" config = current_app.extensions['migrate'].migrate.get_config(directory) if alembic_version >= (0, 7, 0): command.branches(config, verbose=verbose) else: command.branches(config) @MigrateCommand.option('--head-only', dest='head_only', action='store_true', default=False, help='Deprecated. Use --verbose for additional output') @MigrateCommand.option('-v', '--verbose', dest='verbose', action='store_true', default=False, help='Use more verbose output') @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def current(directory=None, verbose=False, head_only=False): """Display the current revision for each database.""" config = current_app.extensions['migrate'].migrate.get_config(directory) if alembic_version >= (0, 7, 0): command.current(config, verbose=verbose, head_only=head_only) else: command.current(config) @MigrateCommand.option('--tag', dest='tag', default=None, help=("Arbitrary 'tag' name - can be used by custom " "env.py scripts")) @MigrateCommand.option('--sql', dest='sql', action='store_true', default=False, help=("Don't emit SQL to database - dump to standard " "output instead")) @MigrateCommand.option('revision', default=None, help="revision identifier") @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def stamp(directory=None, revision='head', sql=False, tag=None): """'stamp' the revision table with the given revision; don't run any migrations""" config = current_app.extensions['migrate'].migrate.get_config(directory) command.stamp(config, revision, sql=sql, tag=tag)
miguelgrinberg/Flask-Migrate
flask_migrate/__init__.py
revision
python
def revision(directory=None, message=None, autogenerate=False, sql=False, head='head', splice=False, branch_label=None, version_path=None, rev_id=None): config = current_app.extensions['migrate'].migrate.get_config(directory) if alembic_version >= (0, 7, 0): command.revision(config, message, autogenerate=autogenerate, sql=sql, head=head, splice=splice, branch_label=branch_label, version_path=version_path, rev_id=rev_id) else: command.revision(config, message, autogenerate=autogenerate, sql=sql)
Create a new revision file.
train
https://github.com/miguelgrinberg/Flask-Migrate/blob/65fbd978681bdf2eddf8940edd04ed7272a94480/flask_migrate/__init__.py#L167-L177
null
import argparse from functools import wraps import logging import os import sys from flask import current_app try: from flask_script import Manager except ImportError: Manager = None from alembic import __version__ as __alembic_version__ from alembic.config import Config as AlembicConfig from alembic import command from alembic.util import CommandError alembic_version = tuple([int(v) for v in __alembic_version__.split('.')[0:3]]) log = logging.getLogger() class _MigrateConfig(object): def __init__(self, migrate, db, **kwargs): self.migrate = migrate self.db = db self.directory = migrate.directory self.configure_args = kwargs @property def metadata(self): """ Backwards compatibility, in old releases app.extensions['migrate'] was set to db, and env.py accessed app.extensions['migrate'].metadata """ return self.db.metadata class Config(AlembicConfig): def get_template_directory(self): package_dir = os.path.abspath(os.path.dirname(__file__)) return os.path.join(package_dir, 'templates') class Migrate(object): def __init__(self, app=None, db=None, directory='migrations', **kwargs): self.configure_callbacks = [] self.db = db self.directory = directory self.alembic_ctx_kwargs = kwargs if app is not None and db is not None: self.init_app(app, db, directory) def init_app(self, app, db=None, directory=None, **kwargs): self.db = db or self.db self.directory = directory or self.directory self.alembic_ctx_kwargs.update(kwargs) if not hasattr(app, 'extensions'): app.extensions = {} app.extensions['migrate'] = _MigrateConfig(self, self.db, **self.alembic_ctx_kwargs) def configure(self, f): self.configure_callbacks.append(f) return f def call_configure_callbacks(self, config): for f in self.configure_callbacks: config = f(config) return config def get_config(self, directory=None, x_arg=None, opts=None): if directory is None: directory = self.directory config = Config(os.path.join(directory, 'alembic.ini')) config.set_main_option('script_location', directory) if config.cmd_opts is None: config.cmd_opts = argparse.Namespace() for opt in opts or []: setattr(config.cmd_opts, opt, True) if not hasattr(config.cmd_opts, 'x'): if x_arg is not None: setattr(config.cmd_opts, 'x', []) if isinstance(x_arg, list) or isinstance(x_arg, tuple): for x in x_arg: config.cmd_opts.x.append(x) else: config.cmd_opts.x.append(x_arg) else: setattr(config.cmd_opts, 'x', None) return self.call_configure_callbacks(config) def catch_errors(f): @wraps(f) def wrapped(*args, **kwargs): try: f(*args, **kwargs) except (CommandError, RuntimeError) as exc: log.error('Error: ' + str(exc)) sys.exit(1) return wrapped if Manager is not None: MigrateCommand = Manager(usage='Perform database migrations') else: class FakeCommand(object): def option(self, *args, **kwargs): def decorator(f): return f return decorator MigrateCommand = FakeCommand() @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @MigrateCommand.option('--multidb', dest='multidb', action='store_true', default=False, help=("Multiple databases migraton (default is " "False)")) @catch_errors def init(directory=None, multidb=False): """Creates a new migration repository""" if directory is None: directory = current_app.extensions['migrate'].directory config = Config() config.set_main_option('script_location', directory) config.config_file_name = os.path.join(directory, 'alembic.ini') config = current_app.extensions['migrate'].\ migrate.call_configure_callbacks(config) if multidb: command.init(config, directory, 'flask-multidb') else: command.init(config, directory, 'flask') @MigrateCommand.option('--rev-id', dest='rev_id', default=None, help=('Specify a hardcoded revision id instead of ' 'generating one')) @MigrateCommand.option('--version-path', dest='version_path', default=None, help=('Specify specific path from config for version ' 'file')) @MigrateCommand.option('--branch-label', dest='branch_label', default=None, help=('Specify a branch label to apply to the new ' 'revision')) @MigrateCommand.option('--splice', dest='splice', action='store_true', default=False, help=('Allow a non-head revision as the "head" to ' 'splice onto')) @MigrateCommand.option('--head', dest='head', default='head', help=('Specify head revision or <branchname>@head to ' 'base new revision on')) @MigrateCommand.option('--sql', dest='sql', action='store_true', default=False, help=("Don't emit SQL to database - dump to standard " "output instead")) @MigrateCommand.option('--autogenerate', dest='autogenerate', action='store_true', default=False, help=('Populate revision script with candidate ' 'migration operations, based on comparison of ' 'database to model')) @MigrateCommand.option('-m', '--message', dest='message', default=None, help='Revision message') @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors @MigrateCommand.option('--rev-id', dest='rev_id', default=None, help=('Specify a hardcoded revision id instead of ' 'generating one')) @MigrateCommand.option('--version-path', dest='version_path', default=None, help=('Specify specific path from config for version ' 'file')) @MigrateCommand.option('--branch-label', dest='branch_label', default=None, help=('Specify a branch label to apply to the new ' 'revision')) @MigrateCommand.option('--splice', dest='splice', action='store_true', default=False, help=('Allow a non-head revision as the "head" to ' 'splice onto')) @MigrateCommand.option('--head', dest='head', default='head', help=('Specify head revision or <branchname>@head to ' 'base new revision on')) @MigrateCommand.option('--sql', dest='sql', action='store_true', default=False, help=("Don't emit SQL to database - dump to standard " "output instead")) @MigrateCommand.option('-m', '--message', dest='message', default=None) @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @MigrateCommand.option('-x', '--x-arg', dest='x_arg', default=None, action='append', help=("Additional arguments consumed " "by custom env.py scripts")) @catch_errors def migrate(directory=None, message=None, sql=False, head='head', splice=False, branch_label=None, version_path=None, rev_id=None, x_arg=None): """Alias for 'revision --autogenerate'""" config = current_app.extensions['migrate'].migrate.get_config( directory, opts=['autogenerate'], x_arg=x_arg) if alembic_version >= (0, 7, 0): command.revision(config, message, autogenerate=True, sql=sql, head=head, splice=splice, branch_label=branch_label, version_path=version_path, rev_id=rev_id) else: command.revision(config, message, autogenerate=True, sql=sql) @MigrateCommand.option('revision', nargs='?', default='head', help="revision identifier") @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def edit(directory=None, revision='current'): """Edit current revision.""" if alembic_version >= (0, 8, 0): config = current_app.extensions['migrate'].migrate.get_config( directory) command.edit(config, revision) else: raise RuntimeError('Alembic 0.8.0 or greater is required') @MigrateCommand.option('--rev-id', dest='rev_id', default=None, help=('Specify a hardcoded revision id instead of ' 'generating one')) @MigrateCommand.option('--branch-label', dest='branch_label', default=None, help=('Specify a branch label to apply to the new ' 'revision')) @MigrateCommand.option('-m', '--message', dest='message', default=None) @MigrateCommand.option('revisions', nargs='+', help='one or more revisions, or "heads" for all heads') @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def merge(directory=None, revisions='', message=None, branch_label=None, rev_id=None): """Merge two revisions together. Creates a new migration file""" if alembic_version >= (0, 7, 0): config = current_app.extensions['migrate'].migrate.get_config( directory) command.merge(config, revisions, message=message, branch_label=branch_label, rev_id=rev_id) else: raise RuntimeError('Alembic 0.7.0 or greater is required') @MigrateCommand.option('--tag', dest='tag', default=None, help=("Arbitrary 'tag' name - can be used by custom " "env.py scripts")) @MigrateCommand.option('--sql', dest='sql', action='store_true', default=False, help=("Don't emit SQL to database - dump to standard " "output instead")) @MigrateCommand.option('revision', nargs='?', default='head', help="revision identifier") @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @MigrateCommand.option('-x', '--x-arg', dest='x_arg', default=None, action='append', help=("Additional arguments consumed " "by custom env.py scripts")) @catch_errors def upgrade(directory=None, revision='head', sql=False, tag=None, x_arg=None): """Upgrade to a later version""" config = current_app.extensions['migrate'].migrate.get_config(directory, x_arg=x_arg) command.upgrade(config, revision, sql=sql, tag=tag) @MigrateCommand.option('--tag', dest='tag', default=None, help=("Arbitrary 'tag' name - can be used by custom " "env.py scripts")) @MigrateCommand.option('--sql', dest='sql', action='store_true', default=False, help=("Don't emit SQL to database - dump to standard " "output instead")) @MigrateCommand.option('revision', nargs='?', default="-1", help="revision identifier") @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @MigrateCommand.option('-x', '--x-arg', dest='x_arg', default=None, action='append', help=("Additional arguments consumed " "by custom env.py scripts")) @catch_errors def downgrade(directory=None, revision='-1', sql=False, tag=None, x_arg=None): """Revert to a previous version""" config = current_app.extensions['migrate'].migrate.get_config(directory, x_arg=x_arg) if sql and revision == '-1': revision = 'head:-1' command.downgrade(config, revision, sql=sql, tag=tag) @MigrateCommand.option('revision', nargs='?', default="head", help="revision identifier") @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def show(directory=None, revision='head'): """Show the revision denoted by the given symbol.""" if alembic_version >= (0, 7, 0): config = current_app.extensions['migrate'].migrate.get_config( directory) command.show(config, revision) else: raise RuntimeError('Alembic 0.7.0 or greater is required') @MigrateCommand.option('-i', '--indicate-current', dest='indicate_current', action='store_true', default=False, help='Indicate current version (Alembic 0.9.9 or greater is required)') @MigrateCommand.option('-v', '--verbose', dest='verbose', action='store_true', default=False, help='Use more verbose output') @MigrateCommand.option('-r', '--rev-range', dest='rev_range', default=None, help='Specify a revision range; format is [start]:[end]') @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def history(directory=None, rev_range=None, verbose=False, indicate_current=False): """List changeset scripts in chronological order.""" config = current_app.extensions['migrate'].migrate.get_config(directory) if alembic_version >= (0, 9, 9): command.history(config, rev_range, verbose=verbose, indicate_current=indicate_current) elif alembic_version >= (0, 7, 0): command.history(config, rev_range, verbose=verbose) else: command.history(config, rev_range) @MigrateCommand.option('--resolve-dependencies', dest='resolve_dependencies', action='store_true', default=False, help='Treat dependency versions as down revisions') @MigrateCommand.option('-v', '--verbose', dest='verbose', action='store_true', default=False, help='Use more verbose output') @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def heads(directory=None, verbose=False, resolve_dependencies=False): """Show current available heads in the script directory""" if alembic_version >= (0, 7, 0): config = current_app.extensions['migrate'].migrate.get_config( directory) command.heads(config, verbose=verbose, resolve_dependencies=resolve_dependencies) else: raise RuntimeError('Alembic 0.7.0 or greater is required') @MigrateCommand.option('-v', '--verbose', dest='verbose', action='store_true', default=False, help='Use more verbose output') @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def branches(directory=None, verbose=False): """Show current branch points""" config = current_app.extensions['migrate'].migrate.get_config(directory) if alembic_version >= (0, 7, 0): command.branches(config, verbose=verbose) else: command.branches(config) @MigrateCommand.option('--head-only', dest='head_only', action='store_true', default=False, help='Deprecated. Use --verbose for additional output') @MigrateCommand.option('-v', '--verbose', dest='verbose', action='store_true', default=False, help='Use more verbose output') @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def current(directory=None, verbose=False, head_only=False): """Display the current revision for each database.""" config = current_app.extensions['migrate'].migrate.get_config(directory) if alembic_version >= (0, 7, 0): command.current(config, verbose=verbose, head_only=head_only) else: command.current(config) @MigrateCommand.option('--tag', dest='tag', default=None, help=("Arbitrary 'tag' name - can be used by custom " "env.py scripts")) @MigrateCommand.option('--sql', dest='sql', action='store_true', default=False, help=("Don't emit SQL to database - dump to standard " "output instead")) @MigrateCommand.option('revision', default=None, help="revision identifier") @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def stamp(directory=None, revision='head', sql=False, tag=None): """'stamp' the revision table with the given revision; don't run any migrations""" config = current_app.extensions['migrate'].migrate.get_config(directory) command.stamp(config, revision, sql=sql, tag=tag)
miguelgrinberg/Flask-Migrate
flask_migrate/__init__.py
edit
python
def edit(directory=None, revision='current'): if alembic_version >= (0, 8, 0): config = current_app.extensions['migrate'].migrate.get_config( directory) command.edit(config, revision) else: raise RuntimeError('Alembic 0.8.0 or greater is required')
Edit current revision.
train
https://github.com/miguelgrinberg/Flask-Migrate/blob/65fbd978681bdf2eddf8940edd04ed7272a94480/flask_migrate/__init__.py#L226-L233
null
import argparse from functools import wraps import logging import os import sys from flask import current_app try: from flask_script import Manager except ImportError: Manager = None from alembic import __version__ as __alembic_version__ from alembic.config import Config as AlembicConfig from alembic import command from alembic.util import CommandError alembic_version = tuple([int(v) for v in __alembic_version__.split('.')[0:3]]) log = logging.getLogger() class _MigrateConfig(object): def __init__(self, migrate, db, **kwargs): self.migrate = migrate self.db = db self.directory = migrate.directory self.configure_args = kwargs @property def metadata(self): """ Backwards compatibility, in old releases app.extensions['migrate'] was set to db, and env.py accessed app.extensions['migrate'].metadata """ return self.db.metadata class Config(AlembicConfig): def get_template_directory(self): package_dir = os.path.abspath(os.path.dirname(__file__)) return os.path.join(package_dir, 'templates') class Migrate(object): def __init__(self, app=None, db=None, directory='migrations', **kwargs): self.configure_callbacks = [] self.db = db self.directory = directory self.alembic_ctx_kwargs = kwargs if app is not None and db is not None: self.init_app(app, db, directory) def init_app(self, app, db=None, directory=None, **kwargs): self.db = db or self.db self.directory = directory or self.directory self.alembic_ctx_kwargs.update(kwargs) if not hasattr(app, 'extensions'): app.extensions = {} app.extensions['migrate'] = _MigrateConfig(self, self.db, **self.alembic_ctx_kwargs) def configure(self, f): self.configure_callbacks.append(f) return f def call_configure_callbacks(self, config): for f in self.configure_callbacks: config = f(config) return config def get_config(self, directory=None, x_arg=None, opts=None): if directory is None: directory = self.directory config = Config(os.path.join(directory, 'alembic.ini')) config.set_main_option('script_location', directory) if config.cmd_opts is None: config.cmd_opts = argparse.Namespace() for opt in opts or []: setattr(config.cmd_opts, opt, True) if not hasattr(config.cmd_opts, 'x'): if x_arg is not None: setattr(config.cmd_opts, 'x', []) if isinstance(x_arg, list) or isinstance(x_arg, tuple): for x in x_arg: config.cmd_opts.x.append(x) else: config.cmd_opts.x.append(x_arg) else: setattr(config.cmd_opts, 'x', None) return self.call_configure_callbacks(config) def catch_errors(f): @wraps(f) def wrapped(*args, **kwargs): try: f(*args, **kwargs) except (CommandError, RuntimeError) as exc: log.error('Error: ' + str(exc)) sys.exit(1) return wrapped if Manager is not None: MigrateCommand = Manager(usage='Perform database migrations') else: class FakeCommand(object): def option(self, *args, **kwargs): def decorator(f): return f return decorator MigrateCommand = FakeCommand() @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @MigrateCommand.option('--multidb', dest='multidb', action='store_true', default=False, help=("Multiple databases migraton (default is " "False)")) @catch_errors def init(directory=None, multidb=False): """Creates a new migration repository""" if directory is None: directory = current_app.extensions['migrate'].directory config = Config() config.set_main_option('script_location', directory) config.config_file_name = os.path.join(directory, 'alembic.ini') config = current_app.extensions['migrate'].\ migrate.call_configure_callbacks(config) if multidb: command.init(config, directory, 'flask-multidb') else: command.init(config, directory, 'flask') @MigrateCommand.option('--rev-id', dest='rev_id', default=None, help=('Specify a hardcoded revision id instead of ' 'generating one')) @MigrateCommand.option('--version-path', dest='version_path', default=None, help=('Specify specific path from config for version ' 'file')) @MigrateCommand.option('--branch-label', dest='branch_label', default=None, help=('Specify a branch label to apply to the new ' 'revision')) @MigrateCommand.option('--splice', dest='splice', action='store_true', default=False, help=('Allow a non-head revision as the "head" to ' 'splice onto')) @MigrateCommand.option('--head', dest='head', default='head', help=('Specify head revision or <branchname>@head to ' 'base new revision on')) @MigrateCommand.option('--sql', dest='sql', action='store_true', default=False, help=("Don't emit SQL to database - dump to standard " "output instead")) @MigrateCommand.option('--autogenerate', dest='autogenerate', action='store_true', default=False, help=('Populate revision script with candidate ' 'migration operations, based on comparison of ' 'database to model')) @MigrateCommand.option('-m', '--message', dest='message', default=None, help='Revision message') @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def revision(directory=None, message=None, autogenerate=False, sql=False, head='head', splice=False, branch_label=None, version_path=None, rev_id=None): """Create a new revision file.""" config = current_app.extensions['migrate'].migrate.get_config(directory) if alembic_version >= (0, 7, 0): command.revision(config, message, autogenerate=autogenerate, sql=sql, head=head, splice=splice, branch_label=branch_label, version_path=version_path, rev_id=rev_id) else: command.revision(config, message, autogenerate=autogenerate, sql=sql) @MigrateCommand.option('--rev-id', dest='rev_id', default=None, help=('Specify a hardcoded revision id instead of ' 'generating one')) @MigrateCommand.option('--version-path', dest='version_path', default=None, help=('Specify specific path from config for version ' 'file')) @MigrateCommand.option('--branch-label', dest='branch_label', default=None, help=('Specify a branch label to apply to the new ' 'revision')) @MigrateCommand.option('--splice', dest='splice', action='store_true', default=False, help=('Allow a non-head revision as the "head" to ' 'splice onto')) @MigrateCommand.option('--head', dest='head', default='head', help=('Specify head revision or <branchname>@head to ' 'base new revision on')) @MigrateCommand.option('--sql', dest='sql', action='store_true', default=False, help=("Don't emit SQL to database - dump to standard " "output instead")) @MigrateCommand.option('-m', '--message', dest='message', default=None) @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @MigrateCommand.option('-x', '--x-arg', dest='x_arg', default=None, action='append', help=("Additional arguments consumed " "by custom env.py scripts")) @catch_errors def migrate(directory=None, message=None, sql=False, head='head', splice=False, branch_label=None, version_path=None, rev_id=None, x_arg=None): """Alias for 'revision --autogenerate'""" config = current_app.extensions['migrate'].migrate.get_config( directory, opts=['autogenerate'], x_arg=x_arg) if alembic_version >= (0, 7, 0): command.revision(config, message, autogenerate=True, sql=sql, head=head, splice=splice, branch_label=branch_label, version_path=version_path, rev_id=rev_id) else: command.revision(config, message, autogenerate=True, sql=sql) @MigrateCommand.option('revision', nargs='?', default='head', help="revision identifier") @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors @MigrateCommand.option('--rev-id', dest='rev_id', default=None, help=('Specify a hardcoded revision id instead of ' 'generating one')) @MigrateCommand.option('--branch-label', dest='branch_label', default=None, help=('Specify a branch label to apply to the new ' 'revision')) @MigrateCommand.option('-m', '--message', dest='message', default=None) @MigrateCommand.option('revisions', nargs='+', help='one or more revisions, or "heads" for all heads') @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def merge(directory=None, revisions='', message=None, branch_label=None, rev_id=None): """Merge two revisions together. Creates a new migration file""" if alembic_version >= (0, 7, 0): config = current_app.extensions['migrate'].migrate.get_config( directory) command.merge(config, revisions, message=message, branch_label=branch_label, rev_id=rev_id) else: raise RuntimeError('Alembic 0.7.0 or greater is required') @MigrateCommand.option('--tag', dest='tag', default=None, help=("Arbitrary 'tag' name - can be used by custom " "env.py scripts")) @MigrateCommand.option('--sql', dest='sql', action='store_true', default=False, help=("Don't emit SQL to database - dump to standard " "output instead")) @MigrateCommand.option('revision', nargs='?', default='head', help="revision identifier") @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @MigrateCommand.option('-x', '--x-arg', dest='x_arg', default=None, action='append', help=("Additional arguments consumed " "by custom env.py scripts")) @catch_errors def upgrade(directory=None, revision='head', sql=False, tag=None, x_arg=None): """Upgrade to a later version""" config = current_app.extensions['migrate'].migrate.get_config(directory, x_arg=x_arg) command.upgrade(config, revision, sql=sql, tag=tag) @MigrateCommand.option('--tag', dest='tag', default=None, help=("Arbitrary 'tag' name - can be used by custom " "env.py scripts")) @MigrateCommand.option('--sql', dest='sql', action='store_true', default=False, help=("Don't emit SQL to database - dump to standard " "output instead")) @MigrateCommand.option('revision', nargs='?', default="-1", help="revision identifier") @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @MigrateCommand.option('-x', '--x-arg', dest='x_arg', default=None, action='append', help=("Additional arguments consumed " "by custom env.py scripts")) @catch_errors def downgrade(directory=None, revision='-1', sql=False, tag=None, x_arg=None): """Revert to a previous version""" config = current_app.extensions['migrate'].migrate.get_config(directory, x_arg=x_arg) if sql and revision == '-1': revision = 'head:-1' command.downgrade(config, revision, sql=sql, tag=tag) @MigrateCommand.option('revision', nargs='?', default="head", help="revision identifier") @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def show(directory=None, revision='head'): """Show the revision denoted by the given symbol.""" if alembic_version >= (0, 7, 0): config = current_app.extensions['migrate'].migrate.get_config( directory) command.show(config, revision) else: raise RuntimeError('Alembic 0.7.0 or greater is required') @MigrateCommand.option('-i', '--indicate-current', dest='indicate_current', action='store_true', default=False, help='Indicate current version (Alembic 0.9.9 or greater is required)') @MigrateCommand.option('-v', '--verbose', dest='verbose', action='store_true', default=False, help='Use more verbose output') @MigrateCommand.option('-r', '--rev-range', dest='rev_range', default=None, help='Specify a revision range; format is [start]:[end]') @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def history(directory=None, rev_range=None, verbose=False, indicate_current=False): """List changeset scripts in chronological order.""" config = current_app.extensions['migrate'].migrate.get_config(directory) if alembic_version >= (0, 9, 9): command.history(config, rev_range, verbose=verbose, indicate_current=indicate_current) elif alembic_version >= (0, 7, 0): command.history(config, rev_range, verbose=verbose) else: command.history(config, rev_range) @MigrateCommand.option('--resolve-dependencies', dest='resolve_dependencies', action='store_true', default=False, help='Treat dependency versions as down revisions') @MigrateCommand.option('-v', '--verbose', dest='verbose', action='store_true', default=False, help='Use more verbose output') @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def heads(directory=None, verbose=False, resolve_dependencies=False): """Show current available heads in the script directory""" if alembic_version >= (0, 7, 0): config = current_app.extensions['migrate'].migrate.get_config( directory) command.heads(config, verbose=verbose, resolve_dependencies=resolve_dependencies) else: raise RuntimeError('Alembic 0.7.0 or greater is required') @MigrateCommand.option('-v', '--verbose', dest='verbose', action='store_true', default=False, help='Use more verbose output') @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def branches(directory=None, verbose=False): """Show current branch points""" config = current_app.extensions['migrate'].migrate.get_config(directory) if alembic_version >= (0, 7, 0): command.branches(config, verbose=verbose) else: command.branches(config) @MigrateCommand.option('--head-only', dest='head_only', action='store_true', default=False, help='Deprecated. Use --verbose for additional output') @MigrateCommand.option('-v', '--verbose', dest='verbose', action='store_true', default=False, help='Use more verbose output') @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def current(directory=None, verbose=False, head_only=False): """Display the current revision for each database.""" config = current_app.extensions['migrate'].migrate.get_config(directory) if alembic_version >= (0, 7, 0): command.current(config, verbose=verbose, head_only=head_only) else: command.current(config) @MigrateCommand.option('--tag', dest='tag', default=None, help=("Arbitrary 'tag' name - can be used by custom " "env.py scripts")) @MigrateCommand.option('--sql', dest='sql', action='store_true', default=False, help=("Don't emit SQL to database - dump to standard " "output instead")) @MigrateCommand.option('revision', default=None, help="revision identifier") @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def stamp(directory=None, revision='head', sql=False, tag=None): """'stamp' the revision table with the given revision; don't run any migrations""" config = current_app.extensions['migrate'].migrate.get_config(directory) command.stamp(config, revision, sql=sql, tag=tag)
miguelgrinberg/Flask-Migrate
flask_migrate/__init__.py
merge
python
def merge(directory=None, revisions='', message=None, branch_label=None, rev_id=None): if alembic_version >= (0, 7, 0): config = current_app.extensions['migrate'].migrate.get_config( directory) command.merge(config, revisions, message=message, branch_label=branch_label, rev_id=rev_id) else: raise RuntimeError('Alembic 0.7.0 or greater is required')
Merge two revisions together. Creates a new migration file
train
https://github.com/miguelgrinberg/Flask-Migrate/blob/65fbd978681bdf2eddf8940edd04ed7272a94480/flask_migrate/__init__.py#L249-L258
null
import argparse from functools import wraps import logging import os import sys from flask import current_app try: from flask_script import Manager except ImportError: Manager = None from alembic import __version__ as __alembic_version__ from alembic.config import Config as AlembicConfig from alembic import command from alembic.util import CommandError alembic_version = tuple([int(v) for v in __alembic_version__.split('.')[0:3]]) log = logging.getLogger() class _MigrateConfig(object): def __init__(self, migrate, db, **kwargs): self.migrate = migrate self.db = db self.directory = migrate.directory self.configure_args = kwargs @property def metadata(self): """ Backwards compatibility, in old releases app.extensions['migrate'] was set to db, and env.py accessed app.extensions['migrate'].metadata """ return self.db.metadata class Config(AlembicConfig): def get_template_directory(self): package_dir = os.path.abspath(os.path.dirname(__file__)) return os.path.join(package_dir, 'templates') class Migrate(object): def __init__(self, app=None, db=None, directory='migrations', **kwargs): self.configure_callbacks = [] self.db = db self.directory = directory self.alembic_ctx_kwargs = kwargs if app is not None and db is not None: self.init_app(app, db, directory) def init_app(self, app, db=None, directory=None, **kwargs): self.db = db or self.db self.directory = directory or self.directory self.alembic_ctx_kwargs.update(kwargs) if not hasattr(app, 'extensions'): app.extensions = {} app.extensions['migrate'] = _MigrateConfig(self, self.db, **self.alembic_ctx_kwargs) def configure(self, f): self.configure_callbacks.append(f) return f def call_configure_callbacks(self, config): for f in self.configure_callbacks: config = f(config) return config def get_config(self, directory=None, x_arg=None, opts=None): if directory is None: directory = self.directory config = Config(os.path.join(directory, 'alembic.ini')) config.set_main_option('script_location', directory) if config.cmd_opts is None: config.cmd_opts = argparse.Namespace() for opt in opts or []: setattr(config.cmd_opts, opt, True) if not hasattr(config.cmd_opts, 'x'): if x_arg is not None: setattr(config.cmd_opts, 'x', []) if isinstance(x_arg, list) or isinstance(x_arg, tuple): for x in x_arg: config.cmd_opts.x.append(x) else: config.cmd_opts.x.append(x_arg) else: setattr(config.cmd_opts, 'x', None) return self.call_configure_callbacks(config) def catch_errors(f): @wraps(f) def wrapped(*args, **kwargs): try: f(*args, **kwargs) except (CommandError, RuntimeError) as exc: log.error('Error: ' + str(exc)) sys.exit(1) return wrapped if Manager is not None: MigrateCommand = Manager(usage='Perform database migrations') else: class FakeCommand(object): def option(self, *args, **kwargs): def decorator(f): return f return decorator MigrateCommand = FakeCommand() @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @MigrateCommand.option('--multidb', dest='multidb', action='store_true', default=False, help=("Multiple databases migraton (default is " "False)")) @catch_errors def init(directory=None, multidb=False): """Creates a new migration repository""" if directory is None: directory = current_app.extensions['migrate'].directory config = Config() config.set_main_option('script_location', directory) config.config_file_name = os.path.join(directory, 'alembic.ini') config = current_app.extensions['migrate'].\ migrate.call_configure_callbacks(config) if multidb: command.init(config, directory, 'flask-multidb') else: command.init(config, directory, 'flask') @MigrateCommand.option('--rev-id', dest='rev_id', default=None, help=('Specify a hardcoded revision id instead of ' 'generating one')) @MigrateCommand.option('--version-path', dest='version_path', default=None, help=('Specify specific path from config for version ' 'file')) @MigrateCommand.option('--branch-label', dest='branch_label', default=None, help=('Specify a branch label to apply to the new ' 'revision')) @MigrateCommand.option('--splice', dest='splice', action='store_true', default=False, help=('Allow a non-head revision as the "head" to ' 'splice onto')) @MigrateCommand.option('--head', dest='head', default='head', help=('Specify head revision or <branchname>@head to ' 'base new revision on')) @MigrateCommand.option('--sql', dest='sql', action='store_true', default=False, help=("Don't emit SQL to database - dump to standard " "output instead")) @MigrateCommand.option('--autogenerate', dest='autogenerate', action='store_true', default=False, help=('Populate revision script with candidate ' 'migration operations, based on comparison of ' 'database to model')) @MigrateCommand.option('-m', '--message', dest='message', default=None, help='Revision message') @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def revision(directory=None, message=None, autogenerate=False, sql=False, head='head', splice=False, branch_label=None, version_path=None, rev_id=None): """Create a new revision file.""" config = current_app.extensions['migrate'].migrate.get_config(directory) if alembic_version >= (0, 7, 0): command.revision(config, message, autogenerate=autogenerate, sql=sql, head=head, splice=splice, branch_label=branch_label, version_path=version_path, rev_id=rev_id) else: command.revision(config, message, autogenerate=autogenerate, sql=sql) @MigrateCommand.option('--rev-id', dest='rev_id', default=None, help=('Specify a hardcoded revision id instead of ' 'generating one')) @MigrateCommand.option('--version-path', dest='version_path', default=None, help=('Specify specific path from config for version ' 'file')) @MigrateCommand.option('--branch-label', dest='branch_label', default=None, help=('Specify a branch label to apply to the new ' 'revision')) @MigrateCommand.option('--splice', dest='splice', action='store_true', default=False, help=('Allow a non-head revision as the "head" to ' 'splice onto')) @MigrateCommand.option('--head', dest='head', default='head', help=('Specify head revision or <branchname>@head to ' 'base new revision on')) @MigrateCommand.option('--sql', dest='sql', action='store_true', default=False, help=("Don't emit SQL to database - dump to standard " "output instead")) @MigrateCommand.option('-m', '--message', dest='message', default=None) @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @MigrateCommand.option('-x', '--x-arg', dest='x_arg', default=None, action='append', help=("Additional arguments consumed " "by custom env.py scripts")) @catch_errors def migrate(directory=None, message=None, sql=False, head='head', splice=False, branch_label=None, version_path=None, rev_id=None, x_arg=None): """Alias for 'revision --autogenerate'""" config = current_app.extensions['migrate'].migrate.get_config( directory, opts=['autogenerate'], x_arg=x_arg) if alembic_version >= (0, 7, 0): command.revision(config, message, autogenerate=True, sql=sql, head=head, splice=splice, branch_label=branch_label, version_path=version_path, rev_id=rev_id) else: command.revision(config, message, autogenerate=True, sql=sql) @MigrateCommand.option('revision', nargs='?', default='head', help="revision identifier") @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def edit(directory=None, revision='current'): """Edit current revision.""" if alembic_version >= (0, 8, 0): config = current_app.extensions['migrate'].migrate.get_config( directory) command.edit(config, revision) else: raise RuntimeError('Alembic 0.8.0 or greater is required') @MigrateCommand.option('--rev-id', dest='rev_id', default=None, help=('Specify a hardcoded revision id instead of ' 'generating one')) @MigrateCommand.option('--branch-label', dest='branch_label', default=None, help=('Specify a branch label to apply to the new ' 'revision')) @MigrateCommand.option('-m', '--message', dest='message', default=None) @MigrateCommand.option('revisions', nargs='+', help='one or more revisions, or "heads" for all heads') @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors @MigrateCommand.option('--tag', dest='tag', default=None, help=("Arbitrary 'tag' name - can be used by custom " "env.py scripts")) @MigrateCommand.option('--sql', dest='sql', action='store_true', default=False, help=("Don't emit SQL to database - dump to standard " "output instead")) @MigrateCommand.option('revision', nargs='?', default='head', help="revision identifier") @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @MigrateCommand.option('-x', '--x-arg', dest='x_arg', default=None, action='append', help=("Additional arguments consumed " "by custom env.py scripts")) @catch_errors def upgrade(directory=None, revision='head', sql=False, tag=None, x_arg=None): """Upgrade to a later version""" config = current_app.extensions['migrate'].migrate.get_config(directory, x_arg=x_arg) command.upgrade(config, revision, sql=sql, tag=tag) @MigrateCommand.option('--tag', dest='tag', default=None, help=("Arbitrary 'tag' name - can be used by custom " "env.py scripts")) @MigrateCommand.option('--sql', dest='sql', action='store_true', default=False, help=("Don't emit SQL to database - dump to standard " "output instead")) @MigrateCommand.option('revision', nargs='?', default="-1", help="revision identifier") @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @MigrateCommand.option('-x', '--x-arg', dest='x_arg', default=None, action='append', help=("Additional arguments consumed " "by custom env.py scripts")) @catch_errors def downgrade(directory=None, revision='-1', sql=False, tag=None, x_arg=None): """Revert to a previous version""" config = current_app.extensions['migrate'].migrate.get_config(directory, x_arg=x_arg) if sql and revision == '-1': revision = 'head:-1' command.downgrade(config, revision, sql=sql, tag=tag) @MigrateCommand.option('revision', nargs='?', default="head", help="revision identifier") @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def show(directory=None, revision='head'): """Show the revision denoted by the given symbol.""" if alembic_version >= (0, 7, 0): config = current_app.extensions['migrate'].migrate.get_config( directory) command.show(config, revision) else: raise RuntimeError('Alembic 0.7.0 or greater is required') @MigrateCommand.option('-i', '--indicate-current', dest='indicate_current', action='store_true', default=False, help='Indicate current version (Alembic 0.9.9 or greater is required)') @MigrateCommand.option('-v', '--verbose', dest='verbose', action='store_true', default=False, help='Use more verbose output') @MigrateCommand.option('-r', '--rev-range', dest='rev_range', default=None, help='Specify a revision range; format is [start]:[end]') @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def history(directory=None, rev_range=None, verbose=False, indicate_current=False): """List changeset scripts in chronological order.""" config = current_app.extensions['migrate'].migrate.get_config(directory) if alembic_version >= (0, 9, 9): command.history(config, rev_range, verbose=verbose, indicate_current=indicate_current) elif alembic_version >= (0, 7, 0): command.history(config, rev_range, verbose=verbose) else: command.history(config, rev_range) @MigrateCommand.option('--resolve-dependencies', dest='resolve_dependencies', action='store_true', default=False, help='Treat dependency versions as down revisions') @MigrateCommand.option('-v', '--verbose', dest='verbose', action='store_true', default=False, help='Use more verbose output') @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def heads(directory=None, verbose=False, resolve_dependencies=False): """Show current available heads in the script directory""" if alembic_version >= (0, 7, 0): config = current_app.extensions['migrate'].migrate.get_config( directory) command.heads(config, verbose=verbose, resolve_dependencies=resolve_dependencies) else: raise RuntimeError('Alembic 0.7.0 or greater is required') @MigrateCommand.option('-v', '--verbose', dest='verbose', action='store_true', default=False, help='Use more verbose output') @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def branches(directory=None, verbose=False): """Show current branch points""" config = current_app.extensions['migrate'].migrate.get_config(directory) if alembic_version >= (0, 7, 0): command.branches(config, verbose=verbose) else: command.branches(config) @MigrateCommand.option('--head-only', dest='head_only', action='store_true', default=False, help='Deprecated. Use --verbose for additional output') @MigrateCommand.option('-v', '--verbose', dest='verbose', action='store_true', default=False, help='Use more verbose output') @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def current(directory=None, verbose=False, head_only=False): """Display the current revision for each database.""" config = current_app.extensions['migrate'].migrate.get_config(directory) if alembic_version >= (0, 7, 0): command.current(config, verbose=verbose, head_only=head_only) else: command.current(config) @MigrateCommand.option('--tag', dest='tag', default=None, help=("Arbitrary 'tag' name - can be used by custom " "env.py scripts")) @MigrateCommand.option('--sql', dest='sql', action='store_true', default=False, help=("Don't emit SQL to database - dump to standard " "output instead")) @MigrateCommand.option('revision', default=None, help="revision identifier") @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def stamp(directory=None, revision='head', sql=False, tag=None): """'stamp' the revision table with the given revision; don't run any migrations""" config = current_app.extensions['migrate'].migrate.get_config(directory) command.stamp(config, revision, sql=sql, tag=tag)
miguelgrinberg/Flask-Migrate
flask_migrate/__init__.py
upgrade
python
def upgrade(directory=None, revision='head', sql=False, tag=None, x_arg=None): config = current_app.extensions['migrate'].migrate.get_config(directory, x_arg=x_arg) command.upgrade(config, revision, sql=sql, tag=tag)
Upgrade to a later version
train
https://github.com/miguelgrinberg/Flask-Migrate/blob/65fbd978681bdf2eddf8940edd04ed7272a94480/flask_migrate/__init__.py#L276-L280
null
import argparse from functools import wraps import logging import os import sys from flask import current_app try: from flask_script import Manager except ImportError: Manager = None from alembic import __version__ as __alembic_version__ from alembic.config import Config as AlembicConfig from alembic import command from alembic.util import CommandError alembic_version = tuple([int(v) for v in __alembic_version__.split('.')[0:3]]) log = logging.getLogger() class _MigrateConfig(object): def __init__(self, migrate, db, **kwargs): self.migrate = migrate self.db = db self.directory = migrate.directory self.configure_args = kwargs @property def metadata(self): """ Backwards compatibility, in old releases app.extensions['migrate'] was set to db, and env.py accessed app.extensions['migrate'].metadata """ return self.db.metadata class Config(AlembicConfig): def get_template_directory(self): package_dir = os.path.abspath(os.path.dirname(__file__)) return os.path.join(package_dir, 'templates') class Migrate(object): def __init__(self, app=None, db=None, directory='migrations', **kwargs): self.configure_callbacks = [] self.db = db self.directory = directory self.alembic_ctx_kwargs = kwargs if app is not None and db is not None: self.init_app(app, db, directory) def init_app(self, app, db=None, directory=None, **kwargs): self.db = db or self.db self.directory = directory or self.directory self.alembic_ctx_kwargs.update(kwargs) if not hasattr(app, 'extensions'): app.extensions = {} app.extensions['migrate'] = _MigrateConfig(self, self.db, **self.alembic_ctx_kwargs) def configure(self, f): self.configure_callbacks.append(f) return f def call_configure_callbacks(self, config): for f in self.configure_callbacks: config = f(config) return config def get_config(self, directory=None, x_arg=None, opts=None): if directory is None: directory = self.directory config = Config(os.path.join(directory, 'alembic.ini')) config.set_main_option('script_location', directory) if config.cmd_opts is None: config.cmd_opts = argparse.Namespace() for opt in opts or []: setattr(config.cmd_opts, opt, True) if not hasattr(config.cmd_opts, 'x'): if x_arg is not None: setattr(config.cmd_opts, 'x', []) if isinstance(x_arg, list) or isinstance(x_arg, tuple): for x in x_arg: config.cmd_opts.x.append(x) else: config.cmd_opts.x.append(x_arg) else: setattr(config.cmd_opts, 'x', None) return self.call_configure_callbacks(config) def catch_errors(f): @wraps(f) def wrapped(*args, **kwargs): try: f(*args, **kwargs) except (CommandError, RuntimeError) as exc: log.error('Error: ' + str(exc)) sys.exit(1) return wrapped if Manager is not None: MigrateCommand = Manager(usage='Perform database migrations') else: class FakeCommand(object): def option(self, *args, **kwargs): def decorator(f): return f return decorator MigrateCommand = FakeCommand() @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @MigrateCommand.option('--multidb', dest='multidb', action='store_true', default=False, help=("Multiple databases migraton (default is " "False)")) @catch_errors def init(directory=None, multidb=False): """Creates a new migration repository""" if directory is None: directory = current_app.extensions['migrate'].directory config = Config() config.set_main_option('script_location', directory) config.config_file_name = os.path.join(directory, 'alembic.ini') config = current_app.extensions['migrate'].\ migrate.call_configure_callbacks(config) if multidb: command.init(config, directory, 'flask-multidb') else: command.init(config, directory, 'flask') @MigrateCommand.option('--rev-id', dest='rev_id', default=None, help=('Specify a hardcoded revision id instead of ' 'generating one')) @MigrateCommand.option('--version-path', dest='version_path', default=None, help=('Specify specific path from config for version ' 'file')) @MigrateCommand.option('--branch-label', dest='branch_label', default=None, help=('Specify a branch label to apply to the new ' 'revision')) @MigrateCommand.option('--splice', dest='splice', action='store_true', default=False, help=('Allow a non-head revision as the "head" to ' 'splice onto')) @MigrateCommand.option('--head', dest='head', default='head', help=('Specify head revision or <branchname>@head to ' 'base new revision on')) @MigrateCommand.option('--sql', dest='sql', action='store_true', default=False, help=("Don't emit SQL to database - dump to standard " "output instead")) @MigrateCommand.option('--autogenerate', dest='autogenerate', action='store_true', default=False, help=('Populate revision script with candidate ' 'migration operations, based on comparison of ' 'database to model')) @MigrateCommand.option('-m', '--message', dest='message', default=None, help='Revision message') @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def revision(directory=None, message=None, autogenerate=False, sql=False, head='head', splice=False, branch_label=None, version_path=None, rev_id=None): """Create a new revision file.""" config = current_app.extensions['migrate'].migrate.get_config(directory) if alembic_version >= (0, 7, 0): command.revision(config, message, autogenerate=autogenerate, sql=sql, head=head, splice=splice, branch_label=branch_label, version_path=version_path, rev_id=rev_id) else: command.revision(config, message, autogenerate=autogenerate, sql=sql) @MigrateCommand.option('--rev-id', dest='rev_id', default=None, help=('Specify a hardcoded revision id instead of ' 'generating one')) @MigrateCommand.option('--version-path', dest='version_path', default=None, help=('Specify specific path from config for version ' 'file')) @MigrateCommand.option('--branch-label', dest='branch_label', default=None, help=('Specify a branch label to apply to the new ' 'revision')) @MigrateCommand.option('--splice', dest='splice', action='store_true', default=False, help=('Allow a non-head revision as the "head" to ' 'splice onto')) @MigrateCommand.option('--head', dest='head', default='head', help=('Specify head revision or <branchname>@head to ' 'base new revision on')) @MigrateCommand.option('--sql', dest='sql', action='store_true', default=False, help=("Don't emit SQL to database - dump to standard " "output instead")) @MigrateCommand.option('-m', '--message', dest='message', default=None) @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @MigrateCommand.option('-x', '--x-arg', dest='x_arg', default=None, action='append', help=("Additional arguments consumed " "by custom env.py scripts")) @catch_errors def migrate(directory=None, message=None, sql=False, head='head', splice=False, branch_label=None, version_path=None, rev_id=None, x_arg=None): """Alias for 'revision --autogenerate'""" config = current_app.extensions['migrate'].migrate.get_config( directory, opts=['autogenerate'], x_arg=x_arg) if alembic_version >= (0, 7, 0): command.revision(config, message, autogenerate=True, sql=sql, head=head, splice=splice, branch_label=branch_label, version_path=version_path, rev_id=rev_id) else: command.revision(config, message, autogenerate=True, sql=sql) @MigrateCommand.option('revision', nargs='?', default='head', help="revision identifier") @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def edit(directory=None, revision='current'): """Edit current revision.""" if alembic_version >= (0, 8, 0): config = current_app.extensions['migrate'].migrate.get_config( directory) command.edit(config, revision) else: raise RuntimeError('Alembic 0.8.0 or greater is required') @MigrateCommand.option('--rev-id', dest='rev_id', default=None, help=('Specify a hardcoded revision id instead of ' 'generating one')) @MigrateCommand.option('--branch-label', dest='branch_label', default=None, help=('Specify a branch label to apply to the new ' 'revision')) @MigrateCommand.option('-m', '--message', dest='message', default=None) @MigrateCommand.option('revisions', nargs='+', help='one or more revisions, or "heads" for all heads') @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def merge(directory=None, revisions='', message=None, branch_label=None, rev_id=None): """Merge two revisions together. Creates a new migration file""" if alembic_version >= (0, 7, 0): config = current_app.extensions['migrate'].migrate.get_config( directory) command.merge(config, revisions, message=message, branch_label=branch_label, rev_id=rev_id) else: raise RuntimeError('Alembic 0.7.0 or greater is required') @MigrateCommand.option('--tag', dest='tag', default=None, help=("Arbitrary 'tag' name - can be used by custom " "env.py scripts")) @MigrateCommand.option('--sql', dest='sql', action='store_true', default=False, help=("Don't emit SQL to database - dump to standard " "output instead")) @MigrateCommand.option('revision', nargs='?', default='head', help="revision identifier") @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @MigrateCommand.option('-x', '--x-arg', dest='x_arg', default=None, action='append', help=("Additional arguments consumed " "by custom env.py scripts")) @catch_errors @MigrateCommand.option('--tag', dest='tag', default=None, help=("Arbitrary 'tag' name - can be used by custom " "env.py scripts")) @MigrateCommand.option('--sql', dest='sql', action='store_true', default=False, help=("Don't emit SQL to database - dump to standard " "output instead")) @MigrateCommand.option('revision', nargs='?', default="-1", help="revision identifier") @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @MigrateCommand.option('-x', '--x-arg', dest='x_arg', default=None, action='append', help=("Additional arguments consumed " "by custom env.py scripts")) @catch_errors def downgrade(directory=None, revision='-1', sql=False, tag=None, x_arg=None): """Revert to a previous version""" config = current_app.extensions['migrate'].migrate.get_config(directory, x_arg=x_arg) if sql and revision == '-1': revision = 'head:-1' command.downgrade(config, revision, sql=sql, tag=tag) @MigrateCommand.option('revision', nargs='?', default="head", help="revision identifier") @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def show(directory=None, revision='head'): """Show the revision denoted by the given symbol.""" if alembic_version >= (0, 7, 0): config = current_app.extensions['migrate'].migrate.get_config( directory) command.show(config, revision) else: raise RuntimeError('Alembic 0.7.0 or greater is required') @MigrateCommand.option('-i', '--indicate-current', dest='indicate_current', action='store_true', default=False, help='Indicate current version (Alembic 0.9.9 or greater is required)') @MigrateCommand.option('-v', '--verbose', dest='verbose', action='store_true', default=False, help='Use more verbose output') @MigrateCommand.option('-r', '--rev-range', dest='rev_range', default=None, help='Specify a revision range; format is [start]:[end]') @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def history(directory=None, rev_range=None, verbose=False, indicate_current=False): """List changeset scripts in chronological order.""" config = current_app.extensions['migrate'].migrate.get_config(directory) if alembic_version >= (0, 9, 9): command.history(config, rev_range, verbose=verbose, indicate_current=indicate_current) elif alembic_version >= (0, 7, 0): command.history(config, rev_range, verbose=verbose) else: command.history(config, rev_range) @MigrateCommand.option('--resolve-dependencies', dest='resolve_dependencies', action='store_true', default=False, help='Treat dependency versions as down revisions') @MigrateCommand.option('-v', '--verbose', dest='verbose', action='store_true', default=False, help='Use more verbose output') @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def heads(directory=None, verbose=False, resolve_dependencies=False): """Show current available heads in the script directory""" if alembic_version >= (0, 7, 0): config = current_app.extensions['migrate'].migrate.get_config( directory) command.heads(config, verbose=verbose, resolve_dependencies=resolve_dependencies) else: raise RuntimeError('Alembic 0.7.0 or greater is required') @MigrateCommand.option('-v', '--verbose', dest='verbose', action='store_true', default=False, help='Use more verbose output') @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def branches(directory=None, verbose=False): """Show current branch points""" config = current_app.extensions['migrate'].migrate.get_config(directory) if alembic_version >= (0, 7, 0): command.branches(config, verbose=verbose) else: command.branches(config) @MigrateCommand.option('--head-only', dest='head_only', action='store_true', default=False, help='Deprecated. Use --verbose for additional output') @MigrateCommand.option('-v', '--verbose', dest='verbose', action='store_true', default=False, help='Use more verbose output') @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def current(directory=None, verbose=False, head_only=False): """Display the current revision for each database.""" config = current_app.extensions['migrate'].migrate.get_config(directory) if alembic_version >= (0, 7, 0): command.current(config, verbose=verbose, head_only=head_only) else: command.current(config) @MigrateCommand.option('--tag', dest='tag', default=None, help=("Arbitrary 'tag' name - can be used by custom " "env.py scripts")) @MigrateCommand.option('--sql', dest='sql', action='store_true', default=False, help=("Don't emit SQL to database - dump to standard " "output instead")) @MigrateCommand.option('revision', default=None, help="revision identifier") @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def stamp(directory=None, revision='head', sql=False, tag=None): """'stamp' the revision table with the given revision; don't run any migrations""" config = current_app.extensions['migrate'].migrate.get_config(directory) command.stamp(config, revision, sql=sql, tag=tag)
miguelgrinberg/Flask-Migrate
flask_migrate/__init__.py
history
python
def history(directory=None, rev_range=None, verbose=False, indicate_current=False): config = current_app.extensions['migrate'].migrate.get_config(directory) if alembic_version >= (0, 9, 9): command.history(config, rev_range, verbose=verbose, indicate_current=indicate_current) elif alembic_version >= (0, 7, 0): command.history(config, rev_range, verbose=verbose) else: command.history(config, rev_range)
List changeset scripts in chronological order.
train
https://github.com/miguelgrinberg/Flask-Migrate/blob/65fbd978681bdf2eddf8940edd04ed7272a94480/flask_migrate/__init__.py#L333-L341
null
import argparse from functools import wraps import logging import os import sys from flask import current_app try: from flask_script import Manager except ImportError: Manager = None from alembic import __version__ as __alembic_version__ from alembic.config import Config as AlembicConfig from alembic import command from alembic.util import CommandError alembic_version = tuple([int(v) for v in __alembic_version__.split('.')[0:3]]) log = logging.getLogger() class _MigrateConfig(object): def __init__(self, migrate, db, **kwargs): self.migrate = migrate self.db = db self.directory = migrate.directory self.configure_args = kwargs @property def metadata(self): """ Backwards compatibility, in old releases app.extensions['migrate'] was set to db, and env.py accessed app.extensions['migrate'].metadata """ return self.db.metadata class Config(AlembicConfig): def get_template_directory(self): package_dir = os.path.abspath(os.path.dirname(__file__)) return os.path.join(package_dir, 'templates') class Migrate(object): def __init__(self, app=None, db=None, directory='migrations', **kwargs): self.configure_callbacks = [] self.db = db self.directory = directory self.alembic_ctx_kwargs = kwargs if app is not None and db is not None: self.init_app(app, db, directory) def init_app(self, app, db=None, directory=None, **kwargs): self.db = db or self.db self.directory = directory or self.directory self.alembic_ctx_kwargs.update(kwargs) if not hasattr(app, 'extensions'): app.extensions = {} app.extensions['migrate'] = _MigrateConfig(self, self.db, **self.alembic_ctx_kwargs) def configure(self, f): self.configure_callbacks.append(f) return f def call_configure_callbacks(self, config): for f in self.configure_callbacks: config = f(config) return config def get_config(self, directory=None, x_arg=None, opts=None): if directory is None: directory = self.directory config = Config(os.path.join(directory, 'alembic.ini')) config.set_main_option('script_location', directory) if config.cmd_opts is None: config.cmd_opts = argparse.Namespace() for opt in opts or []: setattr(config.cmd_opts, opt, True) if not hasattr(config.cmd_opts, 'x'): if x_arg is not None: setattr(config.cmd_opts, 'x', []) if isinstance(x_arg, list) or isinstance(x_arg, tuple): for x in x_arg: config.cmd_opts.x.append(x) else: config.cmd_opts.x.append(x_arg) else: setattr(config.cmd_opts, 'x', None) return self.call_configure_callbacks(config) def catch_errors(f): @wraps(f) def wrapped(*args, **kwargs): try: f(*args, **kwargs) except (CommandError, RuntimeError) as exc: log.error('Error: ' + str(exc)) sys.exit(1) return wrapped if Manager is not None: MigrateCommand = Manager(usage='Perform database migrations') else: class FakeCommand(object): def option(self, *args, **kwargs): def decorator(f): return f return decorator MigrateCommand = FakeCommand() @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @MigrateCommand.option('--multidb', dest='multidb', action='store_true', default=False, help=("Multiple databases migraton (default is " "False)")) @catch_errors def init(directory=None, multidb=False): """Creates a new migration repository""" if directory is None: directory = current_app.extensions['migrate'].directory config = Config() config.set_main_option('script_location', directory) config.config_file_name = os.path.join(directory, 'alembic.ini') config = current_app.extensions['migrate'].\ migrate.call_configure_callbacks(config) if multidb: command.init(config, directory, 'flask-multidb') else: command.init(config, directory, 'flask') @MigrateCommand.option('--rev-id', dest='rev_id', default=None, help=('Specify a hardcoded revision id instead of ' 'generating one')) @MigrateCommand.option('--version-path', dest='version_path', default=None, help=('Specify specific path from config for version ' 'file')) @MigrateCommand.option('--branch-label', dest='branch_label', default=None, help=('Specify a branch label to apply to the new ' 'revision')) @MigrateCommand.option('--splice', dest='splice', action='store_true', default=False, help=('Allow a non-head revision as the "head" to ' 'splice onto')) @MigrateCommand.option('--head', dest='head', default='head', help=('Specify head revision or <branchname>@head to ' 'base new revision on')) @MigrateCommand.option('--sql', dest='sql', action='store_true', default=False, help=("Don't emit SQL to database - dump to standard " "output instead")) @MigrateCommand.option('--autogenerate', dest='autogenerate', action='store_true', default=False, help=('Populate revision script with candidate ' 'migration operations, based on comparison of ' 'database to model')) @MigrateCommand.option('-m', '--message', dest='message', default=None, help='Revision message') @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def revision(directory=None, message=None, autogenerate=False, sql=False, head='head', splice=False, branch_label=None, version_path=None, rev_id=None): """Create a new revision file.""" config = current_app.extensions['migrate'].migrate.get_config(directory) if alembic_version >= (0, 7, 0): command.revision(config, message, autogenerate=autogenerate, sql=sql, head=head, splice=splice, branch_label=branch_label, version_path=version_path, rev_id=rev_id) else: command.revision(config, message, autogenerate=autogenerate, sql=sql) @MigrateCommand.option('--rev-id', dest='rev_id', default=None, help=('Specify a hardcoded revision id instead of ' 'generating one')) @MigrateCommand.option('--version-path', dest='version_path', default=None, help=('Specify specific path from config for version ' 'file')) @MigrateCommand.option('--branch-label', dest='branch_label', default=None, help=('Specify a branch label to apply to the new ' 'revision')) @MigrateCommand.option('--splice', dest='splice', action='store_true', default=False, help=('Allow a non-head revision as the "head" to ' 'splice onto')) @MigrateCommand.option('--head', dest='head', default='head', help=('Specify head revision or <branchname>@head to ' 'base new revision on')) @MigrateCommand.option('--sql', dest='sql', action='store_true', default=False, help=("Don't emit SQL to database - dump to standard " "output instead")) @MigrateCommand.option('-m', '--message', dest='message', default=None) @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @MigrateCommand.option('-x', '--x-arg', dest='x_arg', default=None, action='append', help=("Additional arguments consumed " "by custom env.py scripts")) @catch_errors def migrate(directory=None, message=None, sql=False, head='head', splice=False, branch_label=None, version_path=None, rev_id=None, x_arg=None): """Alias for 'revision --autogenerate'""" config = current_app.extensions['migrate'].migrate.get_config( directory, opts=['autogenerate'], x_arg=x_arg) if alembic_version >= (0, 7, 0): command.revision(config, message, autogenerate=True, sql=sql, head=head, splice=splice, branch_label=branch_label, version_path=version_path, rev_id=rev_id) else: command.revision(config, message, autogenerate=True, sql=sql) @MigrateCommand.option('revision', nargs='?', default='head', help="revision identifier") @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def edit(directory=None, revision='current'): """Edit current revision.""" if alembic_version >= (0, 8, 0): config = current_app.extensions['migrate'].migrate.get_config( directory) command.edit(config, revision) else: raise RuntimeError('Alembic 0.8.0 or greater is required') @MigrateCommand.option('--rev-id', dest='rev_id', default=None, help=('Specify a hardcoded revision id instead of ' 'generating one')) @MigrateCommand.option('--branch-label', dest='branch_label', default=None, help=('Specify a branch label to apply to the new ' 'revision')) @MigrateCommand.option('-m', '--message', dest='message', default=None) @MigrateCommand.option('revisions', nargs='+', help='one or more revisions, or "heads" for all heads') @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def merge(directory=None, revisions='', message=None, branch_label=None, rev_id=None): """Merge two revisions together. Creates a new migration file""" if alembic_version >= (0, 7, 0): config = current_app.extensions['migrate'].migrate.get_config( directory) command.merge(config, revisions, message=message, branch_label=branch_label, rev_id=rev_id) else: raise RuntimeError('Alembic 0.7.0 or greater is required') @MigrateCommand.option('--tag', dest='tag', default=None, help=("Arbitrary 'tag' name - can be used by custom " "env.py scripts")) @MigrateCommand.option('--sql', dest='sql', action='store_true', default=False, help=("Don't emit SQL to database - dump to standard " "output instead")) @MigrateCommand.option('revision', nargs='?', default='head', help="revision identifier") @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @MigrateCommand.option('-x', '--x-arg', dest='x_arg', default=None, action='append', help=("Additional arguments consumed " "by custom env.py scripts")) @catch_errors def upgrade(directory=None, revision='head', sql=False, tag=None, x_arg=None): """Upgrade to a later version""" config = current_app.extensions['migrate'].migrate.get_config(directory, x_arg=x_arg) command.upgrade(config, revision, sql=sql, tag=tag) @MigrateCommand.option('--tag', dest='tag', default=None, help=("Arbitrary 'tag' name - can be used by custom " "env.py scripts")) @MigrateCommand.option('--sql', dest='sql', action='store_true', default=False, help=("Don't emit SQL to database - dump to standard " "output instead")) @MigrateCommand.option('revision', nargs='?', default="-1", help="revision identifier") @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @MigrateCommand.option('-x', '--x-arg', dest='x_arg', default=None, action='append', help=("Additional arguments consumed " "by custom env.py scripts")) @catch_errors def downgrade(directory=None, revision='-1', sql=False, tag=None, x_arg=None): """Revert to a previous version""" config = current_app.extensions['migrate'].migrate.get_config(directory, x_arg=x_arg) if sql and revision == '-1': revision = 'head:-1' command.downgrade(config, revision, sql=sql, tag=tag) @MigrateCommand.option('revision', nargs='?', default="head", help="revision identifier") @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def show(directory=None, revision='head'): """Show the revision denoted by the given symbol.""" if alembic_version >= (0, 7, 0): config = current_app.extensions['migrate'].migrate.get_config( directory) command.show(config, revision) else: raise RuntimeError('Alembic 0.7.0 or greater is required') @MigrateCommand.option('-i', '--indicate-current', dest='indicate_current', action='store_true', default=False, help='Indicate current version (Alembic 0.9.9 or greater is required)') @MigrateCommand.option('-v', '--verbose', dest='verbose', action='store_true', default=False, help='Use more verbose output') @MigrateCommand.option('-r', '--rev-range', dest='rev_range', default=None, help='Specify a revision range; format is [start]:[end]') @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors @MigrateCommand.option('--resolve-dependencies', dest='resolve_dependencies', action='store_true', default=False, help='Treat dependency versions as down revisions') @MigrateCommand.option('-v', '--verbose', dest='verbose', action='store_true', default=False, help='Use more verbose output') @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def heads(directory=None, verbose=False, resolve_dependencies=False): """Show current available heads in the script directory""" if alembic_version >= (0, 7, 0): config = current_app.extensions['migrate'].migrate.get_config( directory) command.heads(config, verbose=verbose, resolve_dependencies=resolve_dependencies) else: raise RuntimeError('Alembic 0.7.0 or greater is required') @MigrateCommand.option('-v', '--verbose', dest='verbose', action='store_true', default=False, help='Use more verbose output') @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def branches(directory=None, verbose=False): """Show current branch points""" config = current_app.extensions['migrate'].migrate.get_config(directory) if alembic_version >= (0, 7, 0): command.branches(config, verbose=verbose) else: command.branches(config) @MigrateCommand.option('--head-only', dest='head_only', action='store_true', default=False, help='Deprecated. Use --verbose for additional output') @MigrateCommand.option('-v', '--verbose', dest='verbose', action='store_true', default=False, help='Use more verbose output') @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def current(directory=None, verbose=False, head_only=False): """Display the current revision for each database.""" config = current_app.extensions['migrate'].migrate.get_config(directory) if alembic_version >= (0, 7, 0): command.current(config, verbose=verbose, head_only=head_only) else: command.current(config) @MigrateCommand.option('--tag', dest='tag', default=None, help=("Arbitrary 'tag' name - can be used by custom " "env.py scripts")) @MigrateCommand.option('--sql', dest='sql', action='store_true', default=False, help=("Don't emit SQL to database - dump to standard " "output instead")) @MigrateCommand.option('revision', default=None, help="revision identifier") @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def stamp(directory=None, revision='head', sql=False, tag=None): """'stamp' the revision table with the given revision; don't run any migrations""" config = current_app.extensions['migrate'].migrate.get_config(directory) command.stamp(config, revision, sql=sql, tag=tag)
miguelgrinberg/Flask-Migrate
flask_migrate/__init__.py
heads
python
def heads(directory=None, verbose=False, resolve_dependencies=False): if alembic_version >= (0, 7, 0): config = current_app.extensions['migrate'].migrate.get_config( directory) command.heads(config, verbose=verbose, resolve_dependencies=resolve_dependencies) else: raise RuntimeError('Alembic 0.7.0 or greater is required')
Show current available heads in the script directory
train
https://github.com/miguelgrinberg/Flask-Migrate/blob/65fbd978681bdf2eddf8940edd04ed7272a94480/flask_migrate/__init__.py#L353-L361
null
import argparse from functools import wraps import logging import os import sys from flask import current_app try: from flask_script import Manager except ImportError: Manager = None from alembic import __version__ as __alembic_version__ from alembic.config import Config as AlembicConfig from alembic import command from alembic.util import CommandError alembic_version = tuple([int(v) for v in __alembic_version__.split('.')[0:3]]) log = logging.getLogger() class _MigrateConfig(object): def __init__(self, migrate, db, **kwargs): self.migrate = migrate self.db = db self.directory = migrate.directory self.configure_args = kwargs @property def metadata(self): """ Backwards compatibility, in old releases app.extensions['migrate'] was set to db, and env.py accessed app.extensions['migrate'].metadata """ return self.db.metadata class Config(AlembicConfig): def get_template_directory(self): package_dir = os.path.abspath(os.path.dirname(__file__)) return os.path.join(package_dir, 'templates') class Migrate(object): def __init__(self, app=None, db=None, directory='migrations', **kwargs): self.configure_callbacks = [] self.db = db self.directory = directory self.alembic_ctx_kwargs = kwargs if app is not None and db is not None: self.init_app(app, db, directory) def init_app(self, app, db=None, directory=None, **kwargs): self.db = db or self.db self.directory = directory or self.directory self.alembic_ctx_kwargs.update(kwargs) if not hasattr(app, 'extensions'): app.extensions = {} app.extensions['migrate'] = _MigrateConfig(self, self.db, **self.alembic_ctx_kwargs) def configure(self, f): self.configure_callbacks.append(f) return f def call_configure_callbacks(self, config): for f in self.configure_callbacks: config = f(config) return config def get_config(self, directory=None, x_arg=None, opts=None): if directory is None: directory = self.directory config = Config(os.path.join(directory, 'alembic.ini')) config.set_main_option('script_location', directory) if config.cmd_opts is None: config.cmd_opts = argparse.Namespace() for opt in opts or []: setattr(config.cmd_opts, opt, True) if not hasattr(config.cmd_opts, 'x'): if x_arg is not None: setattr(config.cmd_opts, 'x', []) if isinstance(x_arg, list) or isinstance(x_arg, tuple): for x in x_arg: config.cmd_opts.x.append(x) else: config.cmd_opts.x.append(x_arg) else: setattr(config.cmd_opts, 'x', None) return self.call_configure_callbacks(config) def catch_errors(f): @wraps(f) def wrapped(*args, **kwargs): try: f(*args, **kwargs) except (CommandError, RuntimeError) as exc: log.error('Error: ' + str(exc)) sys.exit(1) return wrapped if Manager is not None: MigrateCommand = Manager(usage='Perform database migrations') else: class FakeCommand(object): def option(self, *args, **kwargs): def decorator(f): return f return decorator MigrateCommand = FakeCommand() @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @MigrateCommand.option('--multidb', dest='multidb', action='store_true', default=False, help=("Multiple databases migraton (default is " "False)")) @catch_errors def init(directory=None, multidb=False): """Creates a new migration repository""" if directory is None: directory = current_app.extensions['migrate'].directory config = Config() config.set_main_option('script_location', directory) config.config_file_name = os.path.join(directory, 'alembic.ini') config = current_app.extensions['migrate'].\ migrate.call_configure_callbacks(config) if multidb: command.init(config, directory, 'flask-multidb') else: command.init(config, directory, 'flask') @MigrateCommand.option('--rev-id', dest='rev_id', default=None, help=('Specify a hardcoded revision id instead of ' 'generating one')) @MigrateCommand.option('--version-path', dest='version_path', default=None, help=('Specify specific path from config for version ' 'file')) @MigrateCommand.option('--branch-label', dest='branch_label', default=None, help=('Specify a branch label to apply to the new ' 'revision')) @MigrateCommand.option('--splice', dest='splice', action='store_true', default=False, help=('Allow a non-head revision as the "head" to ' 'splice onto')) @MigrateCommand.option('--head', dest='head', default='head', help=('Specify head revision or <branchname>@head to ' 'base new revision on')) @MigrateCommand.option('--sql', dest='sql', action='store_true', default=False, help=("Don't emit SQL to database - dump to standard " "output instead")) @MigrateCommand.option('--autogenerate', dest='autogenerate', action='store_true', default=False, help=('Populate revision script with candidate ' 'migration operations, based on comparison of ' 'database to model')) @MigrateCommand.option('-m', '--message', dest='message', default=None, help='Revision message') @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def revision(directory=None, message=None, autogenerate=False, sql=False, head='head', splice=False, branch_label=None, version_path=None, rev_id=None): """Create a new revision file.""" config = current_app.extensions['migrate'].migrate.get_config(directory) if alembic_version >= (0, 7, 0): command.revision(config, message, autogenerate=autogenerate, sql=sql, head=head, splice=splice, branch_label=branch_label, version_path=version_path, rev_id=rev_id) else: command.revision(config, message, autogenerate=autogenerate, sql=sql) @MigrateCommand.option('--rev-id', dest='rev_id', default=None, help=('Specify a hardcoded revision id instead of ' 'generating one')) @MigrateCommand.option('--version-path', dest='version_path', default=None, help=('Specify specific path from config for version ' 'file')) @MigrateCommand.option('--branch-label', dest='branch_label', default=None, help=('Specify a branch label to apply to the new ' 'revision')) @MigrateCommand.option('--splice', dest='splice', action='store_true', default=False, help=('Allow a non-head revision as the "head" to ' 'splice onto')) @MigrateCommand.option('--head', dest='head', default='head', help=('Specify head revision or <branchname>@head to ' 'base new revision on')) @MigrateCommand.option('--sql', dest='sql', action='store_true', default=False, help=("Don't emit SQL to database - dump to standard " "output instead")) @MigrateCommand.option('-m', '--message', dest='message', default=None) @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @MigrateCommand.option('-x', '--x-arg', dest='x_arg', default=None, action='append', help=("Additional arguments consumed " "by custom env.py scripts")) @catch_errors def migrate(directory=None, message=None, sql=False, head='head', splice=False, branch_label=None, version_path=None, rev_id=None, x_arg=None): """Alias for 'revision --autogenerate'""" config = current_app.extensions['migrate'].migrate.get_config( directory, opts=['autogenerate'], x_arg=x_arg) if alembic_version >= (0, 7, 0): command.revision(config, message, autogenerate=True, sql=sql, head=head, splice=splice, branch_label=branch_label, version_path=version_path, rev_id=rev_id) else: command.revision(config, message, autogenerate=True, sql=sql) @MigrateCommand.option('revision', nargs='?', default='head', help="revision identifier") @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def edit(directory=None, revision='current'): """Edit current revision.""" if alembic_version >= (0, 8, 0): config = current_app.extensions['migrate'].migrate.get_config( directory) command.edit(config, revision) else: raise RuntimeError('Alembic 0.8.0 or greater is required') @MigrateCommand.option('--rev-id', dest='rev_id', default=None, help=('Specify a hardcoded revision id instead of ' 'generating one')) @MigrateCommand.option('--branch-label', dest='branch_label', default=None, help=('Specify a branch label to apply to the new ' 'revision')) @MigrateCommand.option('-m', '--message', dest='message', default=None) @MigrateCommand.option('revisions', nargs='+', help='one or more revisions, or "heads" for all heads') @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def merge(directory=None, revisions='', message=None, branch_label=None, rev_id=None): """Merge two revisions together. Creates a new migration file""" if alembic_version >= (0, 7, 0): config = current_app.extensions['migrate'].migrate.get_config( directory) command.merge(config, revisions, message=message, branch_label=branch_label, rev_id=rev_id) else: raise RuntimeError('Alembic 0.7.0 or greater is required') @MigrateCommand.option('--tag', dest='tag', default=None, help=("Arbitrary 'tag' name - can be used by custom " "env.py scripts")) @MigrateCommand.option('--sql', dest='sql', action='store_true', default=False, help=("Don't emit SQL to database - dump to standard " "output instead")) @MigrateCommand.option('revision', nargs='?', default='head', help="revision identifier") @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @MigrateCommand.option('-x', '--x-arg', dest='x_arg', default=None, action='append', help=("Additional arguments consumed " "by custom env.py scripts")) @catch_errors def upgrade(directory=None, revision='head', sql=False, tag=None, x_arg=None): """Upgrade to a later version""" config = current_app.extensions['migrate'].migrate.get_config(directory, x_arg=x_arg) command.upgrade(config, revision, sql=sql, tag=tag) @MigrateCommand.option('--tag', dest='tag', default=None, help=("Arbitrary 'tag' name - can be used by custom " "env.py scripts")) @MigrateCommand.option('--sql', dest='sql', action='store_true', default=False, help=("Don't emit SQL to database - dump to standard " "output instead")) @MigrateCommand.option('revision', nargs='?', default="-1", help="revision identifier") @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @MigrateCommand.option('-x', '--x-arg', dest='x_arg', default=None, action='append', help=("Additional arguments consumed " "by custom env.py scripts")) @catch_errors def downgrade(directory=None, revision='-1', sql=False, tag=None, x_arg=None): """Revert to a previous version""" config = current_app.extensions['migrate'].migrate.get_config(directory, x_arg=x_arg) if sql and revision == '-1': revision = 'head:-1' command.downgrade(config, revision, sql=sql, tag=tag) @MigrateCommand.option('revision', nargs='?', default="head", help="revision identifier") @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def show(directory=None, revision='head'): """Show the revision denoted by the given symbol.""" if alembic_version >= (0, 7, 0): config = current_app.extensions['migrate'].migrate.get_config( directory) command.show(config, revision) else: raise RuntimeError('Alembic 0.7.0 or greater is required') @MigrateCommand.option('-i', '--indicate-current', dest='indicate_current', action='store_true', default=False, help='Indicate current version (Alembic 0.9.9 or greater is required)') @MigrateCommand.option('-v', '--verbose', dest='verbose', action='store_true', default=False, help='Use more verbose output') @MigrateCommand.option('-r', '--rev-range', dest='rev_range', default=None, help='Specify a revision range; format is [start]:[end]') @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def history(directory=None, rev_range=None, verbose=False, indicate_current=False): """List changeset scripts in chronological order.""" config = current_app.extensions['migrate'].migrate.get_config(directory) if alembic_version >= (0, 9, 9): command.history(config, rev_range, verbose=verbose, indicate_current=indicate_current) elif alembic_version >= (0, 7, 0): command.history(config, rev_range, verbose=verbose) else: command.history(config, rev_range) @MigrateCommand.option('--resolve-dependencies', dest='resolve_dependencies', action='store_true', default=False, help='Treat dependency versions as down revisions') @MigrateCommand.option('-v', '--verbose', dest='verbose', action='store_true', default=False, help='Use more verbose output') @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors @MigrateCommand.option('-v', '--verbose', dest='verbose', action='store_true', default=False, help='Use more verbose output') @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def branches(directory=None, verbose=False): """Show current branch points""" config = current_app.extensions['migrate'].migrate.get_config(directory) if alembic_version >= (0, 7, 0): command.branches(config, verbose=verbose) else: command.branches(config) @MigrateCommand.option('--head-only', dest='head_only', action='store_true', default=False, help='Deprecated. Use --verbose for additional output') @MigrateCommand.option('-v', '--verbose', dest='verbose', action='store_true', default=False, help='Use more verbose output') @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def current(directory=None, verbose=False, head_only=False): """Display the current revision for each database.""" config = current_app.extensions['migrate'].migrate.get_config(directory) if alembic_version >= (0, 7, 0): command.current(config, verbose=verbose, head_only=head_only) else: command.current(config) @MigrateCommand.option('--tag', dest='tag', default=None, help=("Arbitrary 'tag' name - can be used by custom " "env.py scripts")) @MigrateCommand.option('--sql', dest='sql', action='store_true', default=False, help=("Don't emit SQL to database - dump to standard " "output instead")) @MigrateCommand.option('revision', default=None, help="revision identifier") @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def stamp(directory=None, revision='head', sql=False, tag=None): """'stamp' the revision table with the given revision; don't run any migrations""" config = current_app.extensions['migrate'].migrate.get_config(directory) command.stamp(config, revision, sql=sql, tag=tag)
miguelgrinberg/Flask-Migrate
flask_migrate/__init__.py
branches
python
def branches(directory=None, verbose=False): config = current_app.extensions['migrate'].migrate.get_config(directory) if alembic_version >= (0, 7, 0): command.branches(config, verbose=verbose) else: command.branches(config)
Show current branch points
train
https://github.com/miguelgrinberg/Flask-Migrate/blob/65fbd978681bdf2eddf8940edd04ed7272a94480/flask_migrate/__init__.py#L370-L376
null
import argparse from functools import wraps import logging import os import sys from flask import current_app try: from flask_script import Manager except ImportError: Manager = None from alembic import __version__ as __alembic_version__ from alembic.config import Config as AlembicConfig from alembic import command from alembic.util import CommandError alembic_version = tuple([int(v) for v in __alembic_version__.split('.')[0:3]]) log = logging.getLogger() class _MigrateConfig(object): def __init__(self, migrate, db, **kwargs): self.migrate = migrate self.db = db self.directory = migrate.directory self.configure_args = kwargs @property def metadata(self): """ Backwards compatibility, in old releases app.extensions['migrate'] was set to db, and env.py accessed app.extensions['migrate'].metadata """ return self.db.metadata class Config(AlembicConfig): def get_template_directory(self): package_dir = os.path.abspath(os.path.dirname(__file__)) return os.path.join(package_dir, 'templates') class Migrate(object): def __init__(self, app=None, db=None, directory='migrations', **kwargs): self.configure_callbacks = [] self.db = db self.directory = directory self.alembic_ctx_kwargs = kwargs if app is not None and db is not None: self.init_app(app, db, directory) def init_app(self, app, db=None, directory=None, **kwargs): self.db = db or self.db self.directory = directory or self.directory self.alembic_ctx_kwargs.update(kwargs) if not hasattr(app, 'extensions'): app.extensions = {} app.extensions['migrate'] = _MigrateConfig(self, self.db, **self.alembic_ctx_kwargs) def configure(self, f): self.configure_callbacks.append(f) return f def call_configure_callbacks(self, config): for f in self.configure_callbacks: config = f(config) return config def get_config(self, directory=None, x_arg=None, opts=None): if directory is None: directory = self.directory config = Config(os.path.join(directory, 'alembic.ini')) config.set_main_option('script_location', directory) if config.cmd_opts is None: config.cmd_opts = argparse.Namespace() for opt in opts or []: setattr(config.cmd_opts, opt, True) if not hasattr(config.cmd_opts, 'x'): if x_arg is not None: setattr(config.cmd_opts, 'x', []) if isinstance(x_arg, list) or isinstance(x_arg, tuple): for x in x_arg: config.cmd_opts.x.append(x) else: config.cmd_opts.x.append(x_arg) else: setattr(config.cmd_opts, 'x', None) return self.call_configure_callbacks(config) def catch_errors(f): @wraps(f) def wrapped(*args, **kwargs): try: f(*args, **kwargs) except (CommandError, RuntimeError) as exc: log.error('Error: ' + str(exc)) sys.exit(1) return wrapped if Manager is not None: MigrateCommand = Manager(usage='Perform database migrations') else: class FakeCommand(object): def option(self, *args, **kwargs): def decorator(f): return f return decorator MigrateCommand = FakeCommand() @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @MigrateCommand.option('--multidb', dest='multidb', action='store_true', default=False, help=("Multiple databases migraton (default is " "False)")) @catch_errors def init(directory=None, multidb=False): """Creates a new migration repository""" if directory is None: directory = current_app.extensions['migrate'].directory config = Config() config.set_main_option('script_location', directory) config.config_file_name = os.path.join(directory, 'alembic.ini') config = current_app.extensions['migrate'].\ migrate.call_configure_callbacks(config) if multidb: command.init(config, directory, 'flask-multidb') else: command.init(config, directory, 'flask') @MigrateCommand.option('--rev-id', dest='rev_id', default=None, help=('Specify a hardcoded revision id instead of ' 'generating one')) @MigrateCommand.option('--version-path', dest='version_path', default=None, help=('Specify specific path from config for version ' 'file')) @MigrateCommand.option('--branch-label', dest='branch_label', default=None, help=('Specify a branch label to apply to the new ' 'revision')) @MigrateCommand.option('--splice', dest='splice', action='store_true', default=False, help=('Allow a non-head revision as the "head" to ' 'splice onto')) @MigrateCommand.option('--head', dest='head', default='head', help=('Specify head revision or <branchname>@head to ' 'base new revision on')) @MigrateCommand.option('--sql', dest='sql', action='store_true', default=False, help=("Don't emit SQL to database - dump to standard " "output instead")) @MigrateCommand.option('--autogenerate', dest='autogenerate', action='store_true', default=False, help=('Populate revision script with candidate ' 'migration operations, based on comparison of ' 'database to model')) @MigrateCommand.option('-m', '--message', dest='message', default=None, help='Revision message') @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def revision(directory=None, message=None, autogenerate=False, sql=False, head='head', splice=False, branch_label=None, version_path=None, rev_id=None): """Create a new revision file.""" config = current_app.extensions['migrate'].migrate.get_config(directory) if alembic_version >= (0, 7, 0): command.revision(config, message, autogenerate=autogenerate, sql=sql, head=head, splice=splice, branch_label=branch_label, version_path=version_path, rev_id=rev_id) else: command.revision(config, message, autogenerate=autogenerate, sql=sql) @MigrateCommand.option('--rev-id', dest='rev_id', default=None, help=('Specify a hardcoded revision id instead of ' 'generating one')) @MigrateCommand.option('--version-path', dest='version_path', default=None, help=('Specify specific path from config for version ' 'file')) @MigrateCommand.option('--branch-label', dest='branch_label', default=None, help=('Specify a branch label to apply to the new ' 'revision')) @MigrateCommand.option('--splice', dest='splice', action='store_true', default=False, help=('Allow a non-head revision as the "head" to ' 'splice onto')) @MigrateCommand.option('--head', dest='head', default='head', help=('Specify head revision or <branchname>@head to ' 'base new revision on')) @MigrateCommand.option('--sql', dest='sql', action='store_true', default=False, help=("Don't emit SQL to database - dump to standard " "output instead")) @MigrateCommand.option('-m', '--message', dest='message', default=None) @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @MigrateCommand.option('-x', '--x-arg', dest='x_arg', default=None, action='append', help=("Additional arguments consumed " "by custom env.py scripts")) @catch_errors def migrate(directory=None, message=None, sql=False, head='head', splice=False, branch_label=None, version_path=None, rev_id=None, x_arg=None): """Alias for 'revision --autogenerate'""" config = current_app.extensions['migrate'].migrate.get_config( directory, opts=['autogenerate'], x_arg=x_arg) if alembic_version >= (0, 7, 0): command.revision(config, message, autogenerate=True, sql=sql, head=head, splice=splice, branch_label=branch_label, version_path=version_path, rev_id=rev_id) else: command.revision(config, message, autogenerate=True, sql=sql) @MigrateCommand.option('revision', nargs='?', default='head', help="revision identifier") @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def edit(directory=None, revision='current'): """Edit current revision.""" if alembic_version >= (0, 8, 0): config = current_app.extensions['migrate'].migrate.get_config( directory) command.edit(config, revision) else: raise RuntimeError('Alembic 0.8.0 or greater is required') @MigrateCommand.option('--rev-id', dest='rev_id', default=None, help=('Specify a hardcoded revision id instead of ' 'generating one')) @MigrateCommand.option('--branch-label', dest='branch_label', default=None, help=('Specify a branch label to apply to the new ' 'revision')) @MigrateCommand.option('-m', '--message', dest='message', default=None) @MigrateCommand.option('revisions', nargs='+', help='one or more revisions, or "heads" for all heads') @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def merge(directory=None, revisions='', message=None, branch_label=None, rev_id=None): """Merge two revisions together. Creates a new migration file""" if alembic_version >= (0, 7, 0): config = current_app.extensions['migrate'].migrate.get_config( directory) command.merge(config, revisions, message=message, branch_label=branch_label, rev_id=rev_id) else: raise RuntimeError('Alembic 0.7.0 or greater is required') @MigrateCommand.option('--tag', dest='tag', default=None, help=("Arbitrary 'tag' name - can be used by custom " "env.py scripts")) @MigrateCommand.option('--sql', dest='sql', action='store_true', default=False, help=("Don't emit SQL to database - dump to standard " "output instead")) @MigrateCommand.option('revision', nargs='?', default='head', help="revision identifier") @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @MigrateCommand.option('-x', '--x-arg', dest='x_arg', default=None, action='append', help=("Additional arguments consumed " "by custom env.py scripts")) @catch_errors def upgrade(directory=None, revision='head', sql=False, tag=None, x_arg=None): """Upgrade to a later version""" config = current_app.extensions['migrate'].migrate.get_config(directory, x_arg=x_arg) command.upgrade(config, revision, sql=sql, tag=tag) @MigrateCommand.option('--tag', dest='tag', default=None, help=("Arbitrary 'tag' name - can be used by custom " "env.py scripts")) @MigrateCommand.option('--sql', dest='sql', action='store_true', default=False, help=("Don't emit SQL to database - dump to standard " "output instead")) @MigrateCommand.option('revision', nargs='?', default="-1", help="revision identifier") @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @MigrateCommand.option('-x', '--x-arg', dest='x_arg', default=None, action='append', help=("Additional arguments consumed " "by custom env.py scripts")) @catch_errors def downgrade(directory=None, revision='-1', sql=False, tag=None, x_arg=None): """Revert to a previous version""" config = current_app.extensions['migrate'].migrate.get_config(directory, x_arg=x_arg) if sql and revision == '-1': revision = 'head:-1' command.downgrade(config, revision, sql=sql, tag=tag) @MigrateCommand.option('revision', nargs='?', default="head", help="revision identifier") @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def show(directory=None, revision='head'): """Show the revision denoted by the given symbol.""" if alembic_version >= (0, 7, 0): config = current_app.extensions['migrate'].migrate.get_config( directory) command.show(config, revision) else: raise RuntimeError('Alembic 0.7.0 or greater is required') @MigrateCommand.option('-i', '--indicate-current', dest='indicate_current', action='store_true', default=False, help='Indicate current version (Alembic 0.9.9 or greater is required)') @MigrateCommand.option('-v', '--verbose', dest='verbose', action='store_true', default=False, help='Use more verbose output') @MigrateCommand.option('-r', '--rev-range', dest='rev_range', default=None, help='Specify a revision range; format is [start]:[end]') @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def history(directory=None, rev_range=None, verbose=False, indicate_current=False): """List changeset scripts in chronological order.""" config = current_app.extensions['migrate'].migrate.get_config(directory) if alembic_version >= (0, 9, 9): command.history(config, rev_range, verbose=verbose, indicate_current=indicate_current) elif alembic_version >= (0, 7, 0): command.history(config, rev_range, verbose=verbose) else: command.history(config, rev_range) @MigrateCommand.option('--resolve-dependencies', dest='resolve_dependencies', action='store_true', default=False, help='Treat dependency versions as down revisions') @MigrateCommand.option('-v', '--verbose', dest='verbose', action='store_true', default=False, help='Use more verbose output') @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def heads(directory=None, verbose=False, resolve_dependencies=False): """Show current available heads in the script directory""" if alembic_version >= (0, 7, 0): config = current_app.extensions['migrate'].migrate.get_config( directory) command.heads(config, verbose=verbose, resolve_dependencies=resolve_dependencies) else: raise RuntimeError('Alembic 0.7.0 or greater is required') @MigrateCommand.option('-v', '--verbose', dest='verbose', action='store_true', default=False, help='Use more verbose output') @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors @MigrateCommand.option('--head-only', dest='head_only', action='store_true', default=False, help='Deprecated. Use --verbose for additional output') @MigrateCommand.option('-v', '--verbose', dest='verbose', action='store_true', default=False, help='Use more verbose output') @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def current(directory=None, verbose=False, head_only=False): """Display the current revision for each database.""" config = current_app.extensions['migrate'].migrate.get_config(directory) if alembic_version >= (0, 7, 0): command.current(config, verbose=verbose, head_only=head_only) else: command.current(config) @MigrateCommand.option('--tag', dest='tag', default=None, help=("Arbitrary 'tag' name - can be used by custom " "env.py scripts")) @MigrateCommand.option('--sql', dest='sql', action='store_true', default=False, help=("Don't emit SQL to database - dump to standard " "output instead")) @MigrateCommand.option('revision', default=None, help="revision identifier") @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def stamp(directory=None, revision='head', sql=False, tag=None): """'stamp' the revision table with the given revision; don't run any migrations""" config = current_app.extensions['migrate'].migrate.get_config(directory) command.stamp(config, revision, sql=sql, tag=tag)
miguelgrinberg/Flask-Migrate
flask_migrate/__init__.py
current
python
def current(directory=None, verbose=False, head_only=False): config = current_app.extensions['migrate'].migrate.get_config(directory) if alembic_version >= (0, 7, 0): command.current(config, verbose=verbose, head_only=head_only) else: command.current(config)
Display the current revision for each database.
train
https://github.com/miguelgrinberg/Flask-Migrate/blob/65fbd978681bdf2eddf8940edd04ed7272a94480/flask_migrate/__init__.py#L388-L394
null
import argparse from functools import wraps import logging import os import sys from flask import current_app try: from flask_script import Manager except ImportError: Manager = None from alembic import __version__ as __alembic_version__ from alembic.config import Config as AlembicConfig from alembic import command from alembic.util import CommandError alembic_version = tuple([int(v) for v in __alembic_version__.split('.')[0:3]]) log = logging.getLogger() class _MigrateConfig(object): def __init__(self, migrate, db, **kwargs): self.migrate = migrate self.db = db self.directory = migrate.directory self.configure_args = kwargs @property def metadata(self): """ Backwards compatibility, in old releases app.extensions['migrate'] was set to db, and env.py accessed app.extensions['migrate'].metadata """ return self.db.metadata class Config(AlembicConfig): def get_template_directory(self): package_dir = os.path.abspath(os.path.dirname(__file__)) return os.path.join(package_dir, 'templates') class Migrate(object): def __init__(self, app=None, db=None, directory='migrations', **kwargs): self.configure_callbacks = [] self.db = db self.directory = directory self.alembic_ctx_kwargs = kwargs if app is not None and db is not None: self.init_app(app, db, directory) def init_app(self, app, db=None, directory=None, **kwargs): self.db = db or self.db self.directory = directory or self.directory self.alembic_ctx_kwargs.update(kwargs) if not hasattr(app, 'extensions'): app.extensions = {} app.extensions['migrate'] = _MigrateConfig(self, self.db, **self.alembic_ctx_kwargs) def configure(self, f): self.configure_callbacks.append(f) return f def call_configure_callbacks(self, config): for f in self.configure_callbacks: config = f(config) return config def get_config(self, directory=None, x_arg=None, opts=None): if directory is None: directory = self.directory config = Config(os.path.join(directory, 'alembic.ini')) config.set_main_option('script_location', directory) if config.cmd_opts is None: config.cmd_opts = argparse.Namespace() for opt in opts or []: setattr(config.cmd_opts, opt, True) if not hasattr(config.cmd_opts, 'x'): if x_arg is not None: setattr(config.cmd_opts, 'x', []) if isinstance(x_arg, list) or isinstance(x_arg, tuple): for x in x_arg: config.cmd_opts.x.append(x) else: config.cmd_opts.x.append(x_arg) else: setattr(config.cmd_opts, 'x', None) return self.call_configure_callbacks(config) def catch_errors(f): @wraps(f) def wrapped(*args, **kwargs): try: f(*args, **kwargs) except (CommandError, RuntimeError) as exc: log.error('Error: ' + str(exc)) sys.exit(1) return wrapped if Manager is not None: MigrateCommand = Manager(usage='Perform database migrations') else: class FakeCommand(object): def option(self, *args, **kwargs): def decorator(f): return f return decorator MigrateCommand = FakeCommand() @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @MigrateCommand.option('--multidb', dest='multidb', action='store_true', default=False, help=("Multiple databases migraton (default is " "False)")) @catch_errors def init(directory=None, multidb=False): """Creates a new migration repository""" if directory is None: directory = current_app.extensions['migrate'].directory config = Config() config.set_main_option('script_location', directory) config.config_file_name = os.path.join(directory, 'alembic.ini') config = current_app.extensions['migrate'].\ migrate.call_configure_callbacks(config) if multidb: command.init(config, directory, 'flask-multidb') else: command.init(config, directory, 'flask') @MigrateCommand.option('--rev-id', dest='rev_id', default=None, help=('Specify a hardcoded revision id instead of ' 'generating one')) @MigrateCommand.option('--version-path', dest='version_path', default=None, help=('Specify specific path from config for version ' 'file')) @MigrateCommand.option('--branch-label', dest='branch_label', default=None, help=('Specify a branch label to apply to the new ' 'revision')) @MigrateCommand.option('--splice', dest='splice', action='store_true', default=False, help=('Allow a non-head revision as the "head" to ' 'splice onto')) @MigrateCommand.option('--head', dest='head', default='head', help=('Specify head revision or <branchname>@head to ' 'base new revision on')) @MigrateCommand.option('--sql', dest='sql', action='store_true', default=False, help=("Don't emit SQL to database - dump to standard " "output instead")) @MigrateCommand.option('--autogenerate', dest='autogenerate', action='store_true', default=False, help=('Populate revision script with candidate ' 'migration operations, based on comparison of ' 'database to model')) @MigrateCommand.option('-m', '--message', dest='message', default=None, help='Revision message') @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def revision(directory=None, message=None, autogenerate=False, sql=False, head='head', splice=False, branch_label=None, version_path=None, rev_id=None): """Create a new revision file.""" config = current_app.extensions['migrate'].migrate.get_config(directory) if alembic_version >= (0, 7, 0): command.revision(config, message, autogenerate=autogenerate, sql=sql, head=head, splice=splice, branch_label=branch_label, version_path=version_path, rev_id=rev_id) else: command.revision(config, message, autogenerate=autogenerate, sql=sql) @MigrateCommand.option('--rev-id', dest='rev_id', default=None, help=('Specify a hardcoded revision id instead of ' 'generating one')) @MigrateCommand.option('--version-path', dest='version_path', default=None, help=('Specify specific path from config for version ' 'file')) @MigrateCommand.option('--branch-label', dest='branch_label', default=None, help=('Specify a branch label to apply to the new ' 'revision')) @MigrateCommand.option('--splice', dest='splice', action='store_true', default=False, help=('Allow a non-head revision as the "head" to ' 'splice onto')) @MigrateCommand.option('--head', dest='head', default='head', help=('Specify head revision or <branchname>@head to ' 'base new revision on')) @MigrateCommand.option('--sql', dest='sql', action='store_true', default=False, help=("Don't emit SQL to database - dump to standard " "output instead")) @MigrateCommand.option('-m', '--message', dest='message', default=None) @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @MigrateCommand.option('-x', '--x-arg', dest='x_arg', default=None, action='append', help=("Additional arguments consumed " "by custom env.py scripts")) @catch_errors def migrate(directory=None, message=None, sql=False, head='head', splice=False, branch_label=None, version_path=None, rev_id=None, x_arg=None): """Alias for 'revision --autogenerate'""" config = current_app.extensions['migrate'].migrate.get_config( directory, opts=['autogenerate'], x_arg=x_arg) if alembic_version >= (0, 7, 0): command.revision(config, message, autogenerate=True, sql=sql, head=head, splice=splice, branch_label=branch_label, version_path=version_path, rev_id=rev_id) else: command.revision(config, message, autogenerate=True, sql=sql) @MigrateCommand.option('revision', nargs='?', default='head', help="revision identifier") @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def edit(directory=None, revision='current'): """Edit current revision.""" if alembic_version >= (0, 8, 0): config = current_app.extensions['migrate'].migrate.get_config( directory) command.edit(config, revision) else: raise RuntimeError('Alembic 0.8.0 or greater is required') @MigrateCommand.option('--rev-id', dest='rev_id', default=None, help=('Specify a hardcoded revision id instead of ' 'generating one')) @MigrateCommand.option('--branch-label', dest='branch_label', default=None, help=('Specify a branch label to apply to the new ' 'revision')) @MigrateCommand.option('-m', '--message', dest='message', default=None) @MigrateCommand.option('revisions', nargs='+', help='one or more revisions, or "heads" for all heads') @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def merge(directory=None, revisions='', message=None, branch_label=None, rev_id=None): """Merge two revisions together. Creates a new migration file""" if alembic_version >= (0, 7, 0): config = current_app.extensions['migrate'].migrate.get_config( directory) command.merge(config, revisions, message=message, branch_label=branch_label, rev_id=rev_id) else: raise RuntimeError('Alembic 0.7.0 or greater is required') @MigrateCommand.option('--tag', dest='tag', default=None, help=("Arbitrary 'tag' name - can be used by custom " "env.py scripts")) @MigrateCommand.option('--sql', dest='sql', action='store_true', default=False, help=("Don't emit SQL to database - dump to standard " "output instead")) @MigrateCommand.option('revision', nargs='?', default='head', help="revision identifier") @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @MigrateCommand.option('-x', '--x-arg', dest='x_arg', default=None, action='append', help=("Additional arguments consumed " "by custom env.py scripts")) @catch_errors def upgrade(directory=None, revision='head', sql=False, tag=None, x_arg=None): """Upgrade to a later version""" config = current_app.extensions['migrate'].migrate.get_config(directory, x_arg=x_arg) command.upgrade(config, revision, sql=sql, tag=tag) @MigrateCommand.option('--tag', dest='tag', default=None, help=("Arbitrary 'tag' name - can be used by custom " "env.py scripts")) @MigrateCommand.option('--sql', dest='sql', action='store_true', default=False, help=("Don't emit SQL to database - dump to standard " "output instead")) @MigrateCommand.option('revision', nargs='?', default="-1", help="revision identifier") @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @MigrateCommand.option('-x', '--x-arg', dest='x_arg', default=None, action='append', help=("Additional arguments consumed " "by custom env.py scripts")) @catch_errors def downgrade(directory=None, revision='-1', sql=False, tag=None, x_arg=None): """Revert to a previous version""" config = current_app.extensions['migrate'].migrate.get_config(directory, x_arg=x_arg) if sql and revision == '-1': revision = 'head:-1' command.downgrade(config, revision, sql=sql, tag=tag) @MigrateCommand.option('revision', nargs='?', default="head", help="revision identifier") @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def show(directory=None, revision='head'): """Show the revision denoted by the given symbol.""" if alembic_version >= (0, 7, 0): config = current_app.extensions['migrate'].migrate.get_config( directory) command.show(config, revision) else: raise RuntimeError('Alembic 0.7.0 or greater is required') @MigrateCommand.option('-i', '--indicate-current', dest='indicate_current', action='store_true', default=False, help='Indicate current version (Alembic 0.9.9 or greater is required)') @MigrateCommand.option('-v', '--verbose', dest='verbose', action='store_true', default=False, help='Use more verbose output') @MigrateCommand.option('-r', '--rev-range', dest='rev_range', default=None, help='Specify a revision range; format is [start]:[end]') @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def history(directory=None, rev_range=None, verbose=False, indicate_current=False): """List changeset scripts in chronological order.""" config = current_app.extensions['migrate'].migrate.get_config(directory) if alembic_version >= (0, 9, 9): command.history(config, rev_range, verbose=verbose, indicate_current=indicate_current) elif alembic_version >= (0, 7, 0): command.history(config, rev_range, verbose=verbose) else: command.history(config, rev_range) @MigrateCommand.option('--resolve-dependencies', dest='resolve_dependencies', action='store_true', default=False, help='Treat dependency versions as down revisions') @MigrateCommand.option('-v', '--verbose', dest='verbose', action='store_true', default=False, help='Use more verbose output') @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def heads(directory=None, verbose=False, resolve_dependencies=False): """Show current available heads in the script directory""" if alembic_version >= (0, 7, 0): config = current_app.extensions['migrate'].migrate.get_config( directory) command.heads(config, verbose=verbose, resolve_dependencies=resolve_dependencies) else: raise RuntimeError('Alembic 0.7.0 or greater is required') @MigrateCommand.option('-v', '--verbose', dest='verbose', action='store_true', default=False, help='Use more verbose output') @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def branches(directory=None, verbose=False): """Show current branch points""" config = current_app.extensions['migrate'].migrate.get_config(directory) if alembic_version >= (0, 7, 0): command.branches(config, verbose=verbose) else: command.branches(config) @MigrateCommand.option('--head-only', dest='head_only', action='store_true', default=False, help='Deprecated. Use --verbose for additional output') @MigrateCommand.option('-v', '--verbose', dest='verbose', action='store_true', default=False, help='Use more verbose output') @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors @MigrateCommand.option('--tag', dest='tag', default=None, help=("Arbitrary 'tag' name - can be used by custom " "env.py scripts")) @MigrateCommand.option('--sql', dest='sql', action='store_true', default=False, help=("Don't emit SQL to database - dump to standard " "output instead")) @MigrateCommand.option('revision', default=None, help="revision identifier") @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def stamp(directory=None, revision='head', sql=False, tag=None): """'stamp' the revision table with the given revision; don't run any migrations""" config = current_app.extensions['migrate'].migrate.get_config(directory) command.stamp(config, revision, sql=sql, tag=tag)
miguelgrinberg/Flask-Migrate
flask_migrate/__init__.py
stamp
python
def stamp(directory=None, revision='head', sql=False, tag=None): """'stamp' the revision table with the given revision; don't run any migrations""" config = current_app.extensions['migrate'].migrate.get_config(directory) command.stamp(config, revision, sql=sql, tag=tag)
stamp' the revision table with the given revision; don't run any migrations
train
https://github.com/miguelgrinberg/Flask-Migrate/blob/65fbd978681bdf2eddf8940edd04ed7272a94480/flask_migrate/__init__.py#L408-L412
null
import argparse from functools import wraps import logging import os import sys from flask import current_app try: from flask_script import Manager except ImportError: Manager = None from alembic import __version__ as __alembic_version__ from alembic.config import Config as AlembicConfig from alembic import command from alembic.util import CommandError alembic_version = tuple([int(v) for v in __alembic_version__.split('.')[0:3]]) log = logging.getLogger() class _MigrateConfig(object): def __init__(self, migrate, db, **kwargs): self.migrate = migrate self.db = db self.directory = migrate.directory self.configure_args = kwargs @property def metadata(self): """ Backwards compatibility, in old releases app.extensions['migrate'] was set to db, and env.py accessed app.extensions['migrate'].metadata """ return self.db.metadata class Config(AlembicConfig): def get_template_directory(self): package_dir = os.path.abspath(os.path.dirname(__file__)) return os.path.join(package_dir, 'templates') class Migrate(object): def __init__(self, app=None, db=None, directory='migrations', **kwargs): self.configure_callbacks = [] self.db = db self.directory = directory self.alembic_ctx_kwargs = kwargs if app is not None and db is not None: self.init_app(app, db, directory) def init_app(self, app, db=None, directory=None, **kwargs): self.db = db or self.db self.directory = directory or self.directory self.alembic_ctx_kwargs.update(kwargs) if not hasattr(app, 'extensions'): app.extensions = {} app.extensions['migrate'] = _MigrateConfig(self, self.db, **self.alembic_ctx_kwargs) def configure(self, f): self.configure_callbacks.append(f) return f def call_configure_callbacks(self, config): for f in self.configure_callbacks: config = f(config) return config def get_config(self, directory=None, x_arg=None, opts=None): if directory is None: directory = self.directory config = Config(os.path.join(directory, 'alembic.ini')) config.set_main_option('script_location', directory) if config.cmd_opts is None: config.cmd_opts = argparse.Namespace() for opt in opts or []: setattr(config.cmd_opts, opt, True) if not hasattr(config.cmd_opts, 'x'): if x_arg is not None: setattr(config.cmd_opts, 'x', []) if isinstance(x_arg, list) or isinstance(x_arg, tuple): for x in x_arg: config.cmd_opts.x.append(x) else: config.cmd_opts.x.append(x_arg) else: setattr(config.cmd_opts, 'x', None) return self.call_configure_callbacks(config) def catch_errors(f): @wraps(f) def wrapped(*args, **kwargs): try: f(*args, **kwargs) except (CommandError, RuntimeError) as exc: log.error('Error: ' + str(exc)) sys.exit(1) return wrapped if Manager is not None: MigrateCommand = Manager(usage='Perform database migrations') else: class FakeCommand(object): def option(self, *args, **kwargs): def decorator(f): return f return decorator MigrateCommand = FakeCommand() @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @MigrateCommand.option('--multidb', dest='multidb', action='store_true', default=False, help=("Multiple databases migraton (default is " "False)")) @catch_errors def init(directory=None, multidb=False): """Creates a new migration repository""" if directory is None: directory = current_app.extensions['migrate'].directory config = Config() config.set_main_option('script_location', directory) config.config_file_name = os.path.join(directory, 'alembic.ini') config = current_app.extensions['migrate'].\ migrate.call_configure_callbacks(config) if multidb: command.init(config, directory, 'flask-multidb') else: command.init(config, directory, 'flask') @MigrateCommand.option('--rev-id', dest='rev_id', default=None, help=('Specify a hardcoded revision id instead of ' 'generating one')) @MigrateCommand.option('--version-path', dest='version_path', default=None, help=('Specify specific path from config for version ' 'file')) @MigrateCommand.option('--branch-label', dest='branch_label', default=None, help=('Specify a branch label to apply to the new ' 'revision')) @MigrateCommand.option('--splice', dest='splice', action='store_true', default=False, help=('Allow a non-head revision as the "head" to ' 'splice onto')) @MigrateCommand.option('--head', dest='head', default='head', help=('Specify head revision or <branchname>@head to ' 'base new revision on')) @MigrateCommand.option('--sql', dest='sql', action='store_true', default=False, help=("Don't emit SQL to database - dump to standard " "output instead")) @MigrateCommand.option('--autogenerate', dest='autogenerate', action='store_true', default=False, help=('Populate revision script with candidate ' 'migration operations, based on comparison of ' 'database to model')) @MigrateCommand.option('-m', '--message', dest='message', default=None, help='Revision message') @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def revision(directory=None, message=None, autogenerate=False, sql=False, head='head', splice=False, branch_label=None, version_path=None, rev_id=None): """Create a new revision file.""" config = current_app.extensions['migrate'].migrate.get_config(directory) if alembic_version >= (0, 7, 0): command.revision(config, message, autogenerate=autogenerate, sql=sql, head=head, splice=splice, branch_label=branch_label, version_path=version_path, rev_id=rev_id) else: command.revision(config, message, autogenerate=autogenerate, sql=sql) @MigrateCommand.option('--rev-id', dest='rev_id', default=None, help=('Specify a hardcoded revision id instead of ' 'generating one')) @MigrateCommand.option('--version-path', dest='version_path', default=None, help=('Specify specific path from config for version ' 'file')) @MigrateCommand.option('--branch-label', dest='branch_label', default=None, help=('Specify a branch label to apply to the new ' 'revision')) @MigrateCommand.option('--splice', dest='splice', action='store_true', default=False, help=('Allow a non-head revision as the "head" to ' 'splice onto')) @MigrateCommand.option('--head', dest='head', default='head', help=('Specify head revision or <branchname>@head to ' 'base new revision on')) @MigrateCommand.option('--sql', dest='sql', action='store_true', default=False, help=("Don't emit SQL to database - dump to standard " "output instead")) @MigrateCommand.option('-m', '--message', dest='message', default=None) @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @MigrateCommand.option('-x', '--x-arg', dest='x_arg', default=None, action='append', help=("Additional arguments consumed " "by custom env.py scripts")) @catch_errors def migrate(directory=None, message=None, sql=False, head='head', splice=False, branch_label=None, version_path=None, rev_id=None, x_arg=None): """Alias for 'revision --autogenerate'""" config = current_app.extensions['migrate'].migrate.get_config( directory, opts=['autogenerate'], x_arg=x_arg) if alembic_version >= (0, 7, 0): command.revision(config, message, autogenerate=True, sql=sql, head=head, splice=splice, branch_label=branch_label, version_path=version_path, rev_id=rev_id) else: command.revision(config, message, autogenerate=True, sql=sql) @MigrateCommand.option('revision', nargs='?', default='head', help="revision identifier") @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def edit(directory=None, revision='current'): """Edit current revision.""" if alembic_version >= (0, 8, 0): config = current_app.extensions['migrate'].migrate.get_config( directory) command.edit(config, revision) else: raise RuntimeError('Alembic 0.8.0 or greater is required') @MigrateCommand.option('--rev-id', dest='rev_id', default=None, help=('Specify a hardcoded revision id instead of ' 'generating one')) @MigrateCommand.option('--branch-label', dest='branch_label', default=None, help=('Specify a branch label to apply to the new ' 'revision')) @MigrateCommand.option('-m', '--message', dest='message', default=None) @MigrateCommand.option('revisions', nargs='+', help='one or more revisions, or "heads" for all heads') @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def merge(directory=None, revisions='', message=None, branch_label=None, rev_id=None): """Merge two revisions together. Creates a new migration file""" if alembic_version >= (0, 7, 0): config = current_app.extensions['migrate'].migrate.get_config( directory) command.merge(config, revisions, message=message, branch_label=branch_label, rev_id=rev_id) else: raise RuntimeError('Alembic 0.7.0 or greater is required') @MigrateCommand.option('--tag', dest='tag', default=None, help=("Arbitrary 'tag' name - can be used by custom " "env.py scripts")) @MigrateCommand.option('--sql', dest='sql', action='store_true', default=False, help=("Don't emit SQL to database - dump to standard " "output instead")) @MigrateCommand.option('revision', nargs='?', default='head', help="revision identifier") @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @MigrateCommand.option('-x', '--x-arg', dest='x_arg', default=None, action='append', help=("Additional arguments consumed " "by custom env.py scripts")) @catch_errors def upgrade(directory=None, revision='head', sql=False, tag=None, x_arg=None): """Upgrade to a later version""" config = current_app.extensions['migrate'].migrate.get_config(directory, x_arg=x_arg) command.upgrade(config, revision, sql=sql, tag=tag) @MigrateCommand.option('--tag', dest='tag', default=None, help=("Arbitrary 'tag' name - can be used by custom " "env.py scripts")) @MigrateCommand.option('--sql', dest='sql', action='store_true', default=False, help=("Don't emit SQL to database - dump to standard " "output instead")) @MigrateCommand.option('revision', nargs='?', default="-1", help="revision identifier") @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @MigrateCommand.option('-x', '--x-arg', dest='x_arg', default=None, action='append', help=("Additional arguments consumed " "by custom env.py scripts")) @catch_errors def downgrade(directory=None, revision='-1', sql=False, tag=None, x_arg=None): """Revert to a previous version""" config = current_app.extensions['migrate'].migrate.get_config(directory, x_arg=x_arg) if sql and revision == '-1': revision = 'head:-1' command.downgrade(config, revision, sql=sql, tag=tag) @MigrateCommand.option('revision', nargs='?', default="head", help="revision identifier") @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def show(directory=None, revision='head'): """Show the revision denoted by the given symbol.""" if alembic_version >= (0, 7, 0): config = current_app.extensions['migrate'].migrate.get_config( directory) command.show(config, revision) else: raise RuntimeError('Alembic 0.7.0 or greater is required') @MigrateCommand.option('-i', '--indicate-current', dest='indicate_current', action='store_true', default=False, help='Indicate current version (Alembic 0.9.9 or greater is required)') @MigrateCommand.option('-v', '--verbose', dest='verbose', action='store_true', default=False, help='Use more verbose output') @MigrateCommand.option('-r', '--rev-range', dest='rev_range', default=None, help='Specify a revision range; format is [start]:[end]') @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def history(directory=None, rev_range=None, verbose=False, indicate_current=False): """List changeset scripts in chronological order.""" config = current_app.extensions['migrate'].migrate.get_config(directory) if alembic_version >= (0, 9, 9): command.history(config, rev_range, verbose=verbose, indicate_current=indicate_current) elif alembic_version >= (0, 7, 0): command.history(config, rev_range, verbose=verbose) else: command.history(config, rev_range) @MigrateCommand.option('--resolve-dependencies', dest='resolve_dependencies', action='store_true', default=False, help='Treat dependency versions as down revisions') @MigrateCommand.option('-v', '--verbose', dest='verbose', action='store_true', default=False, help='Use more verbose output') @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def heads(directory=None, verbose=False, resolve_dependencies=False): """Show current available heads in the script directory""" if alembic_version >= (0, 7, 0): config = current_app.extensions['migrate'].migrate.get_config( directory) command.heads(config, verbose=verbose, resolve_dependencies=resolve_dependencies) else: raise RuntimeError('Alembic 0.7.0 or greater is required') @MigrateCommand.option('-v', '--verbose', dest='verbose', action='store_true', default=False, help='Use more verbose output') @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def branches(directory=None, verbose=False): """Show current branch points""" config = current_app.extensions['migrate'].migrate.get_config(directory) if alembic_version >= (0, 7, 0): command.branches(config, verbose=verbose) else: command.branches(config) @MigrateCommand.option('--head-only', dest='head_only', action='store_true', default=False, help='Deprecated. Use --verbose for additional output') @MigrateCommand.option('-v', '--verbose', dest='verbose', action='store_true', default=False, help='Use more verbose output') @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors def current(directory=None, verbose=False, head_only=False): """Display the current revision for each database.""" config = current_app.extensions['migrate'].migrate.get_config(directory) if alembic_version >= (0, 7, 0): command.current(config, verbose=verbose, head_only=head_only) else: command.current(config) @MigrateCommand.option('--tag', dest='tag', default=None, help=("Arbitrary 'tag' name - can be used by custom " "env.py scripts")) @MigrateCommand.option('--sql', dest='sql', action='store_true', default=False, help=("Don't emit SQL to database - dump to standard " "output instead")) @MigrateCommand.option('revision', default=None, help="revision identifier") @MigrateCommand.option('-d', '--directory', dest='directory', default=None, help=("migration script directory (default is " "'migrations')")) @catch_errors
goldsmith/Wikipedia
wikipedia/wikipedia.py
set_lang
python
def set_lang(prefix): ''' Change the language of the API being requested. Set `prefix` to one of the two letter prefixes found on the `list of all Wikipedias <http://meta.wikimedia.org/wiki/List_of_Wikipedias>`_. After setting the language, the cache for ``search``, ``suggest``, and ``summary`` will be cleared. .. note:: Make sure you search for page titles in the language that you have set. ''' global API_URL API_URL = 'http://' + prefix.lower() + '.wikipedia.org/w/api.php' for cached_func in (search, suggest, summary): cached_func.clear_cache()
Change the language of the API being requested. Set `prefix` to one of the two letter prefixes found on the `list of all Wikipedias <http://meta.wikimedia.org/wiki/List_of_Wikipedias>`_. After setting the language, the cache for ``search``, ``suggest``, and ``summary`` will be cleared. .. note:: Make sure you search for page titles in the language that you have set.
train
https://github.com/goldsmith/Wikipedia/blob/2065c568502b19b8634241b47fd96930d1bf948d/wikipedia/wikipedia.py#L22-L35
[ "def clear_cache(self):\n self._cache = {}\n" ]
from __future__ import unicode_literals import requests import time from bs4 import BeautifulSoup from datetime import datetime, timedelta from decimal import Decimal from .exceptions import ( PageError, DisambiguationError, RedirectError, HTTPTimeoutError, WikipediaException, ODD_ERROR_MESSAGE) from .util import cache, stdout_encode, debug import re API_URL = 'http://en.wikipedia.org/w/api.php' RATE_LIMIT = False RATE_LIMIT_MIN_WAIT = None RATE_LIMIT_LAST_CALL = None USER_AGENT = 'wikipedia (https://github.com/goldsmith/Wikipedia/)' def set_user_agent(user_agent_string): ''' Set the User-Agent string to be used for all requests. Arguments: * user_agent_string - (string) a string specifying the User-Agent header ''' global USER_AGENT USER_AGENT = user_agent_string def set_rate_limiting(rate_limit, min_wait=timedelta(milliseconds=50)): ''' Enable or disable rate limiting on requests to the Mediawiki servers. If rate limiting is not enabled, under some circumstances (depending on load on Wikipedia, the number of requests you and other `wikipedia` users are making, and other factors), Wikipedia may return an HTTP timeout error. Enabling rate limiting generally prevents that issue, but please note that HTTPTimeoutError still might be raised. Arguments: * rate_limit - (Boolean) whether to enable rate limiting or not Keyword arguments: * min_wait - if rate limiting is enabled, `min_wait` is a timedelta describing the minimum time to wait before requests. Defaults to timedelta(milliseconds=50) ''' global RATE_LIMIT global RATE_LIMIT_MIN_WAIT global RATE_LIMIT_LAST_CALL RATE_LIMIT = rate_limit if not rate_limit: RATE_LIMIT_MIN_WAIT = None else: RATE_LIMIT_MIN_WAIT = min_wait RATE_LIMIT_LAST_CALL = None @cache def search(query, results=10, suggestion=False): ''' Do a Wikipedia search for `query`. Keyword arguments: * results - the maxmimum number of results returned * suggestion - if True, return results and suggestion (if any) in a tuple ''' search_params = { 'list': 'search', 'srprop': '', 'srlimit': results, 'limit': results, 'srsearch': query } if suggestion: search_params['srinfo'] = 'suggestion' raw_results = _wiki_request(search_params) if 'error' in raw_results: if raw_results['error']['info'] in ('HTTP request timed out.', 'Pool queue is full'): raise HTTPTimeoutError(query) else: raise WikipediaException(raw_results['error']['info']) search_results = (d['title'] for d in raw_results['query']['search']) if suggestion: if raw_results['query'].get('searchinfo'): return list(search_results), raw_results['query']['searchinfo']['suggestion'] else: return list(search_results), None return list(search_results) @cache def geosearch(latitude, longitude, title=None, results=10, radius=1000): ''' Do a wikipedia geo search for `latitude` and `longitude` using HTTP API described in http://www.mediawiki.org/wiki/Extension:GeoData Arguments: * latitude (float or decimal.Decimal) * longitude (float or decimal.Decimal) Keyword arguments: * title - The title of an article to search for * results - the maximum number of results returned * radius - Search radius in meters. The value must be between 10 and 10000 ''' search_params = { 'list': 'geosearch', 'gsradius': radius, 'gscoord': '{0}|{1}'.format(latitude, longitude), 'gslimit': results } if title: search_params['titles'] = title raw_results = _wiki_request(search_params) if 'error' in raw_results: if raw_results['error']['info'] in ('HTTP request timed out.', 'Pool queue is full'): raise HTTPTimeoutError('{0}|{1}'.format(latitude, longitude)) else: raise WikipediaException(raw_results['error']['info']) search_pages = raw_results['query'].get('pages', None) if search_pages: search_results = (v['title'] for k, v in search_pages.items() if k != '-1') else: search_results = (d['title'] for d in raw_results['query']['geosearch']) return list(search_results) @cache def suggest(query): ''' Get a Wikipedia search suggestion for `query`. Returns a string or None if no suggestion was found. ''' search_params = { 'list': 'search', 'srinfo': 'suggestion', 'srprop': '', } search_params['srsearch'] = query raw_result = _wiki_request(search_params) if raw_result['query'].get('searchinfo'): return raw_result['query']['searchinfo']['suggestion'] return None def random(pages=1): ''' Get a list of random Wikipedia article titles. .. note:: Random only gets articles from namespace 0, meaning no Category, User talk, or other meta-Wikipedia pages. Keyword arguments: * pages - the number of random pages returned (max of 10) ''' #http://en.wikipedia.org/w/api.php?action=query&list=random&rnlimit=5000&format=jsonfm query_params = { 'list': 'random', 'rnnamespace': 0, 'rnlimit': pages, } request = _wiki_request(query_params) titles = [page['title'] for page in request['query']['random']] if len(titles) == 1: return titles[0] return titles @cache def summary(title, sentences=0, chars=0, auto_suggest=True, redirect=True): ''' Plain text summary of the page. .. note:: This is a convenience wrapper - auto_suggest and redirect are enabled by default Keyword arguments: * sentences - if set, return the first `sentences` sentences (can be no greater than 10). * chars - if set, return only the first `chars` characters (actual text returned may be slightly longer). * auto_suggest - let Wikipedia find a valid page title for the query * redirect - allow redirection without raising RedirectError ''' # use auto_suggest and redirect to get the correct article # also, use page's error checking to raise DisambiguationError if necessary page_info = page(title, auto_suggest=auto_suggest, redirect=redirect) title = page_info.title pageid = page_info.pageid query_params = { 'prop': 'extracts', 'explaintext': '', 'titles': title } if sentences: query_params['exsentences'] = sentences elif chars: query_params['exchars'] = chars else: query_params['exintro'] = '' request = _wiki_request(query_params) summary = request['query']['pages'][pageid]['extract'] return summary def page(title=None, pageid=None, auto_suggest=True, redirect=True, preload=False): ''' Get a WikipediaPage object for the page with title `title` or the pageid `pageid` (mutually exclusive). Keyword arguments: * title - the title of the page to load * pageid - the numeric pageid of the page to load * auto_suggest - let Wikipedia find a valid page title for the query * redirect - allow redirection without raising RedirectError * preload - load content, summary, images, references, and links during initialization ''' if title is not None: if auto_suggest: results, suggestion = search(title, results=1, suggestion=True) try: title = suggestion or results[0] except IndexError: # if there is no suggestion or search results, the page doesn't exist raise PageError(title) return WikipediaPage(title, redirect=redirect, preload=preload) elif pageid is not None: return WikipediaPage(pageid=pageid, preload=preload) else: raise ValueError("Either a title or a pageid must be specified") class WikipediaPage(object): ''' Contains data from a Wikipedia page. Uses property methods to filter data from the raw HTML. ''' def __init__(self, title=None, pageid=None, redirect=True, preload=False, original_title=''): if title is not None: self.title = title self.original_title = original_title or title elif pageid is not None: self.pageid = pageid else: raise ValueError("Either a title or a pageid must be specified") self.__load(redirect=redirect, preload=preload) if preload: for prop in ('content', 'summary', 'images', 'references', 'links', 'sections'): getattr(self, prop) def __repr__(self): return stdout_encode(u'<WikipediaPage \'{}\'>'.format(self.title)) def __eq__(self, other): try: return ( self.pageid == other.pageid and self.title == other.title and self.url == other.url ) except: return False def __load(self, redirect=True, preload=False): ''' Load basic information from Wikipedia. Confirm that page exists and is not a disambiguation/redirect. Does not need to be called manually, should be called automatically during __init__. ''' query_params = { 'prop': 'info|pageprops', 'inprop': 'url', 'ppprop': 'disambiguation', 'redirects': '', } if not getattr(self, 'pageid', None): query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) query = request['query'] pageid = list(query['pages'].keys())[0] page = query['pages'][pageid] # missing is present if the page is missing if 'missing' in page: if hasattr(self, 'title'): raise PageError(self.title) else: raise PageError(pageid=self.pageid) # same thing for redirect, except it shows up in query instead of page for # whatever silly reason elif 'redirects' in query: if redirect: redirects = query['redirects'][0] if 'normalized' in query: normalized = query['normalized'][0] assert normalized['from'] == self.title, ODD_ERROR_MESSAGE from_title = normalized['to'] else: from_title = self.title assert redirects['from'] == from_title, ODD_ERROR_MESSAGE # change the title and reload the whole object self.__init__(redirects['to'], redirect=redirect, preload=preload) else: raise RedirectError(getattr(self, 'title', page['title'])) # since we only asked for disambiguation in ppprop, # if a pageprop is returned, # then the page must be a disambiguation page elif 'pageprops' in page: query_params = { 'prop': 'revisions', 'rvprop': 'content', 'rvparse': '', 'rvlimit': 1 } if hasattr(self, 'pageid'): query_params['pageids'] = self.pageid else: query_params['titles'] = self.title request = _wiki_request(query_params) html = request['query']['pages'][pageid]['revisions'][0]['*'] lis = BeautifulSoup(html, 'html.parser').find_all('li') filtered_lis = [li for li in lis if not 'tocsection' in ''.join(li.get('class', []))] may_refer_to = [li.a.get_text() for li in filtered_lis if li.a] raise DisambiguationError(getattr(self, 'title', page['title']), may_refer_to) else: self.pageid = pageid self.title = page['title'] self.url = page['fullurl'] def __continued_query(self, query_params): ''' Based on https://www.mediawiki.org/wiki/API:Query#Continuing_queries ''' query_params.update(self.__title_query_param) last_continue = {} prop = query_params.get('prop', None) while True: params = query_params.copy() params.update(last_continue) request = _wiki_request(params) if 'query' not in request: break pages = request['query']['pages'] if 'generator' in query_params: for datum in pages.values(): # in python 3.3+: "yield from pages.values()" yield datum else: for datum in pages[self.pageid][prop]: yield datum if 'continue' not in request: break last_continue = request['continue'] @property def __title_query_param(self): if getattr(self, 'title', None) is not None: return {'titles': self.title} else: return {'pageids': self.pageid} def html(self): ''' Get full page HTML. .. warning:: This can get pretty slow on long pages. ''' if not getattr(self, '_html', False): query_params = { 'prop': 'revisions', 'rvprop': 'content', 'rvlimit': 1, 'rvparse': '', 'titles': self.title } request = _wiki_request(query_params) self._html = request['query']['pages'][self.pageid]['revisions'][0]['*'] return self._html @property def content(self): ''' Plain text content of the page, excluding images, tables, and other data. ''' if not getattr(self, '_content', False): query_params = { 'prop': 'extracts|revisions', 'explaintext': '', 'rvprop': 'ids' } if not getattr(self, 'title', None) is None: query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) self._content = request['query']['pages'][self.pageid]['extract'] self._revision_id = request['query']['pages'][self.pageid]['revisions'][0]['revid'] self._parent_id = request['query']['pages'][self.pageid]['revisions'][0]['parentid'] return self._content @property def revision_id(self): ''' Revision ID of the page. The revision ID is a number that uniquely identifies the current version of the page. It can be used to create the permalink or for other direct API calls. See `Help:Page history <http://en.wikipedia.org/wiki/Wikipedia:Revision>`_ for more information. ''' if not getattr(self, '_revid', False): # fetch the content (side effect is loading the revid) self.content return self._revision_id @property def parent_id(self): ''' Revision ID of the parent version of the current revision of this page. See ``revision_id`` for more information. ''' if not getattr(self, '_parentid', False): # fetch the content (side effect is loading the revid) self.content return self._parent_id @property def summary(self): ''' Plain text summary of the page. ''' if not getattr(self, '_summary', False): query_params = { 'prop': 'extracts', 'explaintext': '', 'exintro': '', } if not getattr(self, 'title', None) is None: query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) self._summary = request['query']['pages'][self.pageid]['extract'] return self._summary @property def images(self): ''' List of URLs of images on the page. ''' if not getattr(self, '_images', False): self._images = [ page['imageinfo'][0]['url'] for page in self.__continued_query({ 'generator': 'images', 'gimlimit': 'max', 'prop': 'imageinfo', 'iiprop': 'url', }) if 'imageinfo' in page ] return self._images @property def coordinates(self): ''' Tuple of Decimals in the form of (lat, lon) or None ''' if not getattr(self, '_coordinates', False): query_params = { 'prop': 'coordinates', 'colimit': 'max', 'titles': self.title, } request = _wiki_request(query_params) if 'query' in request: coordinates = request['query']['pages'][self.pageid]['coordinates'] self._coordinates = (Decimal(coordinates[0]['lat']), Decimal(coordinates[0]['lon'])) else: self._coordinates = None return self._coordinates @property def references(self): ''' List of URLs of external links on a page. May include external links within page that aren't technically cited anywhere. ''' if not getattr(self, '_references', False): def add_protocol(url): return url if url.startswith('http') else 'http:' + url self._references = [ add_protocol(link['*']) for link in self.__continued_query({ 'prop': 'extlinks', 'ellimit': 'max' }) ] return self._references @property def links(self): ''' List of titles of Wikipedia page links on a page. .. note:: Only includes articles from namespace 0, meaning no Category, User talk, or other meta-Wikipedia pages. ''' if not getattr(self, '_links', False): self._links = [ link['title'] for link in self.__continued_query({ 'prop': 'links', 'plnamespace': 0, 'pllimit': 'max' }) ] return self._links @property def categories(self): ''' List of categories of a page. ''' if not getattr(self, '_categories', False): self._categories = [re.sub(r'^Category:', '', x) for x in [link['title'] for link in self.__continued_query({ 'prop': 'categories', 'cllimit': 'max' }) ]] return self._categories @property def sections(self): ''' List of section titles from the table of contents on the page. ''' if not getattr(self, '_sections', False): query_params = { 'action': 'parse', 'prop': 'sections', } query_params.update(self.__title_query_param) request = _wiki_request(query_params) self._sections = [section['line'] for section in request['parse']['sections']] return self._sections def section(self, section_title): ''' Get the plain text content of a section from `self.sections`. Returns None if `section_title` isn't found, otherwise returns a whitespace stripped string. This is a convenience method that wraps self.content. .. warning:: Calling `section` on a section that has subheadings will NOT return the full text of all of the subsections. It only gets the text between `section_title` and the next subheading, which is often empty. ''' section = u"== {} ==".format(section_title) try: index = self.content.index(section) + len(section) except ValueError: return None try: next_index = self.content.index("==", index) except ValueError: next_index = len(self.content) return self.content[index:next_index].lstrip("=").strip() @cache def languages(): ''' List all the currently supported language prefixes (usually ISO language code). Can be inputted to `set_lang` to change the Mediawiki that `wikipedia` requests results from. Returns: dict of <prefix>: <local_lang_name> pairs. To get just a list of prefixes, use `wikipedia.languages().keys()`. ''' response = _wiki_request({ 'meta': 'siteinfo', 'siprop': 'languages' }) languages = response['query']['languages'] return { lang['code']: lang['*'] for lang in languages } def donate(): ''' Open up the Wikimedia donate page in your favorite browser. ''' import webbrowser webbrowser.open('https://donate.wikimedia.org/w/index.php?title=Special:FundraiserLandingPage', new=2) def _wiki_request(params): ''' Make a request to the Wikipedia API using the given search parameters. Returns a parsed dict of the JSON response. ''' global RATE_LIMIT_LAST_CALL global USER_AGENT params['format'] = 'json' if not 'action' in params: params['action'] = 'query' headers = { 'User-Agent': USER_AGENT } if RATE_LIMIT and RATE_LIMIT_LAST_CALL and \ RATE_LIMIT_LAST_CALL + RATE_LIMIT_MIN_WAIT > datetime.now(): # it hasn't been long enough since the last API call # so wait until we're in the clear to make the request wait_time = (RATE_LIMIT_LAST_CALL + RATE_LIMIT_MIN_WAIT) - datetime.now() time.sleep(int(wait_time.total_seconds())) r = requests.get(API_URL, params=params, headers=headers) if RATE_LIMIT: RATE_LIMIT_LAST_CALL = datetime.now() return r.json()
goldsmith/Wikipedia
wikipedia/wikipedia.py
set_rate_limiting
python
def set_rate_limiting(rate_limit, min_wait=timedelta(milliseconds=50)): ''' Enable or disable rate limiting on requests to the Mediawiki servers. If rate limiting is not enabled, under some circumstances (depending on load on Wikipedia, the number of requests you and other `wikipedia` users are making, and other factors), Wikipedia may return an HTTP timeout error. Enabling rate limiting generally prevents that issue, but please note that HTTPTimeoutError still might be raised. Arguments: * rate_limit - (Boolean) whether to enable rate limiting or not Keyword arguments: * min_wait - if rate limiting is enabled, `min_wait` is a timedelta describing the minimum time to wait before requests. Defaults to timedelta(milliseconds=50) ''' global RATE_LIMIT global RATE_LIMIT_MIN_WAIT global RATE_LIMIT_LAST_CALL RATE_LIMIT = rate_limit if not rate_limit: RATE_LIMIT_MIN_WAIT = None else: RATE_LIMIT_MIN_WAIT = min_wait RATE_LIMIT_LAST_CALL = None
Enable or disable rate limiting on requests to the Mediawiki servers. If rate limiting is not enabled, under some circumstances (depending on load on Wikipedia, the number of requests you and other `wikipedia` users are making, and other factors), Wikipedia may return an HTTP timeout error. Enabling rate limiting generally prevents that issue, but please note that HTTPTimeoutError still might be raised. Arguments: * rate_limit - (Boolean) whether to enable rate limiting or not Keyword arguments: * min_wait - if rate limiting is enabled, `min_wait` is a timedelta describing the minimum time to wait before requests. Defaults to timedelta(milliseconds=50)
train
https://github.com/goldsmith/Wikipedia/blob/2065c568502b19b8634241b47fd96930d1bf948d/wikipedia/wikipedia.py#L50-L79
null
from __future__ import unicode_literals import requests import time from bs4 import BeautifulSoup from datetime import datetime, timedelta from decimal import Decimal from .exceptions import ( PageError, DisambiguationError, RedirectError, HTTPTimeoutError, WikipediaException, ODD_ERROR_MESSAGE) from .util import cache, stdout_encode, debug import re API_URL = 'http://en.wikipedia.org/w/api.php' RATE_LIMIT = False RATE_LIMIT_MIN_WAIT = None RATE_LIMIT_LAST_CALL = None USER_AGENT = 'wikipedia (https://github.com/goldsmith/Wikipedia/)' def set_lang(prefix): ''' Change the language of the API being requested. Set `prefix` to one of the two letter prefixes found on the `list of all Wikipedias <http://meta.wikimedia.org/wiki/List_of_Wikipedias>`_. After setting the language, the cache for ``search``, ``suggest``, and ``summary`` will be cleared. .. note:: Make sure you search for page titles in the language that you have set. ''' global API_URL API_URL = 'http://' + prefix.lower() + '.wikipedia.org/w/api.php' for cached_func in (search, suggest, summary): cached_func.clear_cache() def set_user_agent(user_agent_string): ''' Set the User-Agent string to be used for all requests. Arguments: * user_agent_string - (string) a string specifying the User-Agent header ''' global USER_AGENT USER_AGENT = user_agent_string @cache def search(query, results=10, suggestion=False): ''' Do a Wikipedia search for `query`. Keyword arguments: * results - the maxmimum number of results returned * suggestion - if True, return results and suggestion (if any) in a tuple ''' search_params = { 'list': 'search', 'srprop': '', 'srlimit': results, 'limit': results, 'srsearch': query } if suggestion: search_params['srinfo'] = 'suggestion' raw_results = _wiki_request(search_params) if 'error' in raw_results: if raw_results['error']['info'] in ('HTTP request timed out.', 'Pool queue is full'): raise HTTPTimeoutError(query) else: raise WikipediaException(raw_results['error']['info']) search_results = (d['title'] for d in raw_results['query']['search']) if suggestion: if raw_results['query'].get('searchinfo'): return list(search_results), raw_results['query']['searchinfo']['suggestion'] else: return list(search_results), None return list(search_results) @cache def geosearch(latitude, longitude, title=None, results=10, radius=1000): ''' Do a wikipedia geo search for `latitude` and `longitude` using HTTP API described in http://www.mediawiki.org/wiki/Extension:GeoData Arguments: * latitude (float or decimal.Decimal) * longitude (float or decimal.Decimal) Keyword arguments: * title - The title of an article to search for * results - the maximum number of results returned * radius - Search radius in meters. The value must be between 10 and 10000 ''' search_params = { 'list': 'geosearch', 'gsradius': radius, 'gscoord': '{0}|{1}'.format(latitude, longitude), 'gslimit': results } if title: search_params['titles'] = title raw_results = _wiki_request(search_params) if 'error' in raw_results: if raw_results['error']['info'] in ('HTTP request timed out.', 'Pool queue is full'): raise HTTPTimeoutError('{0}|{1}'.format(latitude, longitude)) else: raise WikipediaException(raw_results['error']['info']) search_pages = raw_results['query'].get('pages', None) if search_pages: search_results = (v['title'] for k, v in search_pages.items() if k != '-1') else: search_results = (d['title'] for d in raw_results['query']['geosearch']) return list(search_results) @cache def suggest(query): ''' Get a Wikipedia search suggestion for `query`. Returns a string or None if no suggestion was found. ''' search_params = { 'list': 'search', 'srinfo': 'suggestion', 'srprop': '', } search_params['srsearch'] = query raw_result = _wiki_request(search_params) if raw_result['query'].get('searchinfo'): return raw_result['query']['searchinfo']['suggestion'] return None def random(pages=1): ''' Get a list of random Wikipedia article titles. .. note:: Random only gets articles from namespace 0, meaning no Category, User talk, or other meta-Wikipedia pages. Keyword arguments: * pages - the number of random pages returned (max of 10) ''' #http://en.wikipedia.org/w/api.php?action=query&list=random&rnlimit=5000&format=jsonfm query_params = { 'list': 'random', 'rnnamespace': 0, 'rnlimit': pages, } request = _wiki_request(query_params) titles = [page['title'] for page in request['query']['random']] if len(titles) == 1: return titles[0] return titles @cache def summary(title, sentences=0, chars=0, auto_suggest=True, redirect=True): ''' Plain text summary of the page. .. note:: This is a convenience wrapper - auto_suggest and redirect are enabled by default Keyword arguments: * sentences - if set, return the first `sentences` sentences (can be no greater than 10). * chars - if set, return only the first `chars` characters (actual text returned may be slightly longer). * auto_suggest - let Wikipedia find a valid page title for the query * redirect - allow redirection without raising RedirectError ''' # use auto_suggest and redirect to get the correct article # also, use page's error checking to raise DisambiguationError if necessary page_info = page(title, auto_suggest=auto_suggest, redirect=redirect) title = page_info.title pageid = page_info.pageid query_params = { 'prop': 'extracts', 'explaintext': '', 'titles': title } if sentences: query_params['exsentences'] = sentences elif chars: query_params['exchars'] = chars else: query_params['exintro'] = '' request = _wiki_request(query_params) summary = request['query']['pages'][pageid]['extract'] return summary def page(title=None, pageid=None, auto_suggest=True, redirect=True, preload=False): ''' Get a WikipediaPage object for the page with title `title` or the pageid `pageid` (mutually exclusive). Keyword arguments: * title - the title of the page to load * pageid - the numeric pageid of the page to load * auto_suggest - let Wikipedia find a valid page title for the query * redirect - allow redirection without raising RedirectError * preload - load content, summary, images, references, and links during initialization ''' if title is not None: if auto_suggest: results, suggestion = search(title, results=1, suggestion=True) try: title = suggestion or results[0] except IndexError: # if there is no suggestion or search results, the page doesn't exist raise PageError(title) return WikipediaPage(title, redirect=redirect, preload=preload) elif pageid is not None: return WikipediaPage(pageid=pageid, preload=preload) else: raise ValueError("Either a title or a pageid must be specified") class WikipediaPage(object): ''' Contains data from a Wikipedia page. Uses property methods to filter data from the raw HTML. ''' def __init__(self, title=None, pageid=None, redirect=True, preload=False, original_title=''): if title is not None: self.title = title self.original_title = original_title or title elif pageid is not None: self.pageid = pageid else: raise ValueError("Either a title or a pageid must be specified") self.__load(redirect=redirect, preload=preload) if preload: for prop in ('content', 'summary', 'images', 'references', 'links', 'sections'): getattr(self, prop) def __repr__(self): return stdout_encode(u'<WikipediaPage \'{}\'>'.format(self.title)) def __eq__(self, other): try: return ( self.pageid == other.pageid and self.title == other.title and self.url == other.url ) except: return False def __load(self, redirect=True, preload=False): ''' Load basic information from Wikipedia. Confirm that page exists and is not a disambiguation/redirect. Does not need to be called manually, should be called automatically during __init__. ''' query_params = { 'prop': 'info|pageprops', 'inprop': 'url', 'ppprop': 'disambiguation', 'redirects': '', } if not getattr(self, 'pageid', None): query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) query = request['query'] pageid = list(query['pages'].keys())[0] page = query['pages'][pageid] # missing is present if the page is missing if 'missing' in page: if hasattr(self, 'title'): raise PageError(self.title) else: raise PageError(pageid=self.pageid) # same thing for redirect, except it shows up in query instead of page for # whatever silly reason elif 'redirects' in query: if redirect: redirects = query['redirects'][0] if 'normalized' in query: normalized = query['normalized'][0] assert normalized['from'] == self.title, ODD_ERROR_MESSAGE from_title = normalized['to'] else: from_title = self.title assert redirects['from'] == from_title, ODD_ERROR_MESSAGE # change the title and reload the whole object self.__init__(redirects['to'], redirect=redirect, preload=preload) else: raise RedirectError(getattr(self, 'title', page['title'])) # since we only asked for disambiguation in ppprop, # if a pageprop is returned, # then the page must be a disambiguation page elif 'pageprops' in page: query_params = { 'prop': 'revisions', 'rvprop': 'content', 'rvparse': '', 'rvlimit': 1 } if hasattr(self, 'pageid'): query_params['pageids'] = self.pageid else: query_params['titles'] = self.title request = _wiki_request(query_params) html = request['query']['pages'][pageid]['revisions'][0]['*'] lis = BeautifulSoup(html, 'html.parser').find_all('li') filtered_lis = [li for li in lis if not 'tocsection' in ''.join(li.get('class', []))] may_refer_to = [li.a.get_text() for li in filtered_lis if li.a] raise DisambiguationError(getattr(self, 'title', page['title']), may_refer_to) else: self.pageid = pageid self.title = page['title'] self.url = page['fullurl'] def __continued_query(self, query_params): ''' Based on https://www.mediawiki.org/wiki/API:Query#Continuing_queries ''' query_params.update(self.__title_query_param) last_continue = {} prop = query_params.get('prop', None) while True: params = query_params.copy() params.update(last_continue) request = _wiki_request(params) if 'query' not in request: break pages = request['query']['pages'] if 'generator' in query_params: for datum in pages.values(): # in python 3.3+: "yield from pages.values()" yield datum else: for datum in pages[self.pageid][prop]: yield datum if 'continue' not in request: break last_continue = request['continue'] @property def __title_query_param(self): if getattr(self, 'title', None) is not None: return {'titles': self.title} else: return {'pageids': self.pageid} def html(self): ''' Get full page HTML. .. warning:: This can get pretty slow on long pages. ''' if not getattr(self, '_html', False): query_params = { 'prop': 'revisions', 'rvprop': 'content', 'rvlimit': 1, 'rvparse': '', 'titles': self.title } request = _wiki_request(query_params) self._html = request['query']['pages'][self.pageid]['revisions'][0]['*'] return self._html @property def content(self): ''' Plain text content of the page, excluding images, tables, and other data. ''' if not getattr(self, '_content', False): query_params = { 'prop': 'extracts|revisions', 'explaintext': '', 'rvprop': 'ids' } if not getattr(self, 'title', None) is None: query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) self._content = request['query']['pages'][self.pageid]['extract'] self._revision_id = request['query']['pages'][self.pageid]['revisions'][0]['revid'] self._parent_id = request['query']['pages'][self.pageid]['revisions'][0]['parentid'] return self._content @property def revision_id(self): ''' Revision ID of the page. The revision ID is a number that uniquely identifies the current version of the page. It can be used to create the permalink or for other direct API calls. See `Help:Page history <http://en.wikipedia.org/wiki/Wikipedia:Revision>`_ for more information. ''' if not getattr(self, '_revid', False): # fetch the content (side effect is loading the revid) self.content return self._revision_id @property def parent_id(self): ''' Revision ID of the parent version of the current revision of this page. See ``revision_id`` for more information. ''' if not getattr(self, '_parentid', False): # fetch the content (side effect is loading the revid) self.content return self._parent_id @property def summary(self): ''' Plain text summary of the page. ''' if not getattr(self, '_summary', False): query_params = { 'prop': 'extracts', 'explaintext': '', 'exintro': '', } if not getattr(self, 'title', None) is None: query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) self._summary = request['query']['pages'][self.pageid]['extract'] return self._summary @property def images(self): ''' List of URLs of images on the page. ''' if not getattr(self, '_images', False): self._images = [ page['imageinfo'][0]['url'] for page in self.__continued_query({ 'generator': 'images', 'gimlimit': 'max', 'prop': 'imageinfo', 'iiprop': 'url', }) if 'imageinfo' in page ] return self._images @property def coordinates(self): ''' Tuple of Decimals in the form of (lat, lon) or None ''' if not getattr(self, '_coordinates', False): query_params = { 'prop': 'coordinates', 'colimit': 'max', 'titles': self.title, } request = _wiki_request(query_params) if 'query' in request: coordinates = request['query']['pages'][self.pageid]['coordinates'] self._coordinates = (Decimal(coordinates[0]['lat']), Decimal(coordinates[0]['lon'])) else: self._coordinates = None return self._coordinates @property def references(self): ''' List of URLs of external links on a page. May include external links within page that aren't technically cited anywhere. ''' if not getattr(self, '_references', False): def add_protocol(url): return url if url.startswith('http') else 'http:' + url self._references = [ add_protocol(link['*']) for link in self.__continued_query({ 'prop': 'extlinks', 'ellimit': 'max' }) ] return self._references @property def links(self): ''' List of titles of Wikipedia page links on a page. .. note:: Only includes articles from namespace 0, meaning no Category, User talk, or other meta-Wikipedia pages. ''' if not getattr(self, '_links', False): self._links = [ link['title'] for link in self.__continued_query({ 'prop': 'links', 'plnamespace': 0, 'pllimit': 'max' }) ] return self._links @property def categories(self): ''' List of categories of a page. ''' if not getattr(self, '_categories', False): self._categories = [re.sub(r'^Category:', '', x) for x in [link['title'] for link in self.__continued_query({ 'prop': 'categories', 'cllimit': 'max' }) ]] return self._categories @property def sections(self): ''' List of section titles from the table of contents on the page. ''' if not getattr(self, '_sections', False): query_params = { 'action': 'parse', 'prop': 'sections', } query_params.update(self.__title_query_param) request = _wiki_request(query_params) self._sections = [section['line'] for section in request['parse']['sections']] return self._sections def section(self, section_title): ''' Get the plain text content of a section from `self.sections`. Returns None if `section_title` isn't found, otherwise returns a whitespace stripped string. This is a convenience method that wraps self.content. .. warning:: Calling `section` on a section that has subheadings will NOT return the full text of all of the subsections. It only gets the text between `section_title` and the next subheading, which is often empty. ''' section = u"== {} ==".format(section_title) try: index = self.content.index(section) + len(section) except ValueError: return None try: next_index = self.content.index("==", index) except ValueError: next_index = len(self.content) return self.content[index:next_index].lstrip("=").strip() @cache def languages(): ''' List all the currently supported language prefixes (usually ISO language code). Can be inputted to `set_lang` to change the Mediawiki that `wikipedia` requests results from. Returns: dict of <prefix>: <local_lang_name> pairs. To get just a list of prefixes, use `wikipedia.languages().keys()`. ''' response = _wiki_request({ 'meta': 'siteinfo', 'siprop': 'languages' }) languages = response['query']['languages'] return { lang['code']: lang['*'] for lang in languages } def donate(): ''' Open up the Wikimedia donate page in your favorite browser. ''' import webbrowser webbrowser.open('https://donate.wikimedia.org/w/index.php?title=Special:FundraiserLandingPage', new=2) def _wiki_request(params): ''' Make a request to the Wikipedia API using the given search parameters. Returns a parsed dict of the JSON response. ''' global RATE_LIMIT_LAST_CALL global USER_AGENT params['format'] = 'json' if not 'action' in params: params['action'] = 'query' headers = { 'User-Agent': USER_AGENT } if RATE_LIMIT and RATE_LIMIT_LAST_CALL and \ RATE_LIMIT_LAST_CALL + RATE_LIMIT_MIN_WAIT > datetime.now(): # it hasn't been long enough since the last API call # so wait until we're in the clear to make the request wait_time = (RATE_LIMIT_LAST_CALL + RATE_LIMIT_MIN_WAIT) - datetime.now() time.sleep(int(wait_time.total_seconds())) r = requests.get(API_URL, params=params, headers=headers) if RATE_LIMIT: RATE_LIMIT_LAST_CALL = datetime.now() return r.json()
goldsmith/Wikipedia
wikipedia/wikipedia.py
search
python
def search(query, results=10, suggestion=False): ''' Do a Wikipedia search for `query`. Keyword arguments: * results - the maxmimum number of results returned * suggestion - if True, return results and suggestion (if any) in a tuple ''' search_params = { 'list': 'search', 'srprop': '', 'srlimit': results, 'limit': results, 'srsearch': query } if suggestion: search_params['srinfo'] = 'suggestion' raw_results = _wiki_request(search_params) if 'error' in raw_results: if raw_results['error']['info'] in ('HTTP request timed out.', 'Pool queue is full'): raise HTTPTimeoutError(query) else: raise WikipediaException(raw_results['error']['info']) search_results = (d['title'] for d in raw_results['query']['search']) if suggestion: if raw_results['query'].get('searchinfo'): return list(search_results), raw_results['query']['searchinfo']['suggestion'] else: return list(search_results), None return list(search_results)
Do a Wikipedia search for `query`. Keyword arguments: * results - the maxmimum number of results returned * suggestion - if True, return results and suggestion (if any) in a tuple
train
https://github.com/goldsmith/Wikipedia/blob/2065c568502b19b8634241b47fd96930d1bf948d/wikipedia/wikipedia.py#L83-L119
[ "def _wiki_request(params):\n '''\n Make a request to the Wikipedia API using the given search parameters.\n Returns a parsed dict of the JSON response.\n '''\n global RATE_LIMIT_LAST_CALL\n global USER_AGENT\n\n params['format'] = 'json'\n if not 'action' in params:\n params['action'] = 'query'\n\n headers = {\n 'User-Agent': USER_AGENT\n }\n\n if RATE_LIMIT and RATE_LIMIT_LAST_CALL and \\\n RATE_LIMIT_LAST_CALL + RATE_LIMIT_MIN_WAIT > datetime.now():\n\n # it hasn't been long enough since the last API call\n # so wait until we're in the clear to make the request\n\n wait_time = (RATE_LIMIT_LAST_CALL + RATE_LIMIT_MIN_WAIT) - datetime.now()\n time.sleep(int(wait_time.total_seconds()))\n\n r = requests.get(API_URL, params=params, headers=headers)\n\n if RATE_LIMIT:\n RATE_LIMIT_LAST_CALL = datetime.now()\n\n return r.json()\n" ]
from __future__ import unicode_literals import requests import time from bs4 import BeautifulSoup from datetime import datetime, timedelta from decimal import Decimal from .exceptions import ( PageError, DisambiguationError, RedirectError, HTTPTimeoutError, WikipediaException, ODD_ERROR_MESSAGE) from .util import cache, stdout_encode, debug import re API_URL = 'http://en.wikipedia.org/w/api.php' RATE_LIMIT = False RATE_LIMIT_MIN_WAIT = None RATE_LIMIT_LAST_CALL = None USER_AGENT = 'wikipedia (https://github.com/goldsmith/Wikipedia/)' def set_lang(prefix): ''' Change the language of the API being requested. Set `prefix` to one of the two letter prefixes found on the `list of all Wikipedias <http://meta.wikimedia.org/wiki/List_of_Wikipedias>`_. After setting the language, the cache for ``search``, ``suggest``, and ``summary`` will be cleared. .. note:: Make sure you search for page titles in the language that you have set. ''' global API_URL API_URL = 'http://' + prefix.lower() + '.wikipedia.org/w/api.php' for cached_func in (search, suggest, summary): cached_func.clear_cache() def set_user_agent(user_agent_string): ''' Set the User-Agent string to be used for all requests. Arguments: * user_agent_string - (string) a string specifying the User-Agent header ''' global USER_AGENT USER_AGENT = user_agent_string def set_rate_limiting(rate_limit, min_wait=timedelta(milliseconds=50)): ''' Enable or disable rate limiting on requests to the Mediawiki servers. If rate limiting is not enabled, under some circumstances (depending on load on Wikipedia, the number of requests you and other `wikipedia` users are making, and other factors), Wikipedia may return an HTTP timeout error. Enabling rate limiting generally prevents that issue, but please note that HTTPTimeoutError still might be raised. Arguments: * rate_limit - (Boolean) whether to enable rate limiting or not Keyword arguments: * min_wait - if rate limiting is enabled, `min_wait` is a timedelta describing the minimum time to wait before requests. Defaults to timedelta(milliseconds=50) ''' global RATE_LIMIT global RATE_LIMIT_MIN_WAIT global RATE_LIMIT_LAST_CALL RATE_LIMIT = rate_limit if not rate_limit: RATE_LIMIT_MIN_WAIT = None else: RATE_LIMIT_MIN_WAIT = min_wait RATE_LIMIT_LAST_CALL = None @cache @cache def geosearch(latitude, longitude, title=None, results=10, radius=1000): ''' Do a wikipedia geo search for `latitude` and `longitude` using HTTP API described in http://www.mediawiki.org/wiki/Extension:GeoData Arguments: * latitude (float or decimal.Decimal) * longitude (float or decimal.Decimal) Keyword arguments: * title - The title of an article to search for * results - the maximum number of results returned * radius - Search radius in meters. The value must be between 10 and 10000 ''' search_params = { 'list': 'geosearch', 'gsradius': radius, 'gscoord': '{0}|{1}'.format(latitude, longitude), 'gslimit': results } if title: search_params['titles'] = title raw_results = _wiki_request(search_params) if 'error' in raw_results: if raw_results['error']['info'] in ('HTTP request timed out.', 'Pool queue is full'): raise HTTPTimeoutError('{0}|{1}'.format(latitude, longitude)) else: raise WikipediaException(raw_results['error']['info']) search_pages = raw_results['query'].get('pages', None) if search_pages: search_results = (v['title'] for k, v in search_pages.items() if k != '-1') else: search_results = (d['title'] for d in raw_results['query']['geosearch']) return list(search_results) @cache def suggest(query): ''' Get a Wikipedia search suggestion for `query`. Returns a string or None if no suggestion was found. ''' search_params = { 'list': 'search', 'srinfo': 'suggestion', 'srprop': '', } search_params['srsearch'] = query raw_result = _wiki_request(search_params) if raw_result['query'].get('searchinfo'): return raw_result['query']['searchinfo']['suggestion'] return None def random(pages=1): ''' Get a list of random Wikipedia article titles. .. note:: Random only gets articles from namespace 0, meaning no Category, User talk, or other meta-Wikipedia pages. Keyword arguments: * pages - the number of random pages returned (max of 10) ''' #http://en.wikipedia.org/w/api.php?action=query&list=random&rnlimit=5000&format=jsonfm query_params = { 'list': 'random', 'rnnamespace': 0, 'rnlimit': pages, } request = _wiki_request(query_params) titles = [page['title'] for page in request['query']['random']] if len(titles) == 1: return titles[0] return titles @cache def summary(title, sentences=0, chars=0, auto_suggest=True, redirect=True): ''' Plain text summary of the page. .. note:: This is a convenience wrapper - auto_suggest and redirect are enabled by default Keyword arguments: * sentences - if set, return the first `sentences` sentences (can be no greater than 10). * chars - if set, return only the first `chars` characters (actual text returned may be slightly longer). * auto_suggest - let Wikipedia find a valid page title for the query * redirect - allow redirection without raising RedirectError ''' # use auto_suggest and redirect to get the correct article # also, use page's error checking to raise DisambiguationError if necessary page_info = page(title, auto_suggest=auto_suggest, redirect=redirect) title = page_info.title pageid = page_info.pageid query_params = { 'prop': 'extracts', 'explaintext': '', 'titles': title } if sentences: query_params['exsentences'] = sentences elif chars: query_params['exchars'] = chars else: query_params['exintro'] = '' request = _wiki_request(query_params) summary = request['query']['pages'][pageid]['extract'] return summary def page(title=None, pageid=None, auto_suggest=True, redirect=True, preload=False): ''' Get a WikipediaPage object for the page with title `title` or the pageid `pageid` (mutually exclusive). Keyword arguments: * title - the title of the page to load * pageid - the numeric pageid of the page to load * auto_suggest - let Wikipedia find a valid page title for the query * redirect - allow redirection without raising RedirectError * preload - load content, summary, images, references, and links during initialization ''' if title is not None: if auto_suggest: results, suggestion = search(title, results=1, suggestion=True) try: title = suggestion or results[0] except IndexError: # if there is no suggestion or search results, the page doesn't exist raise PageError(title) return WikipediaPage(title, redirect=redirect, preload=preload) elif pageid is not None: return WikipediaPage(pageid=pageid, preload=preload) else: raise ValueError("Either a title or a pageid must be specified") class WikipediaPage(object): ''' Contains data from a Wikipedia page. Uses property methods to filter data from the raw HTML. ''' def __init__(self, title=None, pageid=None, redirect=True, preload=False, original_title=''): if title is not None: self.title = title self.original_title = original_title or title elif pageid is not None: self.pageid = pageid else: raise ValueError("Either a title or a pageid must be specified") self.__load(redirect=redirect, preload=preload) if preload: for prop in ('content', 'summary', 'images', 'references', 'links', 'sections'): getattr(self, prop) def __repr__(self): return stdout_encode(u'<WikipediaPage \'{}\'>'.format(self.title)) def __eq__(self, other): try: return ( self.pageid == other.pageid and self.title == other.title and self.url == other.url ) except: return False def __load(self, redirect=True, preload=False): ''' Load basic information from Wikipedia. Confirm that page exists and is not a disambiguation/redirect. Does not need to be called manually, should be called automatically during __init__. ''' query_params = { 'prop': 'info|pageprops', 'inprop': 'url', 'ppprop': 'disambiguation', 'redirects': '', } if not getattr(self, 'pageid', None): query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) query = request['query'] pageid = list(query['pages'].keys())[0] page = query['pages'][pageid] # missing is present if the page is missing if 'missing' in page: if hasattr(self, 'title'): raise PageError(self.title) else: raise PageError(pageid=self.pageid) # same thing for redirect, except it shows up in query instead of page for # whatever silly reason elif 'redirects' in query: if redirect: redirects = query['redirects'][0] if 'normalized' in query: normalized = query['normalized'][0] assert normalized['from'] == self.title, ODD_ERROR_MESSAGE from_title = normalized['to'] else: from_title = self.title assert redirects['from'] == from_title, ODD_ERROR_MESSAGE # change the title and reload the whole object self.__init__(redirects['to'], redirect=redirect, preload=preload) else: raise RedirectError(getattr(self, 'title', page['title'])) # since we only asked for disambiguation in ppprop, # if a pageprop is returned, # then the page must be a disambiguation page elif 'pageprops' in page: query_params = { 'prop': 'revisions', 'rvprop': 'content', 'rvparse': '', 'rvlimit': 1 } if hasattr(self, 'pageid'): query_params['pageids'] = self.pageid else: query_params['titles'] = self.title request = _wiki_request(query_params) html = request['query']['pages'][pageid]['revisions'][0]['*'] lis = BeautifulSoup(html, 'html.parser').find_all('li') filtered_lis = [li for li in lis if not 'tocsection' in ''.join(li.get('class', []))] may_refer_to = [li.a.get_text() for li in filtered_lis if li.a] raise DisambiguationError(getattr(self, 'title', page['title']), may_refer_to) else: self.pageid = pageid self.title = page['title'] self.url = page['fullurl'] def __continued_query(self, query_params): ''' Based on https://www.mediawiki.org/wiki/API:Query#Continuing_queries ''' query_params.update(self.__title_query_param) last_continue = {} prop = query_params.get('prop', None) while True: params = query_params.copy() params.update(last_continue) request = _wiki_request(params) if 'query' not in request: break pages = request['query']['pages'] if 'generator' in query_params: for datum in pages.values(): # in python 3.3+: "yield from pages.values()" yield datum else: for datum in pages[self.pageid][prop]: yield datum if 'continue' not in request: break last_continue = request['continue'] @property def __title_query_param(self): if getattr(self, 'title', None) is not None: return {'titles': self.title} else: return {'pageids': self.pageid} def html(self): ''' Get full page HTML. .. warning:: This can get pretty slow on long pages. ''' if not getattr(self, '_html', False): query_params = { 'prop': 'revisions', 'rvprop': 'content', 'rvlimit': 1, 'rvparse': '', 'titles': self.title } request = _wiki_request(query_params) self._html = request['query']['pages'][self.pageid]['revisions'][0]['*'] return self._html @property def content(self): ''' Plain text content of the page, excluding images, tables, and other data. ''' if not getattr(self, '_content', False): query_params = { 'prop': 'extracts|revisions', 'explaintext': '', 'rvprop': 'ids' } if not getattr(self, 'title', None) is None: query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) self._content = request['query']['pages'][self.pageid]['extract'] self._revision_id = request['query']['pages'][self.pageid]['revisions'][0]['revid'] self._parent_id = request['query']['pages'][self.pageid]['revisions'][0]['parentid'] return self._content @property def revision_id(self): ''' Revision ID of the page. The revision ID is a number that uniquely identifies the current version of the page. It can be used to create the permalink or for other direct API calls. See `Help:Page history <http://en.wikipedia.org/wiki/Wikipedia:Revision>`_ for more information. ''' if not getattr(self, '_revid', False): # fetch the content (side effect is loading the revid) self.content return self._revision_id @property def parent_id(self): ''' Revision ID of the parent version of the current revision of this page. See ``revision_id`` for more information. ''' if not getattr(self, '_parentid', False): # fetch the content (side effect is loading the revid) self.content return self._parent_id @property def summary(self): ''' Plain text summary of the page. ''' if not getattr(self, '_summary', False): query_params = { 'prop': 'extracts', 'explaintext': '', 'exintro': '', } if not getattr(self, 'title', None) is None: query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) self._summary = request['query']['pages'][self.pageid]['extract'] return self._summary @property def images(self): ''' List of URLs of images on the page. ''' if not getattr(self, '_images', False): self._images = [ page['imageinfo'][0]['url'] for page in self.__continued_query({ 'generator': 'images', 'gimlimit': 'max', 'prop': 'imageinfo', 'iiprop': 'url', }) if 'imageinfo' in page ] return self._images @property def coordinates(self): ''' Tuple of Decimals in the form of (lat, lon) or None ''' if not getattr(self, '_coordinates', False): query_params = { 'prop': 'coordinates', 'colimit': 'max', 'titles': self.title, } request = _wiki_request(query_params) if 'query' in request: coordinates = request['query']['pages'][self.pageid]['coordinates'] self._coordinates = (Decimal(coordinates[0]['lat']), Decimal(coordinates[0]['lon'])) else: self._coordinates = None return self._coordinates @property def references(self): ''' List of URLs of external links on a page. May include external links within page that aren't technically cited anywhere. ''' if not getattr(self, '_references', False): def add_protocol(url): return url if url.startswith('http') else 'http:' + url self._references = [ add_protocol(link['*']) for link in self.__continued_query({ 'prop': 'extlinks', 'ellimit': 'max' }) ] return self._references @property def links(self): ''' List of titles of Wikipedia page links on a page. .. note:: Only includes articles from namespace 0, meaning no Category, User talk, or other meta-Wikipedia pages. ''' if not getattr(self, '_links', False): self._links = [ link['title'] for link in self.__continued_query({ 'prop': 'links', 'plnamespace': 0, 'pllimit': 'max' }) ] return self._links @property def categories(self): ''' List of categories of a page. ''' if not getattr(self, '_categories', False): self._categories = [re.sub(r'^Category:', '', x) for x in [link['title'] for link in self.__continued_query({ 'prop': 'categories', 'cllimit': 'max' }) ]] return self._categories @property def sections(self): ''' List of section titles from the table of contents on the page. ''' if not getattr(self, '_sections', False): query_params = { 'action': 'parse', 'prop': 'sections', } query_params.update(self.__title_query_param) request = _wiki_request(query_params) self._sections = [section['line'] for section in request['parse']['sections']] return self._sections def section(self, section_title): ''' Get the plain text content of a section from `self.sections`. Returns None if `section_title` isn't found, otherwise returns a whitespace stripped string. This is a convenience method that wraps self.content. .. warning:: Calling `section` on a section that has subheadings will NOT return the full text of all of the subsections. It only gets the text between `section_title` and the next subheading, which is often empty. ''' section = u"== {} ==".format(section_title) try: index = self.content.index(section) + len(section) except ValueError: return None try: next_index = self.content.index("==", index) except ValueError: next_index = len(self.content) return self.content[index:next_index].lstrip("=").strip() @cache def languages(): ''' List all the currently supported language prefixes (usually ISO language code). Can be inputted to `set_lang` to change the Mediawiki that `wikipedia` requests results from. Returns: dict of <prefix>: <local_lang_name> pairs. To get just a list of prefixes, use `wikipedia.languages().keys()`. ''' response = _wiki_request({ 'meta': 'siteinfo', 'siprop': 'languages' }) languages = response['query']['languages'] return { lang['code']: lang['*'] for lang in languages } def donate(): ''' Open up the Wikimedia donate page in your favorite browser. ''' import webbrowser webbrowser.open('https://donate.wikimedia.org/w/index.php?title=Special:FundraiserLandingPage', new=2) def _wiki_request(params): ''' Make a request to the Wikipedia API using the given search parameters. Returns a parsed dict of the JSON response. ''' global RATE_LIMIT_LAST_CALL global USER_AGENT params['format'] = 'json' if not 'action' in params: params['action'] = 'query' headers = { 'User-Agent': USER_AGENT } if RATE_LIMIT and RATE_LIMIT_LAST_CALL and \ RATE_LIMIT_LAST_CALL + RATE_LIMIT_MIN_WAIT > datetime.now(): # it hasn't been long enough since the last API call # so wait until we're in the clear to make the request wait_time = (RATE_LIMIT_LAST_CALL + RATE_LIMIT_MIN_WAIT) - datetime.now() time.sleep(int(wait_time.total_seconds())) r = requests.get(API_URL, params=params, headers=headers) if RATE_LIMIT: RATE_LIMIT_LAST_CALL = datetime.now() return r.json()
goldsmith/Wikipedia
wikipedia/wikipedia.py
geosearch
python
def geosearch(latitude, longitude, title=None, results=10, radius=1000): ''' Do a wikipedia geo search for `latitude` and `longitude` using HTTP API described in http://www.mediawiki.org/wiki/Extension:GeoData Arguments: * latitude (float or decimal.Decimal) * longitude (float or decimal.Decimal) Keyword arguments: * title - The title of an article to search for * results - the maximum number of results returned * radius - Search radius in meters. The value must be between 10 and 10000 ''' search_params = { 'list': 'geosearch', 'gsradius': radius, 'gscoord': '{0}|{1}'.format(latitude, longitude), 'gslimit': results } if title: search_params['titles'] = title raw_results = _wiki_request(search_params) if 'error' in raw_results: if raw_results['error']['info'] in ('HTTP request timed out.', 'Pool queue is full'): raise HTTPTimeoutError('{0}|{1}'.format(latitude, longitude)) else: raise WikipediaException(raw_results['error']['info']) search_pages = raw_results['query'].get('pages', None) if search_pages: search_results = (v['title'] for k, v in search_pages.items() if k != '-1') else: search_results = (d['title'] for d in raw_results['query']['geosearch']) return list(search_results)
Do a wikipedia geo search for `latitude` and `longitude` using HTTP API described in http://www.mediawiki.org/wiki/Extension:GeoData Arguments: * latitude (float or decimal.Decimal) * longitude (float or decimal.Decimal) Keyword arguments: * title - The title of an article to search for * results - the maximum number of results returned * radius - Search radius in meters. The value must be between 10 and 10000
train
https://github.com/goldsmith/Wikipedia/blob/2065c568502b19b8634241b47fd96930d1bf948d/wikipedia/wikipedia.py#L123-L163
[ "def _wiki_request(params):\n '''\n Make a request to the Wikipedia API using the given search parameters.\n Returns a parsed dict of the JSON response.\n '''\n global RATE_LIMIT_LAST_CALL\n global USER_AGENT\n\n params['format'] = 'json'\n if not 'action' in params:\n params['action'] = 'query'\n\n headers = {\n 'User-Agent': USER_AGENT\n }\n\n if RATE_LIMIT and RATE_LIMIT_LAST_CALL and \\\n RATE_LIMIT_LAST_CALL + RATE_LIMIT_MIN_WAIT > datetime.now():\n\n # it hasn't been long enough since the last API call\n # so wait until we're in the clear to make the request\n\n wait_time = (RATE_LIMIT_LAST_CALL + RATE_LIMIT_MIN_WAIT) - datetime.now()\n time.sleep(int(wait_time.total_seconds()))\n\n r = requests.get(API_URL, params=params, headers=headers)\n\n if RATE_LIMIT:\n RATE_LIMIT_LAST_CALL = datetime.now()\n\n return r.json()\n" ]
from __future__ import unicode_literals import requests import time from bs4 import BeautifulSoup from datetime import datetime, timedelta from decimal import Decimal from .exceptions import ( PageError, DisambiguationError, RedirectError, HTTPTimeoutError, WikipediaException, ODD_ERROR_MESSAGE) from .util import cache, stdout_encode, debug import re API_URL = 'http://en.wikipedia.org/w/api.php' RATE_LIMIT = False RATE_LIMIT_MIN_WAIT = None RATE_LIMIT_LAST_CALL = None USER_AGENT = 'wikipedia (https://github.com/goldsmith/Wikipedia/)' def set_lang(prefix): ''' Change the language of the API being requested. Set `prefix` to one of the two letter prefixes found on the `list of all Wikipedias <http://meta.wikimedia.org/wiki/List_of_Wikipedias>`_. After setting the language, the cache for ``search``, ``suggest``, and ``summary`` will be cleared. .. note:: Make sure you search for page titles in the language that you have set. ''' global API_URL API_URL = 'http://' + prefix.lower() + '.wikipedia.org/w/api.php' for cached_func in (search, suggest, summary): cached_func.clear_cache() def set_user_agent(user_agent_string): ''' Set the User-Agent string to be used for all requests. Arguments: * user_agent_string - (string) a string specifying the User-Agent header ''' global USER_AGENT USER_AGENT = user_agent_string def set_rate_limiting(rate_limit, min_wait=timedelta(milliseconds=50)): ''' Enable or disable rate limiting on requests to the Mediawiki servers. If rate limiting is not enabled, under some circumstances (depending on load on Wikipedia, the number of requests you and other `wikipedia` users are making, and other factors), Wikipedia may return an HTTP timeout error. Enabling rate limiting generally prevents that issue, but please note that HTTPTimeoutError still might be raised. Arguments: * rate_limit - (Boolean) whether to enable rate limiting or not Keyword arguments: * min_wait - if rate limiting is enabled, `min_wait` is a timedelta describing the minimum time to wait before requests. Defaults to timedelta(milliseconds=50) ''' global RATE_LIMIT global RATE_LIMIT_MIN_WAIT global RATE_LIMIT_LAST_CALL RATE_LIMIT = rate_limit if not rate_limit: RATE_LIMIT_MIN_WAIT = None else: RATE_LIMIT_MIN_WAIT = min_wait RATE_LIMIT_LAST_CALL = None @cache def search(query, results=10, suggestion=False): ''' Do a Wikipedia search for `query`. Keyword arguments: * results - the maxmimum number of results returned * suggestion - if True, return results and suggestion (if any) in a tuple ''' search_params = { 'list': 'search', 'srprop': '', 'srlimit': results, 'limit': results, 'srsearch': query } if suggestion: search_params['srinfo'] = 'suggestion' raw_results = _wiki_request(search_params) if 'error' in raw_results: if raw_results['error']['info'] in ('HTTP request timed out.', 'Pool queue is full'): raise HTTPTimeoutError(query) else: raise WikipediaException(raw_results['error']['info']) search_results = (d['title'] for d in raw_results['query']['search']) if suggestion: if raw_results['query'].get('searchinfo'): return list(search_results), raw_results['query']['searchinfo']['suggestion'] else: return list(search_results), None return list(search_results) @cache @cache def suggest(query): ''' Get a Wikipedia search suggestion for `query`. Returns a string or None if no suggestion was found. ''' search_params = { 'list': 'search', 'srinfo': 'suggestion', 'srprop': '', } search_params['srsearch'] = query raw_result = _wiki_request(search_params) if raw_result['query'].get('searchinfo'): return raw_result['query']['searchinfo']['suggestion'] return None def random(pages=1): ''' Get a list of random Wikipedia article titles. .. note:: Random only gets articles from namespace 0, meaning no Category, User talk, or other meta-Wikipedia pages. Keyword arguments: * pages - the number of random pages returned (max of 10) ''' #http://en.wikipedia.org/w/api.php?action=query&list=random&rnlimit=5000&format=jsonfm query_params = { 'list': 'random', 'rnnamespace': 0, 'rnlimit': pages, } request = _wiki_request(query_params) titles = [page['title'] for page in request['query']['random']] if len(titles) == 1: return titles[0] return titles @cache def summary(title, sentences=0, chars=0, auto_suggest=True, redirect=True): ''' Plain text summary of the page. .. note:: This is a convenience wrapper - auto_suggest and redirect are enabled by default Keyword arguments: * sentences - if set, return the first `sentences` sentences (can be no greater than 10). * chars - if set, return only the first `chars` characters (actual text returned may be slightly longer). * auto_suggest - let Wikipedia find a valid page title for the query * redirect - allow redirection without raising RedirectError ''' # use auto_suggest and redirect to get the correct article # also, use page's error checking to raise DisambiguationError if necessary page_info = page(title, auto_suggest=auto_suggest, redirect=redirect) title = page_info.title pageid = page_info.pageid query_params = { 'prop': 'extracts', 'explaintext': '', 'titles': title } if sentences: query_params['exsentences'] = sentences elif chars: query_params['exchars'] = chars else: query_params['exintro'] = '' request = _wiki_request(query_params) summary = request['query']['pages'][pageid]['extract'] return summary def page(title=None, pageid=None, auto_suggest=True, redirect=True, preload=False): ''' Get a WikipediaPage object for the page with title `title` or the pageid `pageid` (mutually exclusive). Keyword arguments: * title - the title of the page to load * pageid - the numeric pageid of the page to load * auto_suggest - let Wikipedia find a valid page title for the query * redirect - allow redirection without raising RedirectError * preload - load content, summary, images, references, and links during initialization ''' if title is not None: if auto_suggest: results, suggestion = search(title, results=1, suggestion=True) try: title = suggestion or results[0] except IndexError: # if there is no suggestion or search results, the page doesn't exist raise PageError(title) return WikipediaPage(title, redirect=redirect, preload=preload) elif pageid is not None: return WikipediaPage(pageid=pageid, preload=preload) else: raise ValueError("Either a title or a pageid must be specified") class WikipediaPage(object): ''' Contains data from a Wikipedia page. Uses property methods to filter data from the raw HTML. ''' def __init__(self, title=None, pageid=None, redirect=True, preload=False, original_title=''): if title is not None: self.title = title self.original_title = original_title or title elif pageid is not None: self.pageid = pageid else: raise ValueError("Either a title or a pageid must be specified") self.__load(redirect=redirect, preload=preload) if preload: for prop in ('content', 'summary', 'images', 'references', 'links', 'sections'): getattr(self, prop) def __repr__(self): return stdout_encode(u'<WikipediaPage \'{}\'>'.format(self.title)) def __eq__(self, other): try: return ( self.pageid == other.pageid and self.title == other.title and self.url == other.url ) except: return False def __load(self, redirect=True, preload=False): ''' Load basic information from Wikipedia. Confirm that page exists and is not a disambiguation/redirect. Does not need to be called manually, should be called automatically during __init__. ''' query_params = { 'prop': 'info|pageprops', 'inprop': 'url', 'ppprop': 'disambiguation', 'redirects': '', } if not getattr(self, 'pageid', None): query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) query = request['query'] pageid = list(query['pages'].keys())[0] page = query['pages'][pageid] # missing is present if the page is missing if 'missing' in page: if hasattr(self, 'title'): raise PageError(self.title) else: raise PageError(pageid=self.pageid) # same thing for redirect, except it shows up in query instead of page for # whatever silly reason elif 'redirects' in query: if redirect: redirects = query['redirects'][0] if 'normalized' in query: normalized = query['normalized'][0] assert normalized['from'] == self.title, ODD_ERROR_MESSAGE from_title = normalized['to'] else: from_title = self.title assert redirects['from'] == from_title, ODD_ERROR_MESSAGE # change the title and reload the whole object self.__init__(redirects['to'], redirect=redirect, preload=preload) else: raise RedirectError(getattr(self, 'title', page['title'])) # since we only asked for disambiguation in ppprop, # if a pageprop is returned, # then the page must be a disambiguation page elif 'pageprops' in page: query_params = { 'prop': 'revisions', 'rvprop': 'content', 'rvparse': '', 'rvlimit': 1 } if hasattr(self, 'pageid'): query_params['pageids'] = self.pageid else: query_params['titles'] = self.title request = _wiki_request(query_params) html = request['query']['pages'][pageid]['revisions'][0]['*'] lis = BeautifulSoup(html, 'html.parser').find_all('li') filtered_lis = [li for li in lis if not 'tocsection' in ''.join(li.get('class', []))] may_refer_to = [li.a.get_text() for li in filtered_lis if li.a] raise DisambiguationError(getattr(self, 'title', page['title']), may_refer_to) else: self.pageid = pageid self.title = page['title'] self.url = page['fullurl'] def __continued_query(self, query_params): ''' Based on https://www.mediawiki.org/wiki/API:Query#Continuing_queries ''' query_params.update(self.__title_query_param) last_continue = {} prop = query_params.get('prop', None) while True: params = query_params.copy() params.update(last_continue) request = _wiki_request(params) if 'query' not in request: break pages = request['query']['pages'] if 'generator' in query_params: for datum in pages.values(): # in python 3.3+: "yield from pages.values()" yield datum else: for datum in pages[self.pageid][prop]: yield datum if 'continue' not in request: break last_continue = request['continue'] @property def __title_query_param(self): if getattr(self, 'title', None) is not None: return {'titles': self.title} else: return {'pageids': self.pageid} def html(self): ''' Get full page HTML. .. warning:: This can get pretty slow on long pages. ''' if not getattr(self, '_html', False): query_params = { 'prop': 'revisions', 'rvprop': 'content', 'rvlimit': 1, 'rvparse': '', 'titles': self.title } request = _wiki_request(query_params) self._html = request['query']['pages'][self.pageid]['revisions'][0]['*'] return self._html @property def content(self): ''' Plain text content of the page, excluding images, tables, and other data. ''' if not getattr(self, '_content', False): query_params = { 'prop': 'extracts|revisions', 'explaintext': '', 'rvprop': 'ids' } if not getattr(self, 'title', None) is None: query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) self._content = request['query']['pages'][self.pageid]['extract'] self._revision_id = request['query']['pages'][self.pageid]['revisions'][0]['revid'] self._parent_id = request['query']['pages'][self.pageid]['revisions'][0]['parentid'] return self._content @property def revision_id(self): ''' Revision ID of the page. The revision ID is a number that uniquely identifies the current version of the page. It can be used to create the permalink or for other direct API calls. See `Help:Page history <http://en.wikipedia.org/wiki/Wikipedia:Revision>`_ for more information. ''' if not getattr(self, '_revid', False): # fetch the content (side effect is loading the revid) self.content return self._revision_id @property def parent_id(self): ''' Revision ID of the parent version of the current revision of this page. See ``revision_id`` for more information. ''' if not getattr(self, '_parentid', False): # fetch the content (side effect is loading the revid) self.content return self._parent_id @property def summary(self): ''' Plain text summary of the page. ''' if not getattr(self, '_summary', False): query_params = { 'prop': 'extracts', 'explaintext': '', 'exintro': '', } if not getattr(self, 'title', None) is None: query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) self._summary = request['query']['pages'][self.pageid]['extract'] return self._summary @property def images(self): ''' List of URLs of images on the page. ''' if not getattr(self, '_images', False): self._images = [ page['imageinfo'][0]['url'] for page in self.__continued_query({ 'generator': 'images', 'gimlimit': 'max', 'prop': 'imageinfo', 'iiprop': 'url', }) if 'imageinfo' in page ] return self._images @property def coordinates(self): ''' Tuple of Decimals in the form of (lat, lon) or None ''' if not getattr(self, '_coordinates', False): query_params = { 'prop': 'coordinates', 'colimit': 'max', 'titles': self.title, } request = _wiki_request(query_params) if 'query' in request: coordinates = request['query']['pages'][self.pageid]['coordinates'] self._coordinates = (Decimal(coordinates[0]['lat']), Decimal(coordinates[0]['lon'])) else: self._coordinates = None return self._coordinates @property def references(self): ''' List of URLs of external links on a page. May include external links within page that aren't technically cited anywhere. ''' if not getattr(self, '_references', False): def add_protocol(url): return url if url.startswith('http') else 'http:' + url self._references = [ add_protocol(link['*']) for link in self.__continued_query({ 'prop': 'extlinks', 'ellimit': 'max' }) ] return self._references @property def links(self): ''' List of titles of Wikipedia page links on a page. .. note:: Only includes articles from namespace 0, meaning no Category, User talk, or other meta-Wikipedia pages. ''' if not getattr(self, '_links', False): self._links = [ link['title'] for link in self.__continued_query({ 'prop': 'links', 'plnamespace': 0, 'pllimit': 'max' }) ] return self._links @property def categories(self): ''' List of categories of a page. ''' if not getattr(self, '_categories', False): self._categories = [re.sub(r'^Category:', '', x) for x in [link['title'] for link in self.__continued_query({ 'prop': 'categories', 'cllimit': 'max' }) ]] return self._categories @property def sections(self): ''' List of section titles from the table of contents on the page. ''' if not getattr(self, '_sections', False): query_params = { 'action': 'parse', 'prop': 'sections', } query_params.update(self.__title_query_param) request = _wiki_request(query_params) self._sections = [section['line'] for section in request['parse']['sections']] return self._sections def section(self, section_title): ''' Get the plain text content of a section from `self.sections`. Returns None if `section_title` isn't found, otherwise returns a whitespace stripped string. This is a convenience method that wraps self.content. .. warning:: Calling `section` on a section that has subheadings will NOT return the full text of all of the subsections. It only gets the text between `section_title` and the next subheading, which is often empty. ''' section = u"== {} ==".format(section_title) try: index = self.content.index(section) + len(section) except ValueError: return None try: next_index = self.content.index("==", index) except ValueError: next_index = len(self.content) return self.content[index:next_index].lstrip("=").strip() @cache def languages(): ''' List all the currently supported language prefixes (usually ISO language code). Can be inputted to `set_lang` to change the Mediawiki that `wikipedia` requests results from. Returns: dict of <prefix>: <local_lang_name> pairs. To get just a list of prefixes, use `wikipedia.languages().keys()`. ''' response = _wiki_request({ 'meta': 'siteinfo', 'siprop': 'languages' }) languages = response['query']['languages'] return { lang['code']: lang['*'] for lang in languages } def donate(): ''' Open up the Wikimedia donate page in your favorite browser. ''' import webbrowser webbrowser.open('https://donate.wikimedia.org/w/index.php?title=Special:FundraiserLandingPage', new=2) def _wiki_request(params): ''' Make a request to the Wikipedia API using the given search parameters. Returns a parsed dict of the JSON response. ''' global RATE_LIMIT_LAST_CALL global USER_AGENT params['format'] = 'json' if not 'action' in params: params['action'] = 'query' headers = { 'User-Agent': USER_AGENT } if RATE_LIMIT and RATE_LIMIT_LAST_CALL and \ RATE_LIMIT_LAST_CALL + RATE_LIMIT_MIN_WAIT > datetime.now(): # it hasn't been long enough since the last API call # so wait until we're in the clear to make the request wait_time = (RATE_LIMIT_LAST_CALL + RATE_LIMIT_MIN_WAIT) - datetime.now() time.sleep(int(wait_time.total_seconds())) r = requests.get(API_URL, params=params, headers=headers) if RATE_LIMIT: RATE_LIMIT_LAST_CALL = datetime.now() return r.json()
goldsmith/Wikipedia
wikipedia/wikipedia.py
suggest
python
def suggest(query): ''' Get a Wikipedia search suggestion for `query`. Returns a string or None if no suggestion was found. ''' search_params = { 'list': 'search', 'srinfo': 'suggestion', 'srprop': '', } search_params['srsearch'] = query raw_result = _wiki_request(search_params) if raw_result['query'].get('searchinfo'): return raw_result['query']['searchinfo']['suggestion'] return None
Get a Wikipedia search suggestion for `query`. Returns a string or None if no suggestion was found.
train
https://github.com/goldsmith/Wikipedia/blob/2065c568502b19b8634241b47fd96930d1bf948d/wikipedia/wikipedia.py#L167-L185
[ "def _wiki_request(params):\n '''\n Make a request to the Wikipedia API using the given search parameters.\n Returns a parsed dict of the JSON response.\n '''\n global RATE_LIMIT_LAST_CALL\n global USER_AGENT\n\n params['format'] = 'json'\n if not 'action' in params:\n params['action'] = 'query'\n\n headers = {\n 'User-Agent': USER_AGENT\n }\n\n if RATE_LIMIT and RATE_LIMIT_LAST_CALL and \\\n RATE_LIMIT_LAST_CALL + RATE_LIMIT_MIN_WAIT > datetime.now():\n\n # it hasn't been long enough since the last API call\n # so wait until we're in the clear to make the request\n\n wait_time = (RATE_LIMIT_LAST_CALL + RATE_LIMIT_MIN_WAIT) - datetime.now()\n time.sleep(int(wait_time.total_seconds()))\n\n r = requests.get(API_URL, params=params, headers=headers)\n\n if RATE_LIMIT:\n RATE_LIMIT_LAST_CALL = datetime.now()\n\n return r.json()\n" ]
from __future__ import unicode_literals import requests import time from bs4 import BeautifulSoup from datetime import datetime, timedelta from decimal import Decimal from .exceptions import ( PageError, DisambiguationError, RedirectError, HTTPTimeoutError, WikipediaException, ODD_ERROR_MESSAGE) from .util import cache, stdout_encode, debug import re API_URL = 'http://en.wikipedia.org/w/api.php' RATE_LIMIT = False RATE_LIMIT_MIN_WAIT = None RATE_LIMIT_LAST_CALL = None USER_AGENT = 'wikipedia (https://github.com/goldsmith/Wikipedia/)' def set_lang(prefix): ''' Change the language of the API being requested. Set `prefix` to one of the two letter prefixes found on the `list of all Wikipedias <http://meta.wikimedia.org/wiki/List_of_Wikipedias>`_. After setting the language, the cache for ``search``, ``suggest``, and ``summary`` will be cleared. .. note:: Make sure you search for page titles in the language that you have set. ''' global API_URL API_URL = 'http://' + prefix.lower() + '.wikipedia.org/w/api.php' for cached_func in (search, suggest, summary): cached_func.clear_cache() def set_user_agent(user_agent_string): ''' Set the User-Agent string to be used for all requests. Arguments: * user_agent_string - (string) a string specifying the User-Agent header ''' global USER_AGENT USER_AGENT = user_agent_string def set_rate_limiting(rate_limit, min_wait=timedelta(milliseconds=50)): ''' Enable or disable rate limiting on requests to the Mediawiki servers. If rate limiting is not enabled, under some circumstances (depending on load on Wikipedia, the number of requests you and other `wikipedia` users are making, and other factors), Wikipedia may return an HTTP timeout error. Enabling rate limiting generally prevents that issue, but please note that HTTPTimeoutError still might be raised. Arguments: * rate_limit - (Boolean) whether to enable rate limiting or not Keyword arguments: * min_wait - if rate limiting is enabled, `min_wait` is a timedelta describing the minimum time to wait before requests. Defaults to timedelta(milliseconds=50) ''' global RATE_LIMIT global RATE_LIMIT_MIN_WAIT global RATE_LIMIT_LAST_CALL RATE_LIMIT = rate_limit if not rate_limit: RATE_LIMIT_MIN_WAIT = None else: RATE_LIMIT_MIN_WAIT = min_wait RATE_LIMIT_LAST_CALL = None @cache def search(query, results=10, suggestion=False): ''' Do a Wikipedia search for `query`. Keyword arguments: * results - the maxmimum number of results returned * suggestion - if True, return results and suggestion (if any) in a tuple ''' search_params = { 'list': 'search', 'srprop': '', 'srlimit': results, 'limit': results, 'srsearch': query } if suggestion: search_params['srinfo'] = 'suggestion' raw_results = _wiki_request(search_params) if 'error' in raw_results: if raw_results['error']['info'] in ('HTTP request timed out.', 'Pool queue is full'): raise HTTPTimeoutError(query) else: raise WikipediaException(raw_results['error']['info']) search_results = (d['title'] for d in raw_results['query']['search']) if suggestion: if raw_results['query'].get('searchinfo'): return list(search_results), raw_results['query']['searchinfo']['suggestion'] else: return list(search_results), None return list(search_results) @cache def geosearch(latitude, longitude, title=None, results=10, radius=1000): ''' Do a wikipedia geo search for `latitude` and `longitude` using HTTP API described in http://www.mediawiki.org/wiki/Extension:GeoData Arguments: * latitude (float or decimal.Decimal) * longitude (float or decimal.Decimal) Keyword arguments: * title - The title of an article to search for * results - the maximum number of results returned * radius - Search radius in meters. The value must be between 10 and 10000 ''' search_params = { 'list': 'geosearch', 'gsradius': radius, 'gscoord': '{0}|{1}'.format(latitude, longitude), 'gslimit': results } if title: search_params['titles'] = title raw_results = _wiki_request(search_params) if 'error' in raw_results: if raw_results['error']['info'] in ('HTTP request timed out.', 'Pool queue is full'): raise HTTPTimeoutError('{0}|{1}'.format(latitude, longitude)) else: raise WikipediaException(raw_results['error']['info']) search_pages = raw_results['query'].get('pages', None) if search_pages: search_results = (v['title'] for k, v in search_pages.items() if k != '-1') else: search_results = (d['title'] for d in raw_results['query']['geosearch']) return list(search_results) @cache def random(pages=1): ''' Get a list of random Wikipedia article titles. .. note:: Random only gets articles from namespace 0, meaning no Category, User talk, or other meta-Wikipedia pages. Keyword arguments: * pages - the number of random pages returned (max of 10) ''' #http://en.wikipedia.org/w/api.php?action=query&list=random&rnlimit=5000&format=jsonfm query_params = { 'list': 'random', 'rnnamespace': 0, 'rnlimit': pages, } request = _wiki_request(query_params) titles = [page['title'] for page in request['query']['random']] if len(titles) == 1: return titles[0] return titles @cache def summary(title, sentences=0, chars=0, auto_suggest=True, redirect=True): ''' Plain text summary of the page. .. note:: This is a convenience wrapper - auto_suggest and redirect are enabled by default Keyword arguments: * sentences - if set, return the first `sentences` sentences (can be no greater than 10). * chars - if set, return only the first `chars` characters (actual text returned may be slightly longer). * auto_suggest - let Wikipedia find a valid page title for the query * redirect - allow redirection without raising RedirectError ''' # use auto_suggest and redirect to get the correct article # also, use page's error checking to raise DisambiguationError if necessary page_info = page(title, auto_suggest=auto_suggest, redirect=redirect) title = page_info.title pageid = page_info.pageid query_params = { 'prop': 'extracts', 'explaintext': '', 'titles': title } if sentences: query_params['exsentences'] = sentences elif chars: query_params['exchars'] = chars else: query_params['exintro'] = '' request = _wiki_request(query_params) summary = request['query']['pages'][pageid]['extract'] return summary def page(title=None, pageid=None, auto_suggest=True, redirect=True, preload=False): ''' Get a WikipediaPage object for the page with title `title` or the pageid `pageid` (mutually exclusive). Keyword arguments: * title - the title of the page to load * pageid - the numeric pageid of the page to load * auto_suggest - let Wikipedia find a valid page title for the query * redirect - allow redirection without raising RedirectError * preload - load content, summary, images, references, and links during initialization ''' if title is not None: if auto_suggest: results, suggestion = search(title, results=1, suggestion=True) try: title = suggestion or results[0] except IndexError: # if there is no suggestion or search results, the page doesn't exist raise PageError(title) return WikipediaPage(title, redirect=redirect, preload=preload) elif pageid is not None: return WikipediaPage(pageid=pageid, preload=preload) else: raise ValueError("Either a title or a pageid must be specified") class WikipediaPage(object): ''' Contains data from a Wikipedia page. Uses property methods to filter data from the raw HTML. ''' def __init__(self, title=None, pageid=None, redirect=True, preload=False, original_title=''): if title is not None: self.title = title self.original_title = original_title or title elif pageid is not None: self.pageid = pageid else: raise ValueError("Either a title or a pageid must be specified") self.__load(redirect=redirect, preload=preload) if preload: for prop in ('content', 'summary', 'images', 'references', 'links', 'sections'): getattr(self, prop) def __repr__(self): return stdout_encode(u'<WikipediaPage \'{}\'>'.format(self.title)) def __eq__(self, other): try: return ( self.pageid == other.pageid and self.title == other.title and self.url == other.url ) except: return False def __load(self, redirect=True, preload=False): ''' Load basic information from Wikipedia. Confirm that page exists and is not a disambiguation/redirect. Does not need to be called manually, should be called automatically during __init__. ''' query_params = { 'prop': 'info|pageprops', 'inprop': 'url', 'ppprop': 'disambiguation', 'redirects': '', } if not getattr(self, 'pageid', None): query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) query = request['query'] pageid = list(query['pages'].keys())[0] page = query['pages'][pageid] # missing is present if the page is missing if 'missing' in page: if hasattr(self, 'title'): raise PageError(self.title) else: raise PageError(pageid=self.pageid) # same thing for redirect, except it shows up in query instead of page for # whatever silly reason elif 'redirects' in query: if redirect: redirects = query['redirects'][0] if 'normalized' in query: normalized = query['normalized'][0] assert normalized['from'] == self.title, ODD_ERROR_MESSAGE from_title = normalized['to'] else: from_title = self.title assert redirects['from'] == from_title, ODD_ERROR_MESSAGE # change the title and reload the whole object self.__init__(redirects['to'], redirect=redirect, preload=preload) else: raise RedirectError(getattr(self, 'title', page['title'])) # since we only asked for disambiguation in ppprop, # if a pageprop is returned, # then the page must be a disambiguation page elif 'pageprops' in page: query_params = { 'prop': 'revisions', 'rvprop': 'content', 'rvparse': '', 'rvlimit': 1 } if hasattr(self, 'pageid'): query_params['pageids'] = self.pageid else: query_params['titles'] = self.title request = _wiki_request(query_params) html = request['query']['pages'][pageid]['revisions'][0]['*'] lis = BeautifulSoup(html, 'html.parser').find_all('li') filtered_lis = [li for li in lis if not 'tocsection' in ''.join(li.get('class', []))] may_refer_to = [li.a.get_text() for li in filtered_lis if li.a] raise DisambiguationError(getattr(self, 'title', page['title']), may_refer_to) else: self.pageid = pageid self.title = page['title'] self.url = page['fullurl'] def __continued_query(self, query_params): ''' Based on https://www.mediawiki.org/wiki/API:Query#Continuing_queries ''' query_params.update(self.__title_query_param) last_continue = {} prop = query_params.get('prop', None) while True: params = query_params.copy() params.update(last_continue) request = _wiki_request(params) if 'query' not in request: break pages = request['query']['pages'] if 'generator' in query_params: for datum in pages.values(): # in python 3.3+: "yield from pages.values()" yield datum else: for datum in pages[self.pageid][prop]: yield datum if 'continue' not in request: break last_continue = request['continue'] @property def __title_query_param(self): if getattr(self, 'title', None) is not None: return {'titles': self.title} else: return {'pageids': self.pageid} def html(self): ''' Get full page HTML. .. warning:: This can get pretty slow on long pages. ''' if not getattr(self, '_html', False): query_params = { 'prop': 'revisions', 'rvprop': 'content', 'rvlimit': 1, 'rvparse': '', 'titles': self.title } request = _wiki_request(query_params) self._html = request['query']['pages'][self.pageid]['revisions'][0]['*'] return self._html @property def content(self): ''' Plain text content of the page, excluding images, tables, and other data. ''' if not getattr(self, '_content', False): query_params = { 'prop': 'extracts|revisions', 'explaintext': '', 'rvprop': 'ids' } if not getattr(self, 'title', None) is None: query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) self._content = request['query']['pages'][self.pageid]['extract'] self._revision_id = request['query']['pages'][self.pageid]['revisions'][0]['revid'] self._parent_id = request['query']['pages'][self.pageid]['revisions'][0]['parentid'] return self._content @property def revision_id(self): ''' Revision ID of the page. The revision ID is a number that uniquely identifies the current version of the page. It can be used to create the permalink or for other direct API calls. See `Help:Page history <http://en.wikipedia.org/wiki/Wikipedia:Revision>`_ for more information. ''' if not getattr(self, '_revid', False): # fetch the content (side effect is loading the revid) self.content return self._revision_id @property def parent_id(self): ''' Revision ID of the parent version of the current revision of this page. See ``revision_id`` for more information. ''' if not getattr(self, '_parentid', False): # fetch the content (side effect is loading the revid) self.content return self._parent_id @property def summary(self): ''' Plain text summary of the page. ''' if not getattr(self, '_summary', False): query_params = { 'prop': 'extracts', 'explaintext': '', 'exintro': '', } if not getattr(self, 'title', None) is None: query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) self._summary = request['query']['pages'][self.pageid]['extract'] return self._summary @property def images(self): ''' List of URLs of images on the page. ''' if not getattr(self, '_images', False): self._images = [ page['imageinfo'][0]['url'] for page in self.__continued_query({ 'generator': 'images', 'gimlimit': 'max', 'prop': 'imageinfo', 'iiprop': 'url', }) if 'imageinfo' in page ] return self._images @property def coordinates(self): ''' Tuple of Decimals in the form of (lat, lon) or None ''' if not getattr(self, '_coordinates', False): query_params = { 'prop': 'coordinates', 'colimit': 'max', 'titles': self.title, } request = _wiki_request(query_params) if 'query' in request: coordinates = request['query']['pages'][self.pageid]['coordinates'] self._coordinates = (Decimal(coordinates[0]['lat']), Decimal(coordinates[0]['lon'])) else: self._coordinates = None return self._coordinates @property def references(self): ''' List of URLs of external links on a page. May include external links within page that aren't technically cited anywhere. ''' if not getattr(self, '_references', False): def add_protocol(url): return url if url.startswith('http') else 'http:' + url self._references = [ add_protocol(link['*']) for link in self.__continued_query({ 'prop': 'extlinks', 'ellimit': 'max' }) ] return self._references @property def links(self): ''' List of titles of Wikipedia page links on a page. .. note:: Only includes articles from namespace 0, meaning no Category, User talk, or other meta-Wikipedia pages. ''' if not getattr(self, '_links', False): self._links = [ link['title'] for link in self.__continued_query({ 'prop': 'links', 'plnamespace': 0, 'pllimit': 'max' }) ] return self._links @property def categories(self): ''' List of categories of a page. ''' if not getattr(self, '_categories', False): self._categories = [re.sub(r'^Category:', '', x) for x in [link['title'] for link in self.__continued_query({ 'prop': 'categories', 'cllimit': 'max' }) ]] return self._categories @property def sections(self): ''' List of section titles from the table of contents on the page. ''' if not getattr(self, '_sections', False): query_params = { 'action': 'parse', 'prop': 'sections', } query_params.update(self.__title_query_param) request = _wiki_request(query_params) self._sections = [section['line'] for section in request['parse']['sections']] return self._sections def section(self, section_title): ''' Get the plain text content of a section from `self.sections`. Returns None if `section_title` isn't found, otherwise returns a whitespace stripped string. This is a convenience method that wraps self.content. .. warning:: Calling `section` on a section that has subheadings will NOT return the full text of all of the subsections. It only gets the text between `section_title` and the next subheading, which is often empty. ''' section = u"== {} ==".format(section_title) try: index = self.content.index(section) + len(section) except ValueError: return None try: next_index = self.content.index("==", index) except ValueError: next_index = len(self.content) return self.content[index:next_index].lstrip("=").strip() @cache def languages(): ''' List all the currently supported language prefixes (usually ISO language code). Can be inputted to `set_lang` to change the Mediawiki that `wikipedia` requests results from. Returns: dict of <prefix>: <local_lang_name> pairs. To get just a list of prefixes, use `wikipedia.languages().keys()`. ''' response = _wiki_request({ 'meta': 'siteinfo', 'siprop': 'languages' }) languages = response['query']['languages'] return { lang['code']: lang['*'] for lang in languages } def donate(): ''' Open up the Wikimedia donate page in your favorite browser. ''' import webbrowser webbrowser.open('https://donate.wikimedia.org/w/index.php?title=Special:FundraiserLandingPage', new=2) def _wiki_request(params): ''' Make a request to the Wikipedia API using the given search parameters. Returns a parsed dict of the JSON response. ''' global RATE_LIMIT_LAST_CALL global USER_AGENT params['format'] = 'json' if not 'action' in params: params['action'] = 'query' headers = { 'User-Agent': USER_AGENT } if RATE_LIMIT and RATE_LIMIT_LAST_CALL and \ RATE_LIMIT_LAST_CALL + RATE_LIMIT_MIN_WAIT > datetime.now(): # it hasn't been long enough since the last API call # so wait until we're in the clear to make the request wait_time = (RATE_LIMIT_LAST_CALL + RATE_LIMIT_MIN_WAIT) - datetime.now() time.sleep(int(wait_time.total_seconds())) r = requests.get(API_URL, params=params, headers=headers) if RATE_LIMIT: RATE_LIMIT_LAST_CALL = datetime.now() return r.json()
goldsmith/Wikipedia
wikipedia/wikipedia.py
random
python
def random(pages=1): ''' Get a list of random Wikipedia article titles. .. note:: Random only gets articles from namespace 0, meaning no Category, User talk, or other meta-Wikipedia pages. Keyword arguments: * pages - the number of random pages returned (max of 10) ''' #http://en.wikipedia.org/w/api.php?action=query&list=random&rnlimit=5000&format=jsonfm query_params = { 'list': 'random', 'rnnamespace': 0, 'rnlimit': pages, } request = _wiki_request(query_params) titles = [page['title'] for page in request['query']['random']] if len(titles) == 1: return titles[0] return titles
Get a list of random Wikipedia article titles. .. note:: Random only gets articles from namespace 0, meaning no Category, User talk, or other meta-Wikipedia pages. Keyword arguments: * pages - the number of random pages returned (max of 10)
train
https://github.com/goldsmith/Wikipedia/blob/2065c568502b19b8634241b47fd96930d1bf948d/wikipedia/wikipedia.py#L188-L211
[ "def _wiki_request(params):\n '''\n Make a request to the Wikipedia API using the given search parameters.\n Returns a parsed dict of the JSON response.\n '''\n global RATE_LIMIT_LAST_CALL\n global USER_AGENT\n\n params['format'] = 'json'\n if not 'action' in params:\n params['action'] = 'query'\n\n headers = {\n 'User-Agent': USER_AGENT\n }\n\n if RATE_LIMIT and RATE_LIMIT_LAST_CALL and \\\n RATE_LIMIT_LAST_CALL + RATE_LIMIT_MIN_WAIT > datetime.now():\n\n # it hasn't been long enough since the last API call\n # so wait until we're in the clear to make the request\n\n wait_time = (RATE_LIMIT_LAST_CALL + RATE_LIMIT_MIN_WAIT) - datetime.now()\n time.sleep(int(wait_time.total_seconds()))\n\n r = requests.get(API_URL, params=params, headers=headers)\n\n if RATE_LIMIT:\n RATE_LIMIT_LAST_CALL = datetime.now()\n\n return r.json()\n" ]
from __future__ import unicode_literals import requests import time from bs4 import BeautifulSoup from datetime import datetime, timedelta from decimal import Decimal from .exceptions import ( PageError, DisambiguationError, RedirectError, HTTPTimeoutError, WikipediaException, ODD_ERROR_MESSAGE) from .util import cache, stdout_encode, debug import re API_URL = 'http://en.wikipedia.org/w/api.php' RATE_LIMIT = False RATE_LIMIT_MIN_WAIT = None RATE_LIMIT_LAST_CALL = None USER_AGENT = 'wikipedia (https://github.com/goldsmith/Wikipedia/)' def set_lang(prefix): ''' Change the language of the API being requested. Set `prefix` to one of the two letter prefixes found on the `list of all Wikipedias <http://meta.wikimedia.org/wiki/List_of_Wikipedias>`_. After setting the language, the cache for ``search``, ``suggest``, and ``summary`` will be cleared. .. note:: Make sure you search for page titles in the language that you have set. ''' global API_URL API_URL = 'http://' + prefix.lower() + '.wikipedia.org/w/api.php' for cached_func in (search, suggest, summary): cached_func.clear_cache() def set_user_agent(user_agent_string): ''' Set the User-Agent string to be used for all requests. Arguments: * user_agent_string - (string) a string specifying the User-Agent header ''' global USER_AGENT USER_AGENT = user_agent_string def set_rate_limiting(rate_limit, min_wait=timedelta(milliseconds=50)): ''' Enable or disable rate limiting on requests to the Mediawiki servers. If rate limiting is not enabled, under some circumstances (depending on load on Wikipedia, the number of requests you and other `wikipedia` users are making, and other factors), Wikipedia may return an HTTP timeout error. Enabling rate limiting generally prevents that issue, but please note that HTTPTimeoutError still might be raised. Arguments: * rate_limit - (Boolean) whether to enable rate limiting or not Keyword arguments: * min_wait - if rate limiting is enabled, `min_wait` is a timedelta describing the minimum time to wait before requests. Defaults to timedelta(milliseconds=50) ''' global RATE_LIMIT global RATE_LIMIT_MIN_WAIT global RATE_LIMIT_LAST_CALL RATE_LIMIT = rate_limit if not rate_limit: RATE_LIMIT_MIN_WAIT = None else: RATE_LIMIT_MIN_WAIT = min_wait RATE_LIMIT_LAST_CALL = None @cache def search(query, results=10, suggestion=False): ''' Do a Wikipedia search for `query`. Keyword arguments: * results - the maxmimum number of results returned * suggestion - if True, return results and suggestion (if any) in a tuple ''' search_params = { 'list': 'search', 'srprop': '', 'srlimit': results, 'limit': results, 'srsearch': query } if suggestion: search_params['srinfo'] = 'suggestion' raw_results = _wiki_request(search_params) if 'error' in raw_results: if raw_results['error']['info'] in ('HTTP request timed out.', 'Pool queue is full'): raise HTTPTimeoutError(query) else: raise WikipediaException(raw_results['error']['info']) search_results = (d['title'] for d in raw_results['query']['search']) if suggestion: if raw_results['query'].get('searchinfo'): return list(search_results), raw_results['query']['searchinfo']['suggestion'] else: return list(search_results), None return list(search_results) @cache def geosearch(latitude, longitude, title=None, results=10, radius=1000): ''' Do a wikipedia geo search for `latitude` and `longitude` using HTTP API described in http://www.mediawiki.org/wiki/Extension:GeoData Arguments: * latitude (float or decimal.Decimal) * longitude (float or decimal.Decimal) Keyword arguments: * title - The title of an article to search for * results - the maximum number of results returned * radius - Search radius in meters. The value must be between 10 and 10000 ''' search_params = { 'list': 'geosearch', 'gsradius': radius, 'gscoord': '{0}|{1}'.format(latitude, longitude), 'gslimit': results } if title: search_params['titles'] = title raw_results = _wiki_request(search_params) if 'error' in raw_results: if raw_results['error']['info'] in ('HTTP request timed out.', 'Pool queue is full'): raise HTTPTimeoutError('{0}|{1}'.format(latitude, longitude)) else: raise WikipediaException(raw_results['error']['info']) search_pages = raw_results['query'].get('pages', None) if search_pages: search_results = (v['title'] for k, v in search_pages.items() if k != '-1') else: search_results = (d['title'] for d in raw_results['query']['geosearch']) return list(search_results) @cache def suggest(query): ''' Get a Wikipedia search suggestion for `query`. Returns a string or None if no suggestion was found. ''' search_params = { 'list': 'search', 'srinfo': 'suggestion', 'srprop': '', } search_params['srsearch'] = query raw_result = _wiki_request(search_params) if raw_result['query'].get('searchinfo'): return raw_result['query']['searchinfo']['suggestion'] return None @cache def summary(title, sentences=0, chars=0, auto_suggest=True, redirect=True): ''' Plain text summary of the page. .. note:: This is a convenience wrapper - auto_suggest and redirect are enabled by default Keyword arguments: * sentences - if set, return the first `sentences` sentences (can be no greater than 10). * chars - if set, return only the first `chars` characters (actual text returned may be slightly longer). * auto_suggest - let Wikipedia find a valid page title for the query * redirect - allow redirection without raising RedirectError ''' # use auto_suggest and redirect to get the correct article # also, use page's error checking to raise DisambiguationError if necessary page_info = page(title, auto_suggest=auto_suggest, redirect=redirect) title = page_info.title pageid = page_info.pageid query_params = { 'prop': 'extracts', 'explaintext': '', 'titles': title } if sentences: query_params['exsentences'] = sentences elif chars: query_params['exchars'] = chars else: query_params['exintro'] = '' request = _wiki_request(query_params) summary = request['query']['pages'][pageid]['extract'] return summary def page(title=None, pageid=None, auto_suggest=True, redirect=True, preload=False): ''' Get a WikipediaPage object for the page with title `title` or the pageid `pageid` (mutually exclusive). Keyword arguments: * title - the title of the page to load * pageid - the numeric pageid of the page to load * auto_suggest - let Wikipedia find a valid page title for the query * redirect - allow redirection without raising RedirectError * preload - load content, summary, images, references, and links during initialization ''' if title is not None: if auto_suggest: results, suggestion = search(title, results=1, suggestion=True) try: title = suggestion or results[0] except IndexError: # if there is no suggestion or search results, the page doesn't exist raise PageError(title) return WikipediaPage(title, redirect=redirect, preload=preload) elif pageid is not None: return WikipediaPage(pageid=pageid, preload=preload) else: raise ValueError("Either a title or a pageid must be specified") class WikipediaPage(object): ''' Contains data from a Wikipedia page. Uses property methods to filter data from the raw HTML. ''' def __init__(self, title=None, pageid=None, redirect=True, preload=False, original_title=''): if title is not None: self.title = title self.original_title = original_title or title elif pageid is not None: self.pageid = pageid else: raise ValueError("Either a title or a pageid must be specified") self.__load(redirect=redirect, preload=preload) if preload: for prop in ('content', 'summary', 'images', 'references', 'links', 'sections'): getattr(self, prop) def __repr__(self): return stdout_encode(u'<WikipediaPage \'{}\'>'.format(self.title)) def __eq__(self, other): try: return ( self.pageid == other.pageid and self.title == other.title and self.url == other.url ) except: return False def __load(self, redirect=True, preload=False): ''' Load basic information from Wikipedia. Confirm that page exists and is not a disambiguation/redirect. Does not need to be called manually, should be called automatically during __init__. ''' query_params = { 'prop': 'info|pageprops', 'inprop': 'url', 'ppprop': 'disambiguation', 'redirects': '', } if not getattr(self, 'pageid', None): query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) query = request['query'] pageid = list(query['pages'].keys())[0] page = query['pages'][pageid] # missing is present if the page is missing if 'missing' in page: if hasattr(self, 'title'): raise PageError(self.title) else: raise PageError(pageid=self.pageid) # same thing for redirect, except it shows up in query instead of page for # whatever silly reason elif 'redirects' in query: if redirect: redirects = query['redirects'][0] if 'normalized' in query: normalized = query['normalized'][0] assert normalized['from'] == self.title, ODD_ERROR_MESSAGE from_title = normalized['to'] else: from_title = self.title assert redirects['from'] == from_title, ODD_ERROR_MESSAGE # change the title and reload the whole object self.__init__(redirects['to'], redirect=redirect, preload=preload) else: raise RedirectError(getattr(self, 'title', page['title'])) # since we only asked for disambiguation in ppprop, # if a pageprop is returned, # then the page must be a disambiguation page elif 'pageprops' in page: query_params = { 'prop': 'revisions', 'rvprop': 'content', 'rvparse': '', 'rvlimit': 1 } if hasattr(self, 'pageid'): query_params['pageids'] = self.pageid else: query_params['titles'] = self.title request = _wiki_request(query_params) html = request['query']['pages'][pageid]['revisions'][0]['*'] lis = BeautifulSoup(html, 'html.parser').find_all('li') filtered_lis = [li for li in lis if not 'tocsection' in ''.join(li.get('class', []))] may_refer_to = [li.a.get_text() for li in filtered_lis if li.a] raise DisambiguationError(getattr(self, 'title', page['title']), may_refer_to) else: self.pageid = pageid self.title = page['title'] self.url = page['fullurl'] def __continued_query(self, query_params): ''' Based on https://www.mediawiki.org/wiki/API:Query#Continuing_queries ''' query_params.update(self.__title_query_param) last_continue = {} prop = query_params.get('prop', None) while True: params = query_params.copy() params.update(last_continue) request = _wiki_request(params) if 'query' not in request: break pages = request['query']['pages'] if 'generator' in query_params: for datum in pages.values(): # in python 3.3+: "yield from pages.values()" yield datum else: for datum in pages[self.pageid][prop]: yield datum if 'continue' not in request: break last_continue = request['continue'] @property def __title_query_param(self): if getattr(self, 'title', None) is not None: return {'titles': self.title} else: return {'pageids': self.pageid} def html(self): ''' Get full page HTML. .. warning:: This can get pretty slow on long pages. ''' if not getattr(self, '_html', False): query_params = { 'prop': 'revisions', 'rvprop': 'content', 'rvlimit': 1, 'rvparse': '', 'titles': self.title } request = _wiki_request(query_params) self._html = request['query']['pages'][self.pageid]['revisions'][0]['*'] return self._html @property def content(self): ''' Plain text content of the page, excluding images, tables, and other data. ''' if not getattr(self, '_content', False): query_params = { 'prop': 'extracts|revisions', 'explaintext': '', 'rvprop': 'ids' } if not getattr(self, 'title', None) is None: query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) self._content = request['query']['pages'][self.pageid]['extract'] self._revision_id = request['query']['pages'][self.pageid]['revisions'][0]['revid'] self._parent_id = request['query']['pages'][self.pageid]['revisions'][0]['parentid'] return self._content @property def revision_id(self): ''' Revision ID of the page. The revision ID is a number that uniquely identifies the current version of the page. It can be used to create the permalink or for other direct API calls. See `Help:Page history <http://en.wikipedia.org/wiki/Wikipedia:Revision>`_ for more information. ''' if not getattr(self, '_revid', False): # fetch the content (side effect is loading the revid) self.content return self._revision_id @property def parent_id(self): ''' Revision ID of the parent version of the current revision of this page. See ``revision_id`` for more information. ''' if not getattr(self, '_parentid', False): # fetch the content (side effect is loading the revid) self.content return self._parent_id @property def summary(self): ''' Plain text summary of the page. ''' if not getattr(self, '_summary', False): query_params = { 'prop': 'extracts', 'explaintext': '', 'exintro': '', } if not getattr(self, 'title', None) is None: query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) self._summary = request['query']['pages'][self.pageid]['extract'] return self._summary @property def images(self): ''' List of URLs of images on the page. ''' if not getattr(self, '_images', False): self._images = [ page['imageinfo'][0]['url'] for page in self.__continued_query({ 'generator': 'images', 'gimlimit': 'max', 'prop': 'imageinfo', 'iiprop': 'url', }) if 'imageinfo' in page ] return self._images @property def coordinates(self): ''' Tuple of Decimals in the form of (lat, lon) or None ''' if not getattr(self, '_coordinates', False): query_params = { 'prop': 'coordinates', 'colimit': 'max', 'titles': self.title, } request = _wiki_request(query_params) if 'query' in request: coordinates = request['query']['pages'][self.pageid]['coordinates'] self._coordinates = (Decimal(coordinates[0]['lat']), Decimal(coordinates[0]['lon'])) else: self._coordinates = None return self._coordinates @property def references(self): ''' List of URLs of external links on a page. May include external links within page that aren't technically cited anywhere. ''' if not getattr(self, '_references', False): def add_protocol(url): return url if url.startswith('http') else 'http:' + url self._references = [ add_protocol(link['*']) for link in self.__continued_query({ 'prop': 'extlinks', 'ellimit': 'max' }) ] return self._references @property def links(self): ''' List of titles of Wikipedia page links on a page. .. note:: Only includes articles from namespace 0, meaning no Category, User talk, or other meta-Wikipedia pages. ''' if not getattr(self, '_links', False): self._links = [ link['title'] for link in self.__continued_query({ 'prop': 'links', 'plnamespace': 0, 'pllimit': 'max' }) ] return self._links @property def categories(self): ''' List of categories of a page. ''' if not getattr(self, '_categories', False): self._categories = [re.sub(r'^Category:', '', x) for x in [link['title'] for link in self.__continued_query({ 'prop': 'categories', 'cllimit': 'max' }) ]] return self._categories @property def sections(self): ''' List of section titles from the table of contents on the page. ''' if not getattr(self, '_sections', False): query_params = { 'action': 'parse', 'prop': 'sections', } query_params.update(self.__title_query_param) request = _wiki_request(query_params) self._sections = [section['line'] for section in request['parse']['sections']] return self._sections def section(self, section_title): ''' Get the plain text content of a section from `self.sections`. Returns None if `section_title` isn't found, otherwise returns a whitespace stripped string. This is a convenience method that wraps self.content. .. warning:: Calling `section` on a section that has subheadings will NOT return the full text of all of the subsections. It only gets the text between `section_title` and the next subheading, which is often empty. ''' section = u"== {} ==".format(section_title) try: index = self.content.index(section) + len(section) except ValueError: return None try: next_index = self.content.index("==", index) except ValueError: next_index = len(self.content) return self.content[index:next_index].lstrip("=").strip() @cache def languages(): ''' List all the currently supported language prefixes (usually ISO language code). Can be inputted to `set_lang` to change the Mediawiki that `wikipedia` requests results from. Returns: dict of <prefix>: <local_lang_name> pairs. To get just a list of prefixes, use `wikipedia.languages().keys()`. ''' response = _wiki_request({ 'meta': 'siteinfo', 'siprop': 'languages' }) languages = response['query']['languages'] return { lang['code']: lang['*'] for lang in languages } def donate(): ''' Open up the Wikimedia donate page in your favorite browser. ''' import webbrowser webbrowser.open('https://donate.wikimedia.org/w/index.php?title=Special:FundraiserLandingPage', new=2) def _wiki_request(params): ''' Make a request to the Wikipedia API using the given search parameters. Returns a parsed dict of the JSON response. ''' global RATE_LIMIT_LAST_CALL global USER_AGENT params['format'] = 'json' if not 'action' in params: params['action'] = 'query' headers = { 'User-Agent': USER_AGENT } if RATE_LIMIT and RATE_LIMIT_LAST_CALL and \ RATE_LIMIT_LAST_CALL + RATE_LIMIT_MIN_WAIT > datetime.now(): # it hasn't been long enough since the last API call # so wait until we're in the clear to make the request wait_time = (RATE_LIMIT_LAST_CALL + RATE_LIMIT_MIN_WAIT) - datetime.now() time.sleep(int(wait_time.total_seconds())) r = requests.get(API_URL, params=params, headers=headers) if RATE_LIMIT: RATE_LIMIT_LAST_CALL = datetime.now() return r.json()
goldsmith/Wikipedia
wikipedia/wikipedia.py
summary
python
def summary(title, sentences=0, chars=0, auto_suggest=True, redirect=True): ''' Plain text summary of the page. .. note:: This is a convenience wrapper - auto_suggest and redirect are enabled by default Keyword arguments: * sentences - if set, return the first `sentences` sentences (can be no greater than 10). * chars - if set, return only the first `chars` characters (actual text returned may be slightly longer). * auto_suggest - let Wikipedia find a valid page title for the query * redirect - allow redirection without raising RedirectError ''' # use auto_suggest and redirect to get the correct article # also, use page's error checking to raise DisambiguationError if necessary page_info = page(title, auto_suggest=auto_suggest, redirect=redirect) title = page_info.title pageid = page_info.pageid query_params = { 'prop': 'extracts', 'explaintext': '', 'titles': title } if sentences: query_params['exsentences'] = sentences elif chars: query_params['exchars'] = chars else: query_params['exintro'] = '' request = _wiki_request(query_params) summary = request['query']['pages'][pageid]['extract'] return summary
Plain text summary of the page. .. note:: This is a convenience wrapper - auto_suggest and redirect are enabled by default Keyword arguments: * sentences - if set, return the first `sentences` sentences (can be no greater than 10). * chars - if set, return only the first `chars` characters (actual text returned may be slightly longer). * auto_suggest - let Wikipedia find a valid page title for the query * redirect - allow redirection without raising RedirectError
train
https://github.com/goldsmith/Wikipedia/blob/2065c568502b19b8634241b47fd96930d1bf948d/wikipedia/wikipedia.py#L215-L251
[ "def _wiki_request(params):\n '''\n Make a request to the Wikipedia API using the given search parameters.\n Returns a parsed dict of the JSON response.\n '''\n global RATE_LIMIT_LAST_CALL\n global USER_AGENT\n\n params['format'] = 'json'\n if not 'action' in params:\n params['action'] = 'query'\n\n headers = {\n 'User-Agent': USER_AGENT\n }\n\n if RATE_LIMIT and RATE_LIMIT_LAST_CALL and \\\n RATE_LIMIT_LAST_CALL + RATE_LIMIT_MIN_WAIT > datetime.now():\n\n # it hasn't been long enough since the last API call\n # so wait until we're in the clear to make the request\n\n wait_time = (RATE_LIMIT_LAST_CALL + RATE_LIMIT_MIN_WAIT) - datetime.now()\n time.sleep(int(wait_time.total_seconds()))\n\n r = requests.get(API_URL, params=params, headers=headers)\n\n if RATE_LIMIT:\n RATE_LIMIT_LAST_CALL = datetime.now()\n\n return r.json()\n", "def page(title=None, pageid=None, auto_suggest=True, redirect=True, preload=False):\n '''\n Get a WikipediaPage object for the page with title `title` or the pageid\n `pageid` (mutually exclusive).\n\n Keyword arguments:\n\n * title - the title of the page to load\n * pageid - the numeric pageid of the page to load\n * auto_suggest - let Wikipedia find a valid page title for the query\n * redirect - allow redirection without raising RedirectError\n * preload - load content, summary, images, references, and links during initialization\n '''\n\n if title is not None:\n if auto_suggest:\n results, suggestion = search(title, results=1, suggestion=True)\n try:\n title = suggestion or results[0]\n except IndexError:\n # if there is no suggestion or search results, the page doesn't exist\n raise PageError(title)\n return WikipediaPage(title, redirect=redirect, preload=preload)\n elif pageid is not None:\n return WikipediaPage(pageid=pageid, preload=preload)\n else:\n raise ValueError(\"Either a title or a pageid must be specified\")\n" ]
from __future__ import unicode_literals import requests import time from bs4 import BeautifulSoup from datetime import datetime, timedelta from decimal import Decimal from .exceptions import ( PageError, DisambiguationError, RedirectError, HTTPTimeoutError, WikipediaException, ODD_ERROR_MESSAGE) from .util import cache, stdout_encode, debug import re API_URL = 'http://en.wikipedia.org/w/api.php' RATE_LIMIT = False RATE_LIMIT_MIN_WAIT = None RATE_LIMIT_LAST_CALL = None USER_AGENT = 'wikipedia (https://github.com/goldsmith/Wikipedia/)' def set_lang(prefix): ''' Change the language of the API being requested. Set `prefix` to one of the two letter prefixes found on the `list of all Wikipedias <http://meta.wikimedia.org/wiki/List_of_Wikipedias>`_. After setting the language, the cache for ``search``, ``suggest``, and ``summary`` will be cleared. .. note:: Make sure you search for page titles in the language that you have set. ''' global API_URL API_URL = 'http://' + prefix.lower() + '.wikipedia.org/w/api.php' for cached_func in (search, suggest, summary): cached_func.clear_cache() def set_user_agent(user_agent_string): ''' Set the User-Agent string to be used for all requests. Arguments: * user_agent_string - (string) a string specifying the User-Agent header ''' global USER_AGENT USER_AGENT = user_agent_string def set_rate_limiting(rate_limit, min_wait=timedelta(milliseconds=50)): ''' Enable or disable rate limiting on requests to the Mediawiki servers. If rate limiting is not enabled, under some circumstances (depending on load on Wikipedia, the number of requests you and other `wikipedia` users are making, and other factors), Wikipedia may return an HTTP timeout error. Enabling rate limiting generally prevents that issue, but please note that HTTPTimeoutError still might be raised. Arguments: * rate_limit - (Boolean) whether to enable rate limiting or not Keyword arguments: * min_wait - if rate limiting is enabled, `min_wait` is a timedelta describing the minimum time to wait before requests. Defaults to timedelta(milliseconds=50) ''' global RATE_LIMIT global RATE_LIMIT_MIN_WAIT global RATE_LIMIT_LAST_CALL RATE_LIMIT = rate_limit if not rate_limit: RATE_LIMIT_MIN_WAIT = None else: RATE_LIMIT_MIN_WAIT = min_wait RATE_LIMIT_LAST_CALL = None @cache def search(query, results=10, suggestion=False): ''' Do a Wikipedia search for `query`. Keyword arguments: * results - the maxmimum number of results returned * suggestion - if True, return results and suggestion (if any) in a tuple ''' search_params = { 'list': 'search', 'srprop': '', 'srlimit': results, 'limit': results, 'srsearch': query } if suggestion: search_params['srinfo'] = 'suggestion' raw_results = _wiki_request(search_params) if 'error' in raw_results: if raw_results['error']['info'] in ('HTTP request timed out.', 'Pool queue is full'): raise HTTPTimeoutError(query) else: raise WikipediaException(raw_results['error']['info']) search_results = (d['title'] for d in raw_results['query']['search']) if suggestion: if raw_results['query'].get('searchinfo'): return list(search_results), raw_results['query']['searchinfo']['suggestion'] else: return list(search_results), None return list(search_results) @cache def geosearch(latitude, longitude, title=None, results=10, radius=1000): ''' Do a wikipedia geo search for `latitude` and `longitude` using HTTP API described in http://www.mediawiki.org/wiki/Extension:GeoData Arguments: * latitude (float or decimal.Decimal) * longitude (float or decimal.Decimal) Keyword arguments: * title - The title of an article to search for * results - the maximum number of results returned * radius - Search radius in meters. The value must be between 10 and 10000 ''' search_params = { 'list': 'geosearch', 'gsradius': radius, 'gscoord': '{0}|{1}'.format(latitude, longitude), 'gslimit': results } if title: search_params['titles'] = title raw_results = _wiki_request(search_params) if 'error' in raw_results: if raw_results['error']['info'] in ('HTTP request timed out.', 'Pool queue is full'): raise HTTPTimeoutError('{0}|{1}'.format(latitude, longitude)) else: raise WikipediaException(raw_results['error']['info']) search_pages = raw_results['query'].get('pages', None) if search_pages: search_results = (v['title'] for k, v in search_pages.items() if k != '-1') else: search_results = (d['title'] for d in raw_results['query']['geosearch']) return list(search_results) @cache def suggest(query): ''' Get a Wikipedia search suggestion for `query`. Returns a string or None if no suggestion was found. ''' search_params = { 'list': 'search', 'srinfo': 'suggestion', 'srprop': '', } search_params['srsearch'] = query raw_result = _wiki_request(search_params) if raw_result['query'].get('searchinfo'): return raw_result['query']['searchinfo']['suggestion'] return None def random(pages=1): ''' Get a list of random Wikipedia article titles. .. note:: Random only gets articles from namespace 0, meaning no Category, User talk, or other meta-Wikipedia pages. Keyword arguments: * pages - the number of random pages returned (max of 10) ''' #http://en.wikipedia.org/w/api.php?action=query&list=random&rnlimit=5000&format=jsonfm query_params = { 'list': 'random', 'rnnamespace': 0, 'rnlimit': pages, } request = _wiki_request(query_params) titles = [page['title'] for page in request['query']['random']] if len(titles) == 1: return titles[0] return titles @cache def page(title=None, pageid=None, auto_suggest=True, redirect=True, preload=False): ''' Get a WikipediaPage object for the page with title `title` or the pageid `pageid` (mutually exclusive). Keyword arguments: * title - the title of the page to load * pageid - the numeric pageid of the page to load * auto_suggest - let Wikipedia find a valid page title for the query * redirect - allow redirection without raising RedirectError * preload - load content, summary, images, references, and links during initialization ''' if title is not None: if auto_suggest: results, suggestion = search(title, results=1, suggestion=True) try: title = suggestion or results[0] except IndexError: # if there is no suggestion or search results, the page doesn't exist raise PageError(title) return WikipediaPage(title, redirect=redirect, preload=preload) elif pageid is not None: return WikipediaPage(pageid=pageid, preload=preload) else: raise ValueError("Either a title or a pageid must be specified") class WikipediaPage(object): ''' Contains data from a Wikipedia page. Uses property methods to filter data from the raw HTML. ''' def __init__(self, title=None, pageid=None, redirect=True, preload=False, original_title=''): if title is not None: self.title = title self.original_title = original_title or title elif pageid is not None: self.pageid = pageid else: raise ValueError("Either a title or a pageid must be specified") self.__load(redirect=redirect, preload=preload) if preload: for prop in ('content', 'summary', 'images', 'references', 'links', 'sections'): getattr(self, prop) def __repr__(self): return stdout_encode(u'<WikipediaPage \'{}\'>'.format(self.title)) def __eq__(self, other): try: return ( self.pageid == other.pageid and self.title == other.title and self.url == other.url ) except: return False def __load(self, redirect=True, preload=False): ''' Load basic information from Wikipedia. Confirm that page exists and is not a disambiguation/redirect. Does not need to be called manually, should be called automatically during __init__. ''' query_params = { 'prop': 'info|pageprops', 'inprop': 'url', 'ppprop': 'disambiguation', 'redirects': '', } if not getattr(self, 'pageid', None): query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) query = request['query'] pageid = list(query['pages'].keys())[0] page = query['pages'][pageid] # missing is present if the page is missing if 'missing' in page: if hasattr(self, 'title'): raise PageError(self.title) else: raise PageError(pageid=self.pageid) # same thing for redirect, except it shows up in query instead of page for # whatever silly reason elif 'redirects' in query: if redirect: redirects = query['redirects'][0] if 'normalized' in query: normalized = query['normalized'][0] assert normalized['from'] == self.title, ODD_ERROR_MESSAGE from_title = normalized['to'] else: from_title = self.title assert redirects['from'] == from_title, ODD_ERROR_MESSAGE # change the title and reload the whole object self.__init__(redirects['to'], redirect=redirect, preload=preload) else: raise RedirectError(getattr(self, 'title', page['title'])) # since we only asked for disambiguation in ppprop, # if a pageprop is returned, # then the page must be a disambiguation page elif 'pageprops' in page: query_params = { 'prop': 'revisions', 'rvprop': 'content', 'rvparse': '', 'rvlimit': 1 } if hasattr(self, 'pageid'): query_params['pageids'] = self.pageid else: query_params['titles'] = self.title request = _wiki_request(query_params) html = request['query']['pages'][pageid]['revisions'][0]['*'] lis = BeautifulSoup(html, 'html.parser').find_all('li') filtered_lis = [li for li in lis if not 'tocsection' in ''.join(li.get('class', []))] may_refer_to = [li.a.get_text() for li in filtered_lis if li.a] raise DisambiguationError(getattr(self, 'title', page['title']), may_refer_to) else: self.pageid = pageid self.title = page['title'] self.url = page['fullurl'] def __continued_query(self, query_params): ''' Based on https://www.mediawiki.org/wiki/API:Query#Continuing_queries ''' query_params.update(self.__title_query_param) last_continue = {} prop = query_params.get('prop', None) while True: params = query_params.copy() params.update(last_continue) request = _wiki_request(params) if 'query' not in request: break pages = request['query']['pages'] if 'generator' in query_params: for datum in pages.values(): # in python 3.3+: "yield from pages.values()" yield datum else: for datum in pages[self.pageid][prop]: yield datum if 'continue' not in request: break last_continue = request['continue'] @property def __title_query_param(self): if getattr(self, 'title', None) is not None: return {'titles': self.title} else: return {'pageids': self.pageid} def html(self): ''' Get full page HTML. .. warning:: This can get pretty slow on long pages. ''' if not getattr(self, '_html', False): query_params = { 'prop': 'revisions', 'rvprop': 'content', 'rvlimit': 1, 'rvparse': '', 'titles': self.title } request = _wiki_request(query_params) self._html = request['query']['pages'][self.pageid]['revisions'][0]['*'] return self._html @property def content(self): ''' Plain text content of the page, excluding images, tables, and other data. ''' if not getattr(self, '_content', False): query_params = { 'prop': 'extracts|revisions', 'explaintext': '', 'rvprop': 'ids' } if not getattr(self, 'title', None) is None: query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) self._content = request['query']['pages'][self.pageid]['extract'] self._revision_id = request['query']['pages'][self.pageid]['revisions'][0]['revid'] self._parent_id = request['query']['pages'][self.pageid]['revisions'][0]['parentid'] return self._content @property def revision_id(self): ''' Revision ID of the page. The revision ID is a number that uniquely identifies the current version of the page. It can be used to create the permalink or for other direct API calls. See `Help:Page history <http://en.wikipedia.org/wiki/Wikipedia:Revision>`_ for more information. ''' if not getattr(self, '_revid', False): # fetch the content (side effect is loading the revid) self.content return self._revision_id @property def parent_id(self): ''' Revision ID of the parent version of the current revision of this page. See ``revision_id`` for more information. ''' if not getattr(self, '_parentid', False): # fetch the content (side effect is loading the revid) self.content return self._parent_id @property def summary(self): ''' Plain text summary of the page. ''' if not getattr(self, '_summary', False): query_params = { 'prop': 'extracts', 'explaintext': '', 'exintro': '', } if not getattr(self, 'title', None) is None: query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) self._summary = request['query']['pages'][self.pageid]['extract'] return self._summary @property def images(self): ''' List of URLs of images on the page. ''' if not getattr(self, '_images', False): self._images = [ page['imageinfo'][0]['url'] for page in self.__continued_query({ 'generator': 'images', 'gimlimit': 'max', 'prop': 'imageinfo', 'iiprop': 'url', }) if 'imageinfo' in page ] return self._images @property def coordinates(self): ''' Tuple of Decimals in the form of (lat, lon) or None ''' if not getattr(self, '_coordinates', False): query_params = { 'prop': 'coordinates', 'colimit': 'max', 'titles': self.title, } request = _wiki_request(query_params) if 'query' in request: coordinates = request['query']['pages'][self.pageid]['coordinates'] self._coordinates = (Decimal(coordinates[0]['lat']), Decimal(coordinates[0]['lon'])) else: self._coordinates = None return self._coordinates @property def references(self): ''' List of URLs of external links on a page. May include external links within page that aren't technically cited anywhere. ''' if not getattr(self, '_references', False): def add_protocol(url): return url if url.startswith('http') else 'http:' + url self._references = [ add_protocol(link['*']) for link in self.__continued_query({ 'prop': 'extlinks', 'ellimit': 'max' }) ] return self._references @property def links(self): ''' List of titles of Wikipedia page links on a page. .. note:: Only includes articles from namespace 0, meaning no Category, User talk, or other meta-Wikipedia pages. ''' if not getattr(self, '_links', False): self._links = [ link['title'] for link in self.__continued_query({ 'prop': 'links', 'plnamespace': 0, 'pllimit': 'max' }) ] return self._links @property def categories(self): ''' List of categories of a page. ''' if not getattr(self, '_categories', False): self._categories = [re.sub(r'^Category:', '', x) for x in [link['title'] for link in self.__continued_query({ 'prop': 'categories', 'cllimit': 'max' }) ]] return self._categories @property def sections(self): ''' List of section titles from the table of contents on the page. ''' if not getattr(self, '_sections', False): query_params = { 'action': 'parse', 'prop': 'sections', } query_params.update(self.__title_query_param) request = _wiki_request(query_params) self._sections = [section['line'] for section in request['parse']['sections']] return self._sections def section(self, section_title): ''' Get the plain text content of a section from `self.sections`. Returns None if `section_title` isn't found, otherwise returns a whitespace stripped string. This is a convenience method that wraps self.content. .. warning:: Calling `section` on a section that has subheadings will NOT return the full text of all of the subsections. It only gets the text between `section_title` and the next subheading, which is often empty. ''' section = u"== {} ==".format(section_title) try: index = self.content.index(section) + len(section) except ValueError: return None try: next_index = self.content.index("==", index) except ValueError: next_index = len(self.content) return self.content[index:next_index].lstrip("=").strip() @cache def languages(): ''' List all the currently supported language prefixes (usually ISO language code). Can be inputted to `set_lang` to change the Mediawiki that `wikipedia` requests results from. Returns: dict of <prefix>: <local_lang_name> pairs. To get just a list of prefixes, use `wikipedia.languages().keys()`. ''' response = _wiki_request({ 'meta': 'siteinfo', 'siprop': 'languages' }) languages = response['query']['languages'] return { lang['code']: lang['*'] for lang in languages } def donate(): ''' Open up the Wikimedia donate page in your favorite browser. ''' import webbrowser webbrowser.open('https://donate.wikimedia.org/w/index.php?title=Special:FundraiserLandingPage', new=2) def _wiki_request(params): ''' Make a request to the Wikipedia API using the given search parameters. Returns a parsed dict of the JSON response. ''' global RATE_LIMIT_LAST_CALL global USER_AGENT params['format'] = 'json' if not 'action' in params: params['action'] = 'query' headers = { 'User-Agent': USER_AGENT } if RATE_LIMIT and RATE_LIMIT_LAST_CALL and \ RATE_LIMIT_LAST_CALL + RATE_LIMIT_MIN_WAIT > datetime.now(): # it hasn't been long enough since the last API call # so wait until we're in the clear to make the request wait_time = (RATE_LIMIT_LAST_CALL + RATE_LIMIT_MIN_WAIT) - datetime.now() time.sleep(int(wait_time.total_seconds())) r = requests.get(API_URL, params=params, headers=headers) if RATE_LIMIT: RATE_LIMIT_LAST_CALL = datetime.now() return r.json()
goldsmith/Wikipedia
wikipedia/wikipedia.py
page
python
def page(title=None, pageid=None, auto_suggest=True, redirect=True, preload=False): ''' Get a WikipediaPage object for the page with title `title` or the pageid `pageid` (mutually exclusive). Keyword arguments: * title - the title of the page to load * pageid - the numeric pageid of the page to load * auto_suggest - let Wikipedia find a valid page title for the query * redirect - allow redirection without raising RedirectError * preload - load content, summary, images, references, and links during initialization ''' if title is not None: if auto_suggest: results, suggestion = search(title, results=1, suggestion=True) try: title = suggestion or results[0] except IndexError: # if there is no suggestion or search results, the page doesn't exist raise PageError(title) return WikipediaPage(title, redirect=redirect, preload=preload) elif pageid is not None: return WikipediaPage(pageid=pageid, preload=preload) else: raise ValueError("Either a title or a pageid must be specified")
Get a WikipediaPage object for the page with title `title` or the pageid `pageid` (mutually exclusive). Keyword arguments: * title - the title of the page to load * pageid - the numeric pageid of the page to load * auto_suggest - let Wikipedia find a valid page title for the query * redirect - allow redirection without raising RedirectError * preload - load content, summary, images, references, and links during initialization
train
https://github.com/goldsmith/Wikipedia/blob/2065c568502b19b8634241b47fd96930d1bf948d/wikipedia/wikipedia.py#L254-L280
null
from __future__ import unicode_literals import requests import time from bs4 import BeautifulSoup from datetime import datetime, timedelta from decimal import Decimal from .exceptions import ( PageError, DisambiguationError, RedirectError, HTTPTimeoutError, WikipediaException, ODD_ERROR_MESSAGE) from .util import cache, stdout_encode, debug import re API_URL = 'http://en.wikipedia.org/w/api.php' RATE_LIMIT = False RATE_LIMIT_MIN_WAIT = None RATE_LIMIT_LAST_CALL = None USER_AGENT = 'wikipedia (https://github.com/goldsmith/Wikipedia/)' def set_lang(prefix): ''' Change the language of the API being requested. Set `prefix` to one of the two letter prefixes found on the `list of all Wikipedias <http://meta.wikimedia.org/wiki/List_of_Wikipedias>`_. After setting the language, the cache for ``search``, ``suggest``, and ``summary`` will be cleared. .. note:: Make sure you search for page titles in the language that you have set. ''' global API_URL API_URL = 'http://' + prefix.lower() + '.wikipedia.org/w/api.php' for cached_func in (search, suggest, summary): cached_func.clear_cache() def set_user_agent(user_agent_string): ''' Set the User-Agent string to be used for all requests. Arguments: * user_agent_string - (string) a string specifying the User-Agent header ''' global USER_AGENT USER_AGENT = user_agent_string def set_rate_limiting(rate_limit, min_wait=timedelta(milliseconds=50)): ''' Enable or disable rate limiting on requests to the Mediawiki servers. If rate limiting is not enabled, under some circumstances (depending on load on Wikipedia, the number of requests you and other `wikipedia` users are making, and other factors), Wikipedia may return an HTTP timeout error. Enabling rate limiting generally prevents that issue, but please note that HTTPTimeoutError still might be raised. Arguments: * rate_limit - (Boolean) whether to enable rate limiting or not Keyword arguments: * min_wait - if rate limiting is enabled, `min_wait` is a timedelta describing the minimum time to wait before requests. Defaults to timedelta(milliseconds=50) ''' global RATE_LIMIT global RATE_LIMIT_MIN_WAIT global RATE_LIMIT_LAST_CALL RATE_LIMIT = rate_limit if not rate_limit: RATE_LIMIT_MIN_WAIT = None else: RATE_LIMIT_MIN_WAIT = min_wait RATE_LIMIT_LAST_CALL = None @cache def search(query, results=10, suggestion=False): ''' Do a Wikipedia search for `query`. Keyword arguments: * results - the maxmimum number of results returned * suggestion - if True, return results and suggestion (if any) in a tuple ''' search_params = { 'list': 'search', 'srprop': '', 'srlimit': results, 'limit': results, 'srsearch': query } if suggestion: search_params['srinfo'] = 'suggestion' raw_results = _wiki_request(search_params) if 'error' in raw_results: if raw_results['error']['info'] in ('HTTP request timed out.', 'Pool queue is full'): raise HTTPTimeoutError(query) else: raise WikipediaException(raw_results['error']['info']) search_results = (d['title'] for d in raw_results['query']['search']) if suggestion: if raw_results['query'].get('searchinfo'): return list(search_results), raw_results['query']['searchinfo']['suggestion'] else: return list(search_results), None return list(search_results) @cache def geosearch(latitude, longitude, title=None, results=10, radius=1000): ''' Do a wikipedia geo search for `latitude` and `longitude` using HTTP API described in http://www.mediawiki.org/wiki/Extension:GeoData Arguments: * latitude (float or decimal.Decimal) * longitude (float or decimal.Decimal) Keyword arguments: * title - The title of an article to search for * results - the maximum number of results returned * radius - Search radius in meters. The value must be between 10 and 10000 ''' search_params = { 'list': 'geosearch', 'gsradius': radius, 'gscoord': '{0}|{1}'.format(latitude, longitude), 'gslimit': results } if title: search_params['titles'] = title raw_results = _wiki_request(search_params) if 'error' in raw_results: if raw_results['error']['info'] in ('HTTP request timed out.', 'Pool queue is full'): raise HTTPTimeoutError('{0}|{1}'.format(latitude, longitude)) else: raise WikipediaException(raw_results['error']['info']) search_pages = raw_results['query'].get('pages', None) if search_pages: search_results = (v['title'] for k, v in search_pages.items() if k != '-1') else: search_results = (d['title'] for d in raw_results['query']['geosearch']) return list(search_results) @cache def suggest(query): ''' Get a Wikipedia search suggestion for `query`. Returns a string or None if no suggestion was found. ''' search_params = { 'list': 'search', 'srinfo': 'suggestion', 'srprop': '', } search_params['srsearch'] = query raw_result = _wiki_request(search_params) if raw_result['query'].get('searchinfo'): return raw_result['query']['searchinfo']['suggestion'] return None def random(pages=1): ''' Get a list of random Wikipedia article titles. .. note:: Random only gets articles from namespace 0, meaning no Category, User talk, or other meta-Wikipedia pages. Keyword arguments: * pages - the number of random pages returned (max of 10) ''' #http://en.wikipedia.org/w/api.php?action=query&list=random&rnlimit=5000&format=jsonfm query_params = { 'list': 'random', 'rnnamespace': 0, 'rnlimit': pages, } request = _wiki_request(query_params) titles = [page['title'] for page in request['query']['random']] if len(titles) == 1: return titles[0] return titles @cache def summary(title, sentences=0, chars=0, auto_suggest=True, redirect=True): ''' Plain text summary of the page. .. note:: This is a convenience wrapper - auto_suggest and redirect are enabled by default Keyword arguments: * sentences - if set, return the first `sentences` sentences (can be no greater than 10). * chars - if set, return only the first `chars` characters (actual text returned may be slightly longer). * auto_suggest - let Wikipedia find a valid page title for the query * redirect - allow redirection without raising RedirectError ''' # use auto_suggest and redirect to get the correct article # also, use page's error checking to raise DisambiguationError if necessary page_info = page(title, auto_suggest=auto_suggest, redirect=redirect) title = page_info.title pageid = page_info.pageid query_params = { 'prop': 'extracts', 'explaintext': '', 'titles': title } if sentences: query_params['exsentences'] = sentences elif chars: query_params['exchars'] = chars else: query_params['exintro'] = '' request = _wiki_request(query_params) summary = request['query']['pages'][pageid]['extract'] return summary class WikipediaPage(object): ''' Contains data from a Wikipedia page. Uses property methods to filter data from the raw HTML. ''' def __init__(self, title=None, pageid=None, redirect=True, preload=False, original_title=''): if title is not None: self.title = title self.original_title = original_title or title elif pageid is not None: self.pageid = pageid else: raise ValueError("Either a title or a pageid must be specified") self.__load(redirect=redirect, preload=preload) if preload: for prop in ('content', 'summary', 'images', 'references', 'links', 'sections'): getattr(self, prop) def __repr__(self): return stdout_encode(u'<WikipediaPage \'{}\'>'.format(self.title)) def __eq__(self, other): try: return ( self.pageid == other.pageid and self.title == other.title and self.url == other.url ) except: return False def __load(self, redirect=True, preload=False): ''' Load basic information from Wikipedia. Confirm that page exists and is not a disambiguation/redirect. Does not need to be called manually, should be called automatically during __init__. ''' query_params = { 'prop': 'info|pageprops', 'inprop': 'url', 'ppprop': 'disambiguation', 'redirects': '', } if not getattr(self, 'pageid', None): query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) query = request['query'] pageid = list(query['pages'].keys())[0] page = query['pages'][pageid] # missing is present if the page is missing if 'missing' in page: if hasattr(self, 'title'): raise PageError(self.title) else: raise PageError(pageid=self.pageid) # same thing for redirect, except it shows up in query instead of page for # whatever silly reason elif 'redirects' in query: if redirect: redirects = query['redirects'][0] if 'normalized' in query: normalized = query['normalized'][0] assert normalized['from'] == self.title, ODD_ERROR_MESSAGE from_title = normalized['to'] else: from_title = self.title assert redirects['from'] == from_title, ODD_ERROR_MESSAGE # change the title and reload the whole object self.__init__(redirects['to'], redirect=redirect, preload=preload) else: raise RedirectError(getattr(self, 'title', page['title'])) # since we only asked for disambiguation in ppprop, # if a pageprop is returned, # then the page must be a disambiguation page elif 'pageprops' in page: query_params = { 'prop': 'revisions', 'rvprop': 'content', 'rvparse': '', 'rvlimit': 1 } if hasattr(self, 'pageid'): query_params['pageids'] = self.pageid else: query_params['titles'] = self.title request = _wiki_request(query_params) html = request['query']['pages'][pageid]['revisions'][0]['*'] lis = BeautifulSoup(html, 'html.parser').find_all('li') filtered_lis = [li for li in lis if not 'tocsection' in ''.join(li.get('class', []))] may_refer_to = [li.a.get_text() for li in filtered_lis if li.a] raise DisambiguationError(getattr(self, 'title', page['title']), may_refer_to) else: self.pageid = pageid self.title = page['title'] self.url = page['fullurl'] def __continued_query(self, query_params): ''' Based on https://www.mediawiki.org/wiki/API:Query#Continuing_queries ''' query_params.update(self.__title_query_param) last_continue = {} prop = query_params.get('prop', None) while True: params = query_params.copy() params.update(last_continue) request = _wiki_request(params) if 'query' not in request: break pages = request['query']['pages'] if 'generator' in query_params: for datum in pages.values(): # in python 3.3+: "yield from pages.values()" yield datum else: for datum in pages[self.pageid][prop]: yield datum if 'continue' not in request: break last_continue = request['continue'] @property def __title_query_param(self): if getattr(self, 'title', None) is not None: return {'titles': self.title} else: return {'pageids': self.pageid} def html(self): ''' Get full page HTML. .. warning:: This can get pretty slow on long pages. ''' if not getattr(self, '_html', False): query_params = { 'prop': 'revisions', 'rvprop': 'content', 'rvlimit': 1, 'rvparse': '', 'titles': self.title } request = _wiki_request(query_params) self._html = request['query']['pages'][self.pageid]['revisions'][0]['*'] return self._html @property def content(self): ''' Plain text content of the page, excluding images, tables, and other data. ''' if not getattr(self, '_content', False): query_params = { 'prop': 'extracts|revisions', 'explaintext': '', 'rvprop': 'ids' } if not getattr(self, 'title', None) is None: query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) self._content = request['query']['pages'][self.pageid]['extract'] self._revision_id = request['query']['pages'][self.pageid]['revisions'][0]['revid'] self._parent_id = request['query']['pages'][self.pageid]['revisions'][0]['parentid'] return self._content @property def revision_id(self): ''' Revision ID of the page. The revision ID is a number that uniquely identifies the current version of the page. It can be used to create the permalink or for other direct API calls. See `Help:Page history <http://en.wikipedia.org/wiki/Wikipedia:Revision>`_ for more information. ''' if not getattr(self, '_revid', False): # fetch the content (side effect is loading the revid) self.content return self._revision_id @property def parent_id(self): ''' Revision ID of the parent version of the current revision of this page. See ``revision_id`` for more information. ''' if not getattr(self, '_parentid', False): # fetch the content (side effect is loading the revid) self.content return self._parent_id @property def summary(self): ''' Plain text summary of the page. ''' if not getattr(self, '_summary', False): query_params = { 'prop': 'extracts', 'explaintext': '', 'exintro': '', } if not getattr(self, 'title', None) is None: query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) self._summary = request['query']['pages'][self.pageid]['extract'] return self._summary @property def images(self): ''' List of URLs of images on the page. ''' if not getattr(self, '_images', False): self._images = [ page['imageinfo'][0]['url'] for page in self.__continued_query({ 'generator': 'images', 'gimlimit': 'max', 'prop': 'imageinfo', 'iiprop': 'url', }) if 'imageinfo' in page ] return self._images @property def coordinates(self): ''' Tuple of Decimals in the form of (lat, lon) or None ''' if not getattr(self, '_coordinates', False): query_params = { 'prop': 'coordinates', 'colimit': 'max', 'titles': self.title, } request = _wiki_request(query_params) if 'query' in request: coordinates = request['query']['pages'][self.pageid]['coordinates'] self._coordinates = (Decimal(coordinates[0]['lat']), Decimal(coordinates[0]['lon'])) else: self._coordinates = None return self._coordinates @property def references(self): ''' List of URLs of external links on a page. May include external links within page that aren't technically cited anywhere. ''' if not getattr(self, '_references', False): def add_protocol(url): return url if url.startswith('http') else 'http:' + url self._references = [ add_protocol(link['*']) for link in self.__continued_query({ 'prop': 'extlinks', 'ellimit': 'max' }) ] return self._references @property def links(self): ''' List of titles of Wikipedia page links on a page. .. note:: Only includes articles from namespace 0, meaning no Category, User talk, or other meta-Wikipedia pages. ''' if not getattr(self, '_links', False): self._links = [ link['title'] for link in self.__continued_query({ 'prop': 'links', 'plnamespace': 0, 'pllimit': 'max' }) ] return self._links @property def categories(self): ''' List of categories of a page. ''' if not getattr(self, '_categories', False): self._categories = [re.sub(r'^Category:', '', x) for x in [link['title'] for link in self.__continued_query({ 'prop': 'categories', 'cllimit': 'max' }) ]] return self._categories @property def sections(self): ''' List of section titles from the table of contents on the page. ''' if not getattr(self, '_sections', False): query_params = { 'action': 'parse', 'prop': 'sections', } query_params.update(self.__title_query_param) request = _wiki_request(query_params) self._sections = [section['line'] for section in request['parse']['sections']] return self._sections def section(self, section_title): ''' Get the plain text content of a section from `self.sections`. Returns None if `section_title` isn't found, otherwise returns a whitespace stripped string. This is a convenience method that wraps self.content. .. warning:: Calling `section` on a section that has subheadings will NOT return the full text of all of the subsections. It only gets the text between `section_title` and the next subheading, which is often empty. ''' section = u"== {} ==".format(section_title) try: index = self.content.index(section) + len(section) except ValueError: return None try: next_index = self.content.index("==", index) except ValueError: next_index = len(self.content) return self.content[index:next_index].lstrip("=").strip() @cache def languages(): ''' List all the currently supported language prefixes (usually ISO language code). Can be inputted to `set_lang` to change the Mediawiki that `wikipedia` requests results from. Returns: dict of <prefix>: <local_lang_name> pairs. To get just a list of prefixes, use `wikipedia.languages().keys()`. ''' response = _wiki_request({ 'meta': 'siteinfo', 'siprop': 'languages' }) languages = response['query']['languages'] return { lang['code']: lang['*'] for lang in languages } def donate(): ''' Open up the Wikimedia donate page in your favorite browser. ''' import webbrowser webbrowser.open('https://donate.wikimedia.org/w/index.php?title=Special:FundraiserLandingPage', new=2) def _wiki_request(params): ''' Make a request to the Wikipedia API using the given search parameters. Returns a parsed dict of the JSON response. ''' global RATE_LIMIT_LAST_CALL global USER_AGENT params['format'] = 'json' if not 'action' in params: params['action'] = 'query' headers = { 'User-Agent': USER_AGENT } if RATE_LIMIT and RATE_LIMIT_LAST_CALL and \ RATE_LIMIT_LAST_CALL + RATE_LIMIT_MIN_WAIT > datetime.now(): # it hasn't been long enough since the last API call # so wait until we're in the clear to make the request wait_time = (RATE_LIMIT_LAST_CALL + RATE_LIMIT_MIN_WAIT) - datetime.now() time.sleep(int(wait_time.total_seconds())) r = requests.get(API_URL, params=params, headers=headers) if RATE_LIMIT: RATE_LIMIT_LAST_CALL = datetime.now() return r.json()
goldsmith/Wikipedia
wikipedia/wikipedia.py
_wiki_request
python
def _wiki_request(params): ''' Make a request to the Wikipedia API using the given search parameters. Returns a parsed dict of the JSON response. ''' global RATE_LIMIT_LAST_CALL global USER_AGENT params['format'] = 'json' if not 'action' in params: params['action'] = 'query' headers = { 'User-Agent': USER_AGENT } if RATE_LIMIT and RATE_LIMIT_LAST_CALL and \ RATE_LIMIT_LAST_CALL + RATE_LIMIT_MIN_WAIT > datetime.now(): # it hasn't been long enough since the last API call # so wait until we're in the clear to make the request wait_time = (RATE_LIMIT_LAST_CALL + RATE_LIMIT_MIN_WAIT) - datetime.now() time.sleep(int(wait_time.total_seconds())) r = requests.get(API_URL, params=params, headers=headers) if RATE_LIMIT: RATE_LIMIT_LAST_CALL = datetime.now() return r.json()
Make a request to the Wikipedia API using the given search parameters. Returns a parsed dict of the JSON response.
train
https://github.com/goldsmith/Wikipedia/blob/2065c568502b19b8634241b47fd96930d1bf948d/wikipedia/wikipedia.py#L712-L742
null
from __future__ import unicode_literals import requests import time from bs4 import BeautifulSoup from datetime import datetime, timedelta from decimal import Decimal from .exceptions import ( PageError, DisambiguationError, RedirectError, HTTPTimeoutError, WikipediaException, ODD_ERROR_MESSAGE) from .util import cache, stdout_encode, debug import re API_URL = 'http://en.wikipedia.org/w/api.php' RATE_LIMIT = False RATE_LIMIT_MIN_WAIT = None RATE_LIMIT_LAST_CALL = None USER_AGENT = 'wikipedia (https://github.com/goldsmith/Wikipedia/)' def set_lang(prefix): ''' Change the language of the API being requested. Set `prefix` to one of the two letter prefixes found on the `list of all Wikipedias <http://meta.wikimedia.org/wiki/List_of_Wikipedias>`_. After setting the language, the cache for ``search``, ``suggest``, and ``summary`` will be cleared. .. note:: Make sure you search for page titles in the language that you have set. ''' global API_URL API_URL = 'http://' + prefix.lower() + '.wikipedia.org/w/api.php' for cached_func in (search, suggest, summary): cached_func.clear_cache() def set_user_agent(user_agent_string): ''' Set the User-Agent string to be used for all requests. Arguments: * user_agent_string - (string) a string specifying the User-Agent header ''' global USER_AGENT USER_AGENT = user_agent_string def set_rate_limiting(rate_limit, min_wait=timedelta(milliseconds=50)): ''' Enable or disable rate limiting on requests to the Mediawiki servers. If rate limiting is not enabled, under some circumstances (depending on load on Wikipedia, the number of requests you and other `wikipedia` users are making, and other factors), Wikipedia may return an HTTP timeout error. Enabling rate limiting generally prevents that issue, but please note that HTTPTimeoutError still might be raised. Arguments: * rate_limit - (Boolean) whether to enable rate limiting or not Keyword arguments: * min_wait - if rate limiting is enabled, `min_wait` is a timedelta describing the minimum time to wait before requests. Defaults to timedelta(milliseconds=50) ''' global RATE_LIMIT global RATE_LIMIT_MIN_WAIT global RATE_LIMIT_LAST_CALL RATE_LIMIT = rate_limit if not rate_limit: RATE_LIMIT_MIN_WAIT = None else: RATE_LIMIT_MIN_WAIT = min_wait RATE_LIMIT_LAST_CALL = None @cache def search(query, results=10, suggestion=False): ''' Do a Wikipedia search for `query`. Keyword arguments: * results - the maxmimum number of results returned * suggestion - if True, return results and suggestion (if any) in a tuple ''' search_params = { 'list': 'search', 'srprop': '', 'srlimit': results, 'limit': results, 'srsearch': query } if suggestion: search_params['srinfo'] = 'suggestion' raw_results = _wiki_request(search_params) if 'error' in raw_results: if raw_results['error']['info'] in ('HTTP request timed out.', 'Pool queue is full'): raise HTTPTimeoutError(query) else: raise WikipediaException(raw_results['error']['info']) search_results = (d['title'] for d in raw_results['query']['search']) if suggestion: if raw_results['query'].get('searchinfo'): return list(search_results), raw_results['query']['searchinfo']['suggestion'] else: return list(search_results), None return list(search_results) @cache def geosearch(latitude, longitude, title=None, results=10, radius=1000): ''' Do a wikipedia geo search for `latitude` and `longitude` using HTTP API described in http://www.mediawiki.org/wiki/Extension:GeoData Arguments: * latitude (float or decimal.Decimal) * longitude (float or decimal.Decimal) Keyword arguments: * title - The title of an article to search for * results - the maximum number of results returned * radius - Search radius in meters. The value must be between 10 and 10000 ''' search_params = { 'list': 'geosearch', 'gsradius': radius, 'gscoord': '{0}|{1}'.format(latitude, longitude), 'gslimit': results } if title: search_params['titles'] = title raw_results = _wiki_request(search_params) if 'error' in raw_results: if raw_results['error']['info'] in ('HTTP request timed out.', 'Pool queue is full'): raise HTTPTimeoutError('{0}|{1}'.format(latitude, longitude)) else: raise WikipediaException(raw_results['error']['info']) search_pages = raw_results['query'].get('pages', None) if search_pages: search_results = (v['title'] for k, v in search_pages.items() if k != '-1') else: search_results = (d['title'] for d in raw_results['query']['geosearch']) return list(search_results) @cache def suggest(query): ''' Get a Wikipedia search suggestion for `query`. Returns a string or None if no suggestion was found. ''' search_params = { 'list': 'search', 'srinfo': 'suggestion', 'srprop': '', } search_params['srsearch'] = query raw_result = _wiki_request(search_params) if raw_result['query'].get('searchinfo'): return raw_result['query']['searchinfo']['suggestion'] return None def random(pages=1): ''' Get a list of random Wikipedia article titles. .. note:: Random only gets articles from namespace 0, meaning no Category, User talk, or other meta-Wikipedia pages. Keyword arguments: * pages - the number of random pages returned (max of 10) ''' #http://en.wikipedia.org/w/api.php?action=query&list=random&rnlimit=5000&format=jsonfm query_params = { 'list': 'random', 'rnnamespace': 0, 'rnlimit': pages, } request = _wiki_request(query_params) titles = [page['title'] for page in request['query']['random']] if len(titles) == 1: return titles[0] return titles @cache def summary(title, sentences=0, chars=0, auto_suggest=True, redirect=True): ''' Plain text summary of the page. .. note:: This is a convenience wrapper - auto_suggest and redirect are enabled by default Keyword arguments: * sentences - if set, return the first `sentences` sentences (can be no greater than 10). * chars - if set, return only the first `chars` characters (actual text returned may be slightly longer). * auto_suggest - let Wikipedia find a valid page title for the query * redirect - allow redirection without raising RedirectError ''' # use auto_suggest and redirect to get the correct article # also, use page's error checking to raise DisambiguationError if necessary page_info = page(title, auto_suggest=auto_suggest, redirect=redirect) title = page_info.title pageid = page_info.pageid query_params = { 'prop': 'extracts', 'explaintext': '', 'titles': title } if sentences: query_params['exsentences'] = sentences elif chars: query_params['exchars'] = chars else: query_params['exintro'] = '' request = _wiki_request(query_params) summary = request['query']['pages'][pageid]['extract'] return summary def page(title=None, pageid=None, auto_suggest=True, redirect=True, preload=False): ''' Get a WikipediaPage object for the page with title `title` or the pageid `pageid` (mutually exclusive). Keyword arguments: * title - the title of the page to load * pageid - the numeric pageid of the page to load * auto_suggest - let Wikipedia find a valid page title for the query * redirect - allow redirection without raising RedirectError * preload - load content, summary, images, references, and links during initialization ''' if title is not None: if auto_suggest: results, suggestion = search(title, results=1, suggestion=True) try: title = suggestion or results[0] except IndexError: # if there is no suggestion or search results, the page doesn't exist raise PageError(title) return WikipediaPage(title, redirect=redirect, preload=preload) elif pageid is not None: return WikipediaPage(pageid=pageid, preload=preload) else: raise ValueError("Either a title or a pageid must be specified") class WikipediaPage(object): ''' Contains data from a Wikipedia page. Uses property methods to filter data from the raw HTML. ''' def __init__(self, title=None, pageid=None, redirect=True, preload=False, original_title=''): if title is not None: self.title = title self.original_title = original_title or title elif pageid is not None: self.pageid = pageid else: raise ValueError("Either a title or a pageid must be specified") self.__load(redirect=redirect, preload=preload) if preload: for prop in ('content', 'summary', 'images', 'references', 'links', 'sections'): getattr(self, prop) def __repr__(self): return stdout_encode(u'<WikipediaPage \'{}\'>'.format(self.title)) def __eq__(self, other): try: return ( self.pageid == other.pageid and self.title == other.title and self.url == other.url ) except: return False def __load(self, redirect=True, preload=False): ''' Load basic information from Wikipedia. Confirm that page exists and is not a disambiguation/redirect. Does not need to be called manually, should be called automatically during __init__. ''' query_params = { 'prop': 'info|pageprops', 'inprop': 'url', 'ppprop': 'disambiguation', 'redirects': '', } if not getattr(self, 'pageid', None): query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) query = request['query'] pageid = list(query['pages'].keys())[0] page = query['pages'][pageid] # missing is present if the page is missing if 'missing' in page: if hasattr(self, 'title'): raise PageError(self.title) else: raise PageError(pageid=self.pageid) # same thing for redirect, except it shows up in query instead of page for # whatever silly reason elif 'redirects' in query: if redirect: redirects = query['redirects'][0] if 'normalized' in query: normalized = query['normalized'][0] assert normalized['from'] == self.title, ODD_ERROR_MESSAGE from_title = normalized['to'] else: from_title = self.title assert redirects['from'] == from_title, ODD_ERROR_MESSAGE # change the title and reload the whole object self.__init__(redirects['to'], redirect=redirect, preload=preload) else: raise RedirectError(getattr(self, 'title', page['title'])) # since we only asked for disambiguation in ppprop, # if a pageprop is returned, # then the page must be a disambiguation page elif 'pageprops' in page: query_params = { 'prop': 'revisions', 'rvprop': 'content', 'rvparse': '', 'rvlimit': 1 } if hasattr(self, 'pageid'): query_params['pageids'] = self.pageid else: query_params['titles'] = self.title request = _wiki_request(query_params) html = request['query']['pages'][pageid]['revisions'][0]['*'] lis = BeautifulSoup(html, 'html.parser').find_all('li') filtered_lis = [li for li in lis if not 'tocsection' in ''.join(li.get('class', []))] may_refer_to = [li.a.get_text() for li in filtered_lis if li.a] raise DisambiguationError(getattr(self, 'title', page['title']), may_refer_to) else: self.pageid = pageid self.title = page['title'] self.url = page['fullurl'] def __continued_query(self, query_params): ''' Based on https://www.mediawiki.org/wiki/API:Query#Continuing_queries ''' query_params.update(self.__title_query_param) last_continue = {} prop = query_params.get('prop', None) while True: params = query_params.copy() params.update(last_continue) request = _wiki_request(params) if 'query' not in request: break pages = request['query']['pages'] if 'generator' in query_params: for datum in pages.values(): # in python 3.3+: "yield from pages.values()" yield datum else: for datum in pages[self.pageid][prop]: yield datum if 'continue' not in request: break last_continue = request['continue'] @property def __title_query_param(self): if getattr(self, 'title', None) is not None: return {'titles': self.title} else: return {'pageids': self.pageid} def html(self): ''' Get full page HTML. .. warning:: This can get pretty slow on long pages. ''' if not getattr(self, '_html', False): query_params = { 'prop': 'revisions', 'rvprop': 'content', 'rvlimit': 1, 'rvparse': '', 'titles': self.title } request = _wiki_request(query_params) self._html = request['query']['pages'][self.pageid]['revisions'][0]['*'] return self._html @property def content(self): ''' Plain text content of the page, excluding images, tables, and other data. ''' if not getattr(self, '_content', False): query_params = { 'prop': 'extracts|revisions', 'explaintext': '', 'rvprop': 'ids' } if not getattr(self, 'title', None) is None: query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) self._content = request['query']['pages'][self.pageid]['extract'] self._revision_id = request['query']['pages'][self.pageid]['revisions'][0]['revid'] self._parent_id = request['query']['pages'][self.pageid]['revisions'][0]['parentid'] return self._content @property def revision_id(self): ''' Revision ID of the page. The revision ID is a number that uniquely identifies the current version of the page. It can be used to create the permalink or for other direct API calls. See `Help:Page history <http://en.wikipedia.org/wiki/Wikipedia:Revision>`_ for more information. ''' if not getattr(self, '_revid', False): # fetch the content (side effect is loading the revid) self.content return self._revision_id @property def parent_id(self): ''' Revision ID of the parent version of the current revision of this page. See ``revision_id`` for more information. ''' if not getattr(self, '_parentid', False): # fetch the content (side effect is loading the revid) self.content return self._parent_id @property def summary(self): ''' Plain text summary of the page. ''' if not getattr(self, '_summary', False): query_params = { 'prop': 'extracts', 'explaintext': '', 'exintro': '', } if not getattr(self, 'title', None) is None: query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) self._summary = request['query']['pages'][self.pageid]['extract'] return self._summary @property def images(self): ''' List of URLs of images on the page. ''' if not getattr(self, '_images', False): self._images = [ page['imageinfo'][0]['url'] for page in self.__continued_query({ 'generator': 'images', 'gimlimit': 'max', 'prop': 'imageinfo', 'iiprop': 'url', }) if 'imageinfo' in page ] return self._images @property def coordinates(self): ''' Tuple of Decimals in the form of (lat, lon) or None ''' if not getattr(self, '_coordinates', False): query_params = { 'prop': 'coordinates', 'colimit': 'max', 'titles': self.title, } request = _wiki_request(query_params) if 'query' in request: coordinates = request['query']['pages'][self.pageid]['coordinates'] self._coordinates = (Decimal(coordinates[0]['lat']), Decimal(coordinates[0]['lon'])) else: self._coordinates = None return self._coordinates @property def references(self): ''' List of URLs of external links on a page. May include external links within page that aren't technically cited anywhere. ''' if not getattr(self, '_references', False): def add_protocol(url): return url if url.startswith('http') else 'http:' + url self._references = [ add_protocol(link['*']) for link in self.__continued_query({ 'prop': 'extlinks', 'ellimit': 'max' }) ] return self._references @property def links(self): ''' List of titles of Wikipedia page links on a page. .. note:: Only includes articles from namespace 0, meaning no Category, User talk, or other meta-Wikipedia pages. ''' if not getattr(self, '_links', False): self._links = [ link['title'] for link in self.__continued_query({ 'prop': 'links', 'plnamespace': 0, 'pllimit': 'max' }) ] return self._links @property def categories(self): ''' List of categories of a page. ''' if not getattr(self, '_categories', False): self._categories = [re.sub(r'^Category:', '', x) for x in [link['title'] for link in self.__continued_query({ 'prop': 'categories', 'cllimit': 'max' }) ]] return self._categories @property def sections(self): ''' List of section titles from the table of contents on the page. ''' if not getattr(self, '_sections', False): query_params = { 'action': 'parse', 'prop': 'sections', } query_params.update(self.__title_query_param) request = _wiki_request(query_params) self._sections = [section['line'] for section in request['parse']['sections']] return self._sections def section(self, section_title): ''' Get the plain text content of a section from `self.sections`. Returns None if `section_title` isn't found, otherwise returns a whitespace stripped string. This is a convenience method that wraps self.content. .. warning:: Calling `section` on a section that has subheadings will NOT return the full text of all of the subsections. It only gets the text between `section_title` and the next subheading, which is often empty. ''' section = u"== {} ==".format(section_title) try: index = self.content.index(section) + len(section) except ValueError: return None try: next_index = self.content.index("==", index) except ValueError: next_index = len(self.content) return self.content[index:next_index].lstrip("=").strip() @cache def languages(): ''' List all the currently supported language prefixes (usually ISO language code). Can be inputted to `set_lang` to change the Mediawiki that `wikipedia` requests results from. Returns: dict of <prefix>: <local_lang_name> pairs. To get just a list of prefixes, use `wikipedia.languages().keys()`. ''' response = _wiki_request({ 'meta': 'siteinfo', 'siprop': 'languages' }) languages = response['query']['languages'] return { lang['code']: lang['*'] for lang in languages } def donate(): ''' Open up the Wikimedia donate page in your favorite browser. ''' import webbrowser webbrowser.open('https://donate.wikimedia.org/w/index.php?title=Special:FundraiserLandingPage', new=2)
goldsmith/Wikipedia
wikipedia/wikipedia.py
WikipediaPage.__load
python
def __load(self, redirect=True, preload=False): ''' Load basic information from Wikipedia. Confirm that page exists and is not a disambiguation/redirect. Does not need to be called manually, should be called automatically during __init__. ''' query_params = { 'prop': 'info|pageprops', 'inprop': 'url', 'ppprop': 'disambiguation', 'redirects': '', } if not getattr(self, 'pageid', None): query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) query = request['query'] pageid = list(query['pages'].keys())[0] page = query['pages'][pageid] # missing is present if the page is missing if 'missing' in page: if hasattr(self, 'title'): raise PageError(self.title) else: raise PageError(pageid=self.pageid) # same thing for redirect, except it shows up in query instead of page for # whatever silly reason elif 'redirects' in query: if redirect: redirects = query['redirects'][0] if 'normalized' in query: normalized = query['normalized'][0] assert normalized['from'] == self.title, ODD_ERROR_MESSAGE from_title = normalized['to'] else: from_title = self.title assert redirects['from'] == from_title, ODD_ERROR_MESSAGE # change the title and reload the whole object self.__init__(redirects['to'], redirect=redirect, preload=preload) else: raise RedirectError(getattr(self, 'title', page['title'])) # since we only asked for disambiguation in ppprop, # if a pageprop is returned, # then the page must be a disambiguation page elif 'pageprops' in page: query_params = { 'prop': 'revisions', 'rvprop': 'content', 'rvparse': '', 'rvlimit': 1 } if hasattr(self, 'pageid'): query_params['pageids'] = self.pageid else: query_params['titles'] = self.title request = _wiki_request(query_params) html = request['query']['pages'][pageid]['revisions'][0]['*'] lis = BeautifulSoup(html, 'html.parser').find_all('li') filtered_lis = [li for li in lis if not 'tocsection' in ''.join(li.get('class', []))] may_refer_to = [li.a.get_text() for li in filtered_lis if li.a] raise DisambiguationError(getattr(self, 'title', page['title']), may_refer_to) else: self.pageid = pageid self.title = page['title'] self.url = page['fullurl']
Load basic information from Wikipedia. Confirm that page exists and is not a disambiguation/redirect. Does not need to be called manually, should be called automatically during __init__.
train
https://github.com/goldsmith/Wikipedia/blob/2065c568502b19b8634241b47fd96930d1bf948d/wikipedia/wikipedia.py#L318-L398
[ "def _wiki_request(params):\n '''\n Make a request to the Wikipedia API using the given search parameters.\n Returns a parsed dict of the JSON response.\n '''\n global RATE_LIMIT_LAST_CALL\n global USER_AGENT\n\n params['format'] = 'json'\n if not 'action' in params:\n params['action'] = 'query'\n\n headers = {\n 'User-Agent': USER_AGENT\n }\n\n if RATE_LIMIT and RATE_LIMIT_LAST_CALL and \\\n RATE_LIMIT_LAST_CALL + RATE_LIMIT_MIN_WAIT > datetime.now():\n\n # it hasn't been long enough since the last API call\n # so wait until we're in the clear to make the request\n\n wait_time = (RATE_LIMIT_LAST_CALL + RATE_LIMIT_MIN_WAIT) - datetime.now()\n time.sleep(int(wait_time.total_seconds()))\n\n r = requests.get(API_URL, params=params, headers=headers)\n\n if RATE_LIMIT:\n RATE_LIMIT_LAST_CALL = datetime.now()\n\n return r.json()\n", "def __init__(self, title=None, pageid=None, redirect=True, preload=False, original_title=''):\n if title is not None:\n self.title = title\n self.original_title = original_title or title\n elif pageid is not None:\n self.pageid = pageid\n else:\n raise ValueError(\"Either a title or a pageid must be specified\")\n\n self.__load(redirect=redirect, preload=preload)\n\n if preload:\n for prop in ('content', 'summary', 'images', 'references', 'links', 'sections'):\n getattr(self, prop)\n" ]
class WikipediaPage(object): ''' Contains data from a Wikipedia page. Uses property methods to filter data from the raw HTML. ''' def __init__(self, title=None, pageid=None, redirect=True, preload=False, original_title=''): if title is not None: self.title = title self.original_title = original_title or title elif pageid is not None: self.pageid = pageid else: raise ValueError("Either a title or a pageid must be specified") self.__load(redirect=redirect, preload=preload) if preload: for prop in ('content', 'summary', 'images', 'references', 'links', 'sections'): getattr(self, prop) def __repr__(self): return stdout_encode(u'<WikipediaPage \'{}\'>'.format(self.title)) def __eq__(self, other): try: return ( self.pageid == other.pageid and self.title == other.title and self.url == other.url ) except: return False def __continued_query(self, query_params): ''' Based on https://www.mediawiki.org/wiki/API:Query#Continuing_queries ''' query_params.update(self.__title_query_param) last_continue = {} prop = query_params.get('prop', None) while True: params = query_params.copy() params.update(last_continue) request = _wiki_request(params) if 'query' not in request: break pages = request['query']['pages'] if 'generator' in query_params: for datum in pages.values(): # in python 3.3+: "yield from pages.values()" yield datum else: for datum in pages[self.pageid][prop]: yield datum if 'continue' not in request: break last_continue = request['continue'] @property def __title_query_param(self): if getattr(self, 'title', None) is not None: return {'titles': self.title} else: return {'pageids': self.pageid} def html(self): ''' Get full page HTML. .. warning:: This can get pretty slow on long pages. ''' if not getattr(self, '_html', False): query_params = { 'prop': 'revisions', 'rvprop': 'content', 'rvlimit': 1, 'rvparse': '', 'titles': self.title } request = _wiki_request(query_params) self._html = request['query']['pages'][self.pageid]['revisions'][0]['*'] return self._html @property def content(self): ''' Plain text content of the page, excluding images, tables, and other data. ''' if not getattr(self, '_content', False): query_params = { 'prop': 'extracts|revisions', 'explaintext': '', 'rvprop': 'ids' } if not getattr(self, 'title', None) is None: query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) self._content = request['query']['pages'][self.pageid]['extract'] self._revision_id = request['query']['pages'][self.pageid]['revisions'][0]['revid'] self._parent_id = request['query']['pages'][self.pageid]['revisions'][0]['parentid'] return self._content @property def revision_id(self): ''' Revision ID of the page. The revision ID is a number that uniquely identifies the current version of the page. It can be used to create the permalink or for other direct API calls. See `Help:Page history <http://en.wikipedia.org/wiki/Wikipedia:Revision>`_ for more information. ''' if not getattr(self, '_revid', False): # fetch the content (side effect is loading the revid) self.content return self._revision_id @property def parent_id(self): ''' Revision ID of the parent version of the current revision of this page. See ``revision_id`` for more information. ''' if not getattr(self, '_parentid', False): # fetch the content (side effect is loading the revid) self.content return self._parent_id @property def summary(self): ''' Plain text summary of the page. ''' if not getattr(self, '_summary', False): query_params = { 'prop': 'extracts', 'explaintext': '', 'exintro': '', } if not getattr(self, 'title', None) is None: query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) self._summary = request['query']['pages'][self.pageid]['extract'] return self._summary @property def images(self): ''' List of URLs of images on the page. ''' if not getattr(self, '_images', False): self._images = [ page['imageinfo'][0]['url'] for page in self.__continued_query({ 'generator': 'images', 'gimlimit': 'max', 'prop': 'imageinfo', 'iiprop': 'url', }) if 'imageinfo' in page ] return self._images @property def coordinates(self): ''' Tuple of Decimals in the form of (lat, lon) or None ''' if not getattr(self, '_coordinates', False): query_params = { 'prop': 'coordinates', 'colimit': 'max', 'titles': self.title, } request = _wiki_request(query_params) if 'query' in request: coordinates = request['query']['pages'][self.pageid]['coordinates'] self._coordinates = (Decimal(coordinates[0]['lat']), Decimal(coordinates[0]['lon'])) else: self._coordinates = None return self._coordinates @property def references(self): ''' List of URLs of external links on a page. May include external links within page that aren't technically cited anywhere. ''' if not getattr(self, '_references', False): def add_protocol(url): return url if url.startswith('http') else 'http:' + url self._references = [ add_protocol(link['*']) for link in self.__continued_query({ 'prop': 'extlinks', 'ellimit': 'max' }) ] return self._references @property def links(self): ''' List of titles of Wikipedia page links on a page. .. note:: Only includes articles from namespace 0, meaning no Category, User talk, or other meta-Wikipedia pages. ''' if not getattr(self, '_links', False): self._links = [ link['title'] for link in self.__continued_query({ 'prop': 'links', 'plnamespace': 0, 'pllimit': 'max' }) ] return self._links @property def categories(self): ''' List of categories of a page. ''' if not getattr(self, '_categories', False): self._categories = [re.sub(r'^Category:', '', x) for x in [link['title'] for link in self.__continued_query({ 'prop': 'categories', 'cllimit': 'max' }) ]] return self._categories @property def sections(self): ''' List of section titles from the table of contents on the page. ''' if not getattr(self, '_sections', False): query_params = { 'action': 'parse', 'prop': 'sections', } query_params.update(self.__title_query_param) request = _wiki_request(query_params) self._sections = [section['line'] for section in request['parse']['sections']] return self._sections def section(self, section_title): ''' Get the plain text content of a section from `self.sections`. Returns None if `section_title` isn't found, otherwise returns a whitespace stripped string. This is a convenience method that wraps self.content. .. warning:: Calling `section` on a section that has subheadings will NOT return the full text of all of the subsections. It only gets the text between `section_title` and the next subheading, which is often empty. ''' section = u"== {} ==".format(section_title) try: index = self.content.index(section) + len(section) except ValueError: return None try: next_index = self.content.index("==", index) except ValueError: next_index = len(self.content) return self.content[index:next_index].lstrip("=").strip()
goldsmith/Wikipedia
wikipedia/wikipedia.py
WikipediaPage.__continued_query
python
def __continued_query(self, query_params): ''' Based on https://www.mediawiki.org/wiki/API:Query#Continuing_queries ''' query_params.update(self.__title_query_param) last_continue = {} prop = query_params.get('prop', None) while True: params = query_params.copy() params.update(last_continue) request = _wiki_request(params) if 'query' not in request: break pages = request['query']['pages'] if 'generator' in query_params: for datum in pages.values(): # in python 3.3+: "yield from pages.values()" yield datum else: for datum in pages[self.pageid][prop]: yield datum if 'continue' not in request: break last_continue = request['continue']
Based on https://www.mediawiki.org/wiki/API:Query#Continuing_queries
train
https://github.com/goldsmith/Wikipedia/blob/2065c568502b19b8634241b47fd96930d1bf948d/wikipedia/wikipedia.py#L400-L429
[ "def _wiki_request(params):\n '''\n Make a request to the Wikipedia API using the given search parameters.\n Returns a parsed dict of the JSON response.\n '''\n global RATE_LIMIT_LAST_CALL\n global USER_AGENT\n\n params['format'] = 'json'\n if not 'action' in params:\n params['action'] = 'query'\n\n headers = {\n 'User-Agent': USER_AGENT\n }\n\n if RATE_LIMIT and RATE_LIMIT_LAST_CALL and \\\n RATE_LIMIT_LAST_CALL + RATE_LIMIT_MIN_WAIT > datetime.now():\n\n # it hasn't been long enough since the last API call\n # so wait until we're in the clear to make the request\n\n wait_time = (RATE_LIMIT_LAST_CALL + RATE_LIMIT_MIN_WAIT) - datetime.now()\n time.sleep(int(wait_time.total_seconds()))\n\n r = requests.get(API_URL, params=params, headers=headers)\n\n if RATE_LIMIT:\n RATE_LIMIT_LAST_CALL = datetime.now()\n\n return r.json()\n" ]
class WikipediaPage(object): ''' Contains data from a Wikipedia page. Uses property methods to filter data from the raw HTML. ''' def __init__(self, title=None, pageid=None, redirect=True, preload=False, original_title=''): if title is not None: self.title = title self.original_title = original_title or title elif pageid is not None: self.pageid = pageid else: raise ValueError("Either a title or a pageid must be specified") self.__load(redirect=redirect, preload=preload) if preload: for prop in ('content', 'summary', 'images', 'references', 'links', 'sections'): getattr(self, prop) def __repr__(self): return stdout_encode(u'<WikipediaPage \'{}\'>'.format(self.title)) def __eq__(self, other): try: return ( self.pageid == other.pageid and self.title == other.title and self.url == other.url ) except: return False def __load(self, redirect=True, preload=False): ''' Load basic information from Wikipedia. Confirm that page exists and is not a disambiguation/redirect. Does not need to be called manually, should be called automatically during __init__. ''' query_params = { 'prop': 'info|pageprops', 'inprop': 'url', 'ppprop': 'disambiguation', 'redirects': '', } if not getattr(self, 'pageid', None): query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) query = request['query'] pageid = list(query['pages'].keys())[0] page = query['pages'][pageid] # missing is present if the page is missing if 'missing' in page: if hasattr(self, 'title'): raise PageError(self.title) else: raise PageError(pageid=self.pageid) # same thing for redirect, except it shows up in query instead of page for # whatever silly reason elif 'redirects' in query: if redirect: redirects = query['redirects'][0] if 'normalized' in query: normalized = query['normalized'][0] assert normalized['from'] == self.title, ODD_ERROR_MESSAGE from_title = normalized['to'] else: from_title = self.title assert redirects['from'] == from_title, ODD_ERROR_MESSAGE # change the title and reload the whole object self.__init__(redirects['to'], redirect=redirect, preload=preload) else: raise RedirectError(getattr(self, 'title', page['title'])) # since we only asked for disambiguation in ppprop, # if a pageprop is returned, # then the page must be a disambiguation page elif 'pageprops' in page: query_params = { 'prop': 'revisions', 'rvprop': 'content', 'rvparse': '', 'rvlimit': 1 } if hasattr(self, 'pageid'): query_params['pageids'] = self.pageid else: query_params['titles'] = self.title request = _wiki_request(query_params) html = request['query']['pages'][pageid]['revisions'][0]['*'] lis = BeautifulSoup(html, 'html.parser').find_all('li') filtered_lis = [li for li in lis if not 'tocsection' in ''.join(li.get('class', []))] may_refer_to = [li.a.get_text() for li in filtered_lis if li.a] raise DisambiguationError(getattr(self, 'title', page['title']), may_refer_to) else: self.pageid = pageid self.title = page['title'] self.url = page['fullurl'] @property def __title_query_param(self): if getattr(self, 'title', None) is not None: return {'titles': self.title} else: return {'pageids': self.pageid} def html(self): ''' Get full page HTML. .. warning:: This can get pretty slow on long pages. ''' if not getattr(self, '_html', False): query_params = { 'prop': 'revisions', 'rvprop': 'content', 'rvlimit': 1, 'rvparse': '', 'titles': self.title } request = _wiki_request(query_params) self._html = request['query']['pages'][self.pageid]['revisions'][0]['*'] return self._html @property def content(self): ''' Plain text content of the page, excluding images, tables, and other data. ''' if not getattr(self, '_content', False): query_params = { 'prop': 'extracts|revisions', 'explaintext': '', 'rvprop': 'ids' } if not getattr(self, 'title', None) is None: query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) self._content = request['query']['pages'][self.pageid]['extract'] self._revision_id = request['query']['pages'][self.pageid]['revisions'][0]['revid'] self._parent_id = request['query']['pages'][self.pageid]['revisions'][0]['parentid'] return self._content @property def revision_id(self): ''' Revision ID of the page. The revision ID is a number that uniquely identifies the current version of the page. It can be used to create the permalink or for other direct API calls. See `Help:Page history <http://en.wikipedia.org/wiki/Wikipedia:Revision>`_ for more information. ''' if not getattr(self, '_revid', False): # fetch the content (side effect is loading the revid) self.content return self._revision_id @property def parent_id(self): ''' Revision ID of the parent version of the current revision of this page. See ``revision_id`` for more information. ''' if not getattr(self, '_parentid', False): # fetch the content (side effect is loading the revid) self.content return self._parent_id @property def summary(self): ''' Plain text summary of the page. ''' if not getattr(self, '_summary', False): query_params = { 'prop': 'extracts', 'explaintext': '', 'exintro': '', } if not getattr(self, 'title', None) is None: query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) self._summary = request['query']['pages'][self.pageid]['extract'] return self._summary @property def images(self): ''' List of URLs of images on the page. ''' if not getattr(self, '_images', False): self._images = [ page['imageinfo'][0]['url'] for page in self.__continued_query({ 'generator': 'images', 'gimlimit': 'max', 'prop': 'imageinfo', 'iiprop': 'url', }) if 'imageinfo' in page ] return self._images @property def coordinates(self): ''' Tuple of Decimals in the form of (lat, lon) or None ''' if not getattr(self, '_coordinates', False): query_params = { 'prop': 'coordinates', 'colimit': 'max', 'titles': self.title, } request = _wiki_request(query_params) if 'query' in request: coordinates = request['query']['pages'][self.pageid]['coordinates'] self._coordinates = (Decimal(coordinates[0]['lat']), Decimal(coordinates[0]['lon'])) else: self._coordinates = None return self._coordinates @property def references(self): ''' List of URLs of external links on a page. May include external links within page that aren't technically cited anywhere. ''' if not getattr(self, '_references', False): def add_protocol(url): return url if url.startswith('http') else 'http:' + url self._references = [ add_protocol(link['*']) for link in self.__continued_query({ 'prop': 'extlinks', 'ellimit': 'max' }) ] return self._references @property def links(self): ''' List of titles of Wikipedia page links on a page. .. note:: Only includes articles from namespace 0, meaning no Category, User talk, or other meta-Wikipedia pages. ''' if not getattr(self, '_links', False): self._links = [ link['title'] for link in self.__continued_query({ 'prop': 'links', 'plnamespace': 0, 'pllimit': 'max' }) ] return self._links @property def categories(self): ''' List of categories of a page. ''' if not getattr(self, '_categories', False): self._categories = [re.sub(r'^Category:', '', x) for x in [link['title'] for link in self.__continued_query({ 'prop': 'categories', 'cllimit': 'max' }) ]] return self._categories @property def sections(self): ''' List of section titles from the table of contents on the page. ''' if not getattr(self, '_sections', False): query_params = { 'action': 'parse', 'prop': 'sections', } query_params.update(self.__title_query_param) request = _wiki_request(query_params) self._sections = [section['line'] for section in request['parse']['sections']] return self._sections def section(self, section_title): ''' Get the plain text content of a section from `self.sections`. Returns None if `section_title` isn't found, otherwise returns a whitespace stripped string. This is a convenience method that wraps self.content. .. warning:: Calling `section` on a section that has subheadings will NOT return the full text of all of the subsections. It only gets the text between `section_title` and the next subheading, which is often empty. ''' section = u"== {} ==".format(section_title) try: index = self.content.index(section) + len(section) except ValueError: return None try: next_index = self.content.index("==", index) except ValueError: next_index = len(self.content) return self.content[index:next_index].lstrip("=").strip()
goldsmith/Wikipedia
wikipedia/wikipedia.py
WikipediaPage.html
python
def html(self): ''' Get full page HTML. .. warning:: This can get pretty slow on long pages. ''' if not getattr(self, '_html', False): query_params = { 'prop': 'revisions', 'rvprop': 'content', 'rvlimit': 1, 'rvparse': '', 'titles': self.title } request = _wiki_request(query_params) self._html = request['query']['pages'][self.pageid]['revisions'][0]['*'] return self._html
Get full page HTML. .. warning:: This can get pretty slow on long pages.
train
https://github.com/goldsmith/Wikipedia/blob/2065c568502b19b8634241b47fd96930d1bf948d/wikipedia/wikipedia.py#L438-L457
[ "def _wiki_request(params):\n '''\n Make a request to the Wikipedia API using the given search parameters.\n Returns a parsed dict of the JSON response.\n '''\n global RATE_LIMIT_LAST_CALL\n global USER_AGENT\n\n params['format'] = 'json'\n if not 'action' in params:\n params['action'] = 'query'\n\n headers = {\n 'User-Agent': USER_AGENT\n }\n\n if RATE_LIMIT and RATE_LIMIT_LAST_CALL and \\\n RATE_LIMIT_LAST_CALL + RATE_LIMIT_MIN_WAIT > datetime.now():\n\n # it hasn't been long enough since the last API call\n # so wait until we're in the clear to make the request\n\n wait_time = (RATE_LIMIT_LAST_CALL + RATE_LIMIT_MIN_WAIT) - datetime.now()\n time.sleep(int(wait_time.total_seconds()))\n\n r = requests.get(API_URL, params=params, headers=headers)\n\n if RATE_LIMIT:\n RATE_LIMIT_LAST_CALL = datetime.now()\n\n return r.json()\n" ]
class WikipediaPage(object): ''' Contains data from a Wikipedia page. Uses property methods to filter data from the raw HTML. ''' def __init__(self, title=None, pageid=None, redirect=True, preload=False, original_title=''): if title is not None: self.title = title self.original_title = original_title or title elif pageid is not None: self.pageid = pageid else: raise ValueError("Either a title or a pageid must be specified") self.__load(redirect=redirect, preload=preload) if preload: for prop in ('content', 'summary', 'images', 'references', 'links', 'sections'): getattr(self, prop) def __repr__(self): return stdout_encode(u'<WikipediaPage \'{}\'>'.format(self.title)) def __eq__(self, other): try: return ( self.pageid == other.pageid and self.title == other.title and self.url == other.url ) except: return False def __load(self, redirect=True, preload=False): ''' Load basic information from Wikipedia. Confirm that page exists and is not a disambiguation/redirect. Does not need to be called manually, should be called automatically during __init__. ''' query_params = { 'prop': 'info|pageprops', 'inprop': 'url', 'ppprop': 'disambiguation', 'redirects': '', } if not getattr(self, 'pageid', None): query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) query = request['query'] pageid = list(query['pages'].keys())[0] page = query['pages'][pageid] # missing is present if the page is missing if 'missing' in page: if hasattr(self, 'title'): raise PageError(self.title) else: raise PageError(pageid=self.pageid) # same thing for redirect, except it shows up in query instead of page for # whatever silly reason elif 'redirects' in query: if redirect: redirects = query['redirects'][0] if 'normalized' in query: normalized = query['normalized'][0] assert normalized['from'] == self.title, ODD_ERROR_MESSAGE from_title = normalized['to'] else: from_title = self.title assert redirects['from'] == from_title, ODD_ERROR_MESSAGE # change the title and reload the whole object self.__init__(redirects['to'], redirect=redirect, preload=preload) else: raise RedirectError(getattr(self, 'title', page['title'])) # since we only asked for disambiguation in ppprop, # if a pageprop is returned, # then the page must be a disambiguation page elif 'pageprops' in page: query_params = { 'prop': 'revisions', 'rvprop': 'content', 'rvparse': '', 'rvlimit': 1 } if hasattr(self, 'pageid'): query_params['pageids'] = self.pageid else: query_params['titles'] = self.title request = _wiki_request(query_params) html = request['query']['pages'][pageid]['revisions'][0]['*'] lis = BeautifulSoup(html, 'html.parser').find_all('li') filtered_lis = [li for li in lis if not 'tocsection' in ''.join(li.get('class', []))] may_refer_to = [li.a.get_text() for li in filtered_lis if li.a] raise DisambiguationError(getattr(self, 'title', page['title']), may_refer_to) else: self.pageid = pageid self.title = page['title'] self.url = page['fullurl'] def __continued_query(self, query_params): ''' Based on https://www.mediawiki.org/wiki/API:Query#Continuing_queries ''' query_params.update(self.__title_query_param) last_continue = {} prop = query_params.get('prop', None) while True: params = query_params.copy() params.update(last_continue) request = _wiki_request(params) if 'query' not in request: break pages = request['query']['pages'] if 'generator' in query_params: for datum in pages.values(): # in python 3.3+: "yield from pages.values()" yield datum else: for datum in pages[self.pageid][prop]: yield datum if 'continue' not in request: break last_continue = request['continue'] @property def __title_query_param(self): if getattr(self, 'title', None) is not None: return {'titles': self.title} else: return {'pageids': self.pageid} @property def content(self): ''' Plain text content of the page, excluding images, tables, and other data. ''' if not getattr(self, '_content', False): query_params = { 'prop': 'extracts|revisions', 'explaintext': '', 'rvprop': 'ids' } if not getattr(self, 'title', None) is None: query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) self._content = request['query']['pages'][self.pageid]['extract'] self._revision_id = request['query']['pages'][self.pageid]['revisions'][0]['revid'] self._parent_id = request['query']['pages'][self.pageid]['revisions'][0]['parentid'] return self._content @property def revision_id(self): ''' Revision ID of the page. The revision ID is a number that uniquely identifies the current version of the page. It can be used to create the permalink or for other direct API calls. See `Help:Page history <http://en.wikipedia.org/wiki/Wikipedia:Revision>`_ for more information. ''' if not getattr(self, '_revid', False): # fetch the content (side effect is loading the revid) self.content return self._revision_id @property def parent_id(self): ''' Revision ID of the parent version of the current revision of this page. See ``revision_id`` for more information. ''' if not getattr(self, '_parentid', False): # fetch the content (side effect is loading the revid) self.content return self._parent_id @property def summary(self): ''' Plain text summary of the page. ''' if not getattr(self, '_summary', False): query_params = { 'prop': 'extracts', 'explaintext': '', 'exintro': '', } if not getattr(self, 'title', None) is None: query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) self._summary = request['query']['pages'][self.pageid]['extract'] return self._summary @property def images(self): ''' List of URLs of images on the page. ''' if not getattr(self, '_images', False): self._images = [ page['imageinfo'][0]['url'] for page in self.__continued_query({ 'generator': 'images', 'gimlimit': 'max', 'prop': 'imageinfo', 'iiprop': 'url', }) if 'imageinfo' in page ] return self._images @property def coordinates(self): ''' Tuple of Decimals in the form of (lat, lon) or None ''' if not getattr(self, '_coordinates', False): query_params = { 'prop': 'coordinates', 'colimit': 'max', 'titles': self.title, } request = _wiki_request(query_params) if 'query' in request: coordinates = request['query']['pages'][self.pageid]['coordinates'] self._coordinates = (Decimal(coordinates[0]['lat']), Decimal(coordinates[0]['lon'])) else: self._coordinates = None return self._coordinates @property def references(self): ''' List of URLs of external links on a page. May include external links within page that aren't technically cited anywhere. ''' if not getattr(self, '_references', False): def add_protocol(url): return url if url.startswith('http') else 'http:' + url self._references = [ add_protocol(link['*']) for link in self.__continued_query({ 'prop': 'extlinks', 'ellimit': 'max' }) ] return self._references @property def links(self): ''' List of titles of Wikipedia page links on a page. .. note:: Only includes articles from namespace 0, meaning no Category, User talk, or other meta-Wikipedia pages. ''' if not getattr(self, '_links', False): self._links = [ link['title'] for link in self.__continued_query({ 'prop': 'links', 'plnamespace': 0, 'pllimit': 'max' }) ] return self._links @property def categories(self): ''' List of categories of a page. ''' if not getattr(self, '_categories', False): self._categories = [re.sub(r'^Category:', '', x) for x in [link['title'] for link in self.__continued_query({ 'prop': 'categories', 'cllimit': 'max' }) ]] return self._categories @property def sections(self): ''' List of section titles from the table of contents on the page. ''' if not getattr(self, '_sections', False): query_params = { 'action': 'parse', 'prop': 'sections', } query_params.update(self.__title_query_param) request = _wiki_request(query_params) self._sections = [section['line'] for section in request['parse']['sections']] return self._sections def section(self, section_title): ''' Get the plain text content of a section from `self.sections`. Returns None if `section_title` isn't found, otherwise returns a whitespace stripped string. This is a convenience method that wraps self.content. .. warning:: Calling `section` on a section that has subheadings will NOT return the full text of all of the subsections. It only gets the text between `section_title` and the next subheading, which is often empty. ''' section = u"== {} ==".format(section_title) try: index = self.content.index(section) + len(section) except ValueError: return None try: next_index = self.content.index("==", index) except ValueError: next_index = len(self.content) return self.content[index:next_index].lstrip("=").strip()
goldsmith/Wikipedia
wikipedia/wikipedia.py
WikipediaPage.content
python
def content(self): ''' Plain text content of the page, excluding images, tables, and other data. ''' if not getattr(self, '_content', False): query_params = { 'prop': 'extracts|revisions', 'explaintext': '', 'rvprop': 'ids' } if not getattr(self, 'title', None) is None: query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) self._content = request['query']['pages'][self.pageid]['extract'] self._revision_id = request['query']['pages'][self.pageid]['revisions'][0]['revid'] self._parent_id = request['query']['pages'][self.pageid]['revisions'][0]['parentid'] return self._content
Plain text content of the page, excluding images, tables, and other data.
train
https://github.com/goldsmith/Wikipedia/blob/2065c568502b19b8634241b47fd96930d1bf948d/wikipedia/wikipedia.py#L460-L480
[ "def _wiki_request(params):\n '''\n Make a request to the Wikipedia API using the given search parameters.\n Returns a parsed dict of the JSON response.\n '''\n global RATE_LIMIT_LAST_CALL\n global USER_AGENT\n\n params['format'] = 'json'\n if not 'action' in params:\n params['action'] = 'query'\n\n headers = {\n 'User-Agent': USER_AGENT\n }\n\n if RATE_LIMIT and RATE_LIMIT_LAST_CALL and \\\n RATE_LIMIT_LAST_CALL + RATE_LIMIT_MIN_WAIT > datetime.now():\n\n # it hasn't been long enough since the last API call\n # so wait until we're in the clear to make the request\n\n wait_time = (RATE_LIMIT_LAST_CALL + RATE_LIMIT_MIN_WAIT) - datetime.now()\n time.sleep(int(wait_time.total_seconds()))\n\n r = requests.get(API_URL, params=params, headers=headers)\n\n if RATE_LIMIT:\n RATE_LIMIT_LAST_CALL = datetime.now()\n\n return r.json()\n" ]
class WikipediaPage(object): ''' Contains data from a Wikipedia page. Uses property methods to filter data from the raw HTML. ''' def __init__(self, title=None, pageid=None, redirect=True, preload=False, original_title=''): if title is not None: self.title = title self.original_title = original_title or title elif pageid is not None: self.pageid = pageid else: raise ValueError("Either a title or a pageid must be specified") self.__load(redirect=redirect, preload=preload) if preload: for prop in ('content', 'summary', 'images', 'references', 'links', 'sections'): getattr(self, prop) def __repr__(self): return stdout_encode(u'<WikipediaPage \'{}\'>'.format(self.title)) def __eq__(self, other): try: return ( self.pageid == other.pageid and self.title == other.title and self.url == other.url ) except: return False def __load(self, redirect=True, preload=False): ''' Load basic information from Wikipedia. Confirm that page exists and is not a disambiguation/redirect. Does not need to be called manually, should be called automatically during __init__. ''' query_params = { 'prop': 'info|pageprops', 'inprop': 'url', 'ppprop': 'disambiguation', 'redirects': '', } if not getattr(self, 'pageid', None): query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) query = request['query'] pageid = list(query['pages'].keys())[0] page = query['pages'][pageid] # missing is present if the page is missing if 'missing' in page: if hasattr(self, 'title'): raise PageError(self.title) else: raise PageError(pageid=self.pageid) # same thing for redirect, except it shows up in query instead of page for # whatever silly reason elif 'redirects' in query: if redirect: redirects = query['redirects'][0] if 'normalized' in query: normalized = query['normalized'][0] assert normalized['from'] == self.title, ODD_ERROR_MESSAGE from_title = normalized['to'] else: from_title = self.title assert redirects['from'] == from_title, ODD_ERROR_MESSAGE # change the title and reload the whole object self.__init__(redirects['to'], redirect=redirect, preload=preload) else: raise RedirectError(getattr(self, 'title', page['title'])) # since we only asked for disambiguation in ppprop, # if a pageprop is returned, # then the page must be a disambiguation page elif 'pageprops' in page: query_params = { 'prop': 'revisions', 'rvprop': 'content', 'rvparse': '', 'rvlimit': 1 } if hasattr(self, 'pageid'): query_params['pageids'] = self.pageid else: query_params['titles'] = self.title request = _wiki_request(query_params) html = request['query']['pages'][pageid]['revisions'][0]['*'] lis = BeautifulSoup(html, 'html.parser').find_all('li') filtered_lis = [li for li in lis if not 'tocsection' in ''.join(li.get('class', []))] may_refer_to = [li.a.get_text() for li in filtered_lis if li.a] raise DisambiguationError(getattr(self, 'title', page['title']), may_refer_to) else: self.pageid = pageid self.title = page['title'] self.url = page['fullurl'] def __continued_query(self, query_params): ''' Based on https://www.mediawiki.org/wiki/API:Query#Continuing_queries ''' query_params.update(self.__title_query_param) last_continue = {} prop = query_params.get('prop', None) while True: params = query_params.copy() params.update(last_continue) request = _wiki_request(params) if 'query' not in request: break pages = request['query']['pages'] if 'generator' in query_params: for datum in pages.values(): # in python 3.3+: "yield from pages.values()" yield datum else: for datum in pages[self.pageid][prop]: yield datum if 'continue' not in request: break last_continue = request['continue'] @property def __title_query_param(self): if getattr(self, 'title', None) is not None: return {'titles': self.title} else: return {'pageids': self.pageid} def html(self): ''' Get full page HTML. .. warning:: This can get pretty slow on long pages. ''' if not getattr(self, '_html', False): query_params = { 'prop': 'revisions', 'rvprop': 'content', 'rvlimit': 1, 'rvparse': '', 'titles': self.title } request = _wiki_request(query_params) self._html = request['query']['pages'][self.pageid]['revisions'][0]['*'] return self._html @property @property def revision_id(self): ''' Revision ID of the page. The revision ID is a number that uniquely identifies the current version of the page. It can be used to create the permalink or for other direct API calls. See `Help:Page history <http://en.wikipedia.org/wiki/Wikipedia:Revision>`_ for more information. ''' if not getattr(self, '_revid', False): # fetch the content (side effect is loading the revid) self.content return self._revision_id @property def parent_id(self): ''' Revision ID of the parent version of the current revision of this page. See ``revision_id`` for more information. ''' if not getattr(self, '_parentid', False): # fetch the content (side effect is loading the revid) self.content return self._parent_id @property def summary(self): ''' Plain text summary of the page. ''' if not getattr(self, '_summary', False): query_params = { 'prop': 'extracts', 'explaintext': '', 'exintro': '', } if not getattr(self, 'title', None) is None: query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) self._summary = request['query']['pages'][self.pageid]['extract'] return self._summary @property def images(self): ''' List of URLs of images on the page. ''' if not getattr(self, '_images', False): self._images = [ page['imageinfo'][0]['url'] for page in self.__continued_query({ 'generator': 'images', 'gimlimit': 'max', 'prop': 'imageinfo', 'iiprop': 'url', }) if 'imageinfo' in page ] return self._images @property def coordinates(self): ''' Tuple of Decimals in the form of (lat, lon) or None ''' if not getattr(self, '_coordinates', False): query_params = { 'prop': 'coordinates', 'colimit': 'max', 'titles': self.title, } request = _wiki_request(query_params) if 'query' in request: coordinates = request['query']['pages'][self.pageid]['coordinates'] self._coordinates = (Decimal(coordinates[0]['lat']), Decimal(coordinates[0]['lon'])) else: self._coordinates = None return self._coordinates @property def references(self): ''' List of URLs of external links on a page. May include external links within page that aren't technically cited anywhere. ''' if not getattr(self, '_references', False): def add_protocol(url): return url if url.startswith('http') else 'http:' + url self._references = [ add_protocol(link['*']) for link in self.__continued_query({ 'prop': 'extlinks', 'ellimit': 'max' }) ] return self._references @property def links(self): ''' List of titles of Wikipedia page links on a page. .. note:: Only includes articles from namespace 0, meaning no Category, User talk, or other meta-Wikipedia pages. ''' if not getattr(self, '_links', False): self._links = [ link['title'] for link in self.__continued_query({ 'prop': 'links', 'plnamespace': 0, 'pllimit': 'max' }) ] return self._links @property def categories(self): ''' List of categories of a page. ''' if not getattr(self, '_categories', False): self._categories = [re.sub(r'^Category:', '', x) for x in [link['title'] for link in self.__continued_query({ 'prop': 'categories', 'cllimit': 'max' }) ]] return self._categories @property def sections(self): ''' List of section titles from the table of contents on the page. ''' if not getattr(self, '_sections', False): query_params = { 'action': 'parse', 'prop': 'sections', } query_params.update(self.__title_query_param) request = _wiki_request(query_params) self._sections = [section['line'] for section in request['parse']['sections']] return self._sections def section(self, section_title): ''' Get the plain text content of a section from `self.sections`. Returns None if `section_title` isn't found, otherwise returns a whitespace stripped string. This is a convenience method that wraps self.content. .. warning:: Calling `section` on a section that has subheadings will NOT return the full text of all of the subsections. It only gets the text between `section_title` and the next subheading, which is often empty. ''' section = u"== {} ==".format(section_title) try: index = self.content.index(section) + len(section) except ValueError: return None try: next_index = self.content.index("==", index) except ValueError: next_index = len(self.content) return self.content[index:next_index].lstrip("=").strip()
goldsmith/Wikipedia
wikipedia/wikipedia.py
WikipediaPage.summary
python
def summary(self): ''' Plain text summary of the page. ''' if not getattr(self, '_summary', False): query_params = { 'prop': 'extracts', 'explaintext': '', 'exintro': '', } if not getattr(self, 'title', None) is None: query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) self._summary = request['query']['pages'][self.pageid]['extract'] return self._summary
Plain text summary of the page.
train
https://github.com/goldsmith/Wikipedia/blob/2065c568502b19b8634241b47fd96930d1bf948d/wikipedia/wikipedia.py#L514-L533
[ "def _wiki_request(params):\n '''\n Make a request to the Wikipedia API using the given search parameters.\n Returns a parsed dict of the JSON response.\n '''\n global RATE_LIMIT_LAST_CALL\n global USER_AGENT\n\n params['format'] = 'json'\n if not 'action' in params:\n params['action'] = 'query'\n\n headers = {\n 'User-Agent': USER_AGENT\n }\n\n if RATE_LIMIT and RATE_LIMIT_LAST_CALL and \\\n RATE_LIMIT_LAST_CALL + RATE_LIMIT_MIN_WAIT > datetime.now():\n\n # it hasn't been long enough since the last API call\n # so wait until we're in the clear to make the request\n\n wait_time = (RATE_LIMIT_LAST_CALL + RATE_LIMIT_MIN_WAIT) - datetime.now()\n time.sleep(int(wait_time.total_seconds()))\n\n r = requests.get(API_URL, params=params, headers=headers)\n\n if RATE_LIMIT:\n RATE_LIMIT_LAST_CALL = datetime.now()\n\n return r.json()\n" ]
class WikipediaPage(object): ''' Contains data from a Wikipedia page. Uses property methods to filter data from the raw HTML. ''' def __init__(self, title=None, pageid=None, redirect=True, preload=False, original_title=''): if title is not None: self.title = title self.original_title = original_title or title elif pageid is not None: self.pageid = pageid else: raise ValueError("Either a title or a pageid must be specified") self.__load(redirect=redirect, preload=preload) if preload: for prop in ('content', 'summary', 'images', 'references', 'links', 'sections'): getattr(self, prop) def __repr__(self): return stdout_encode(u'<WikipediaPage \'{}\'>'.format(self.title)) def __eq__(self, other): try: return ( self.pageid == other.pageid and self.title == other.title and self.url == other.url ) except: return False def __load(self, redirect=True, preload=False): ''' Load basic information from Wikipedia. Confirm that page exists and is not a disambiguation/redirect. Does not need to be called manually, should be called automatically during __init__. ''' query_params = { 'prop': 'info|pageprops', 'inprop': 'url', 'ppprop': 'disambiguation', 'redirects': '', } if not getattr(self, 'pageid', None): query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) query = request['query'] pageid = list(query['pages'].keys())[0] page = query['pages'][pageid] # missing is present if the page is missing if 'missing' in page: if hasattr(self, 'title'): raise PageError(self.title) else: raise PageError(pageid=self.pageid) # same thing for redirect, except it shows up in query instead of page for # whatever silly reason elif 'redirects' in query: if redirect: redirects = query['redirects'][0] if 'normalized' in query: normalized = query['normalized'][0] assert normalized['from'] == self.title, ODD_ERROR_MESSAGE from_title = normalized['to'] else: from_title = self.title assert redirects['from'] == from_title, ODD_ERROR_MESSAGE # change the title and reload the whole object self.__init__(redirects['to'], redirect=redirect, preload=preload) else: raise RedirectError(getattr(self, 'title', page['title'])) # since we only asked for disambiguation in ppprop, # if a pageprop is returned, # then the page must be a disambiguation page elif 'pageprops' in page: query_params = { 'prop': 'revisions', 'rvprop': 'content', 'rvparse': '', 'rvlimit': 1 } if hasattr(self, 'pageid'): query_params['pageids'] = self.pageid else: query_params['titles'] = self.title request = _wiki_request(query_params) html = request['query']['pages'][pageid]['revisions'][0]['*'] lis = BeautifulSoup(html, 'html.parser').find_all('li') filtered_lis = [li for li in lis if not 'tocsection' in ''.join(li.get('class', []))] may_refer_to = [li.a.get_text() for li in filtered_lis if li.a] raise DisambiguationError(getattr(self, 'title', page['title']), may_refer_to) else: self.pageid = pageid self.title = page['title'] self.url = page['fullurl'] def __continued_query(self, query_params): ''' Based on https://www.mediawiki.org/wiki/API:Query#Continuing_queries ''' query_params.update(self.__title_query_param) last_continue = {} prop = query_params.get('prop', None) while True: params = query_params.copy() params.update(last_continue) request = _wiki_request(params) if 'query' not in request: break pages = request['query']['pages'] if 'generator' in query_params: for datum in pages.values(): # in python 3.3+: "yield from pages.values()" yield datum else: for datum in pages[self.pageid][prop]: yield datum if 'continue' not in request: break last_continue = request['continue'] @property def __title_query_param(self): if getattr(self, 'title', None) is not None: return {'titles': self.title} else: return {'pageids': self.pageid} def html(self): ''' Get full page HTML. .. warning:: This can get pretty slow on long pages. ''' if not getattr(self, '_html', False): query_params = { 'prop': 'revisions', 'rvprop': 'content', 'rvlimit': 1, 'rvparse': '', 'titles': self.title } request = _wiki_request(query_params) self._html = request['query']['pages'][self.pageid]['revisions'][0]['*'] return self._html @property def content(self): ''' Plain text content of the page, excluding images, tables, and other data. ''' if not getattr(self, '_content', False): query_params = { 'prop': 'extracts|revisions', 'explaintext': '', 'rvprop': 'ids' } if not getattr(self, 'title', None) is None: query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) self._content = request['query']['pages'][self.pageid]['extract'] self._revision_id = request['query']['pages'][self.pageid]['revisions'][0]['revid'] self._parent_id = request['query']['pages'][self.pageid]['revisions'][0]['parentid'] return self._content @property def revision_id(self): ''' Revision ID of the page. The revision ID is a number that uniquely identifies the current version of the page. It can be used to create the permalink or for other direct API calls. See `Help:Page history <http://en.wikipedia.org/wiki/Wikipedia:Revision>`_ for more information. ''' if not getattr(self, '_revid', False): # fetch the content (side effect is loading the revid) self.content return self._revision_id @property def parent_id(self): ''' Revision ID of the parent version of the current revision of this page. See ``revision_id`` for more information. ''' if not getattr(self, '_parentid', False): # fetch the content (side effect is loading the revid) self.content return self._parent_id @property @property def images(self): ''' List of URLs of images on the page. ''' if not getattr(self, '_images', False): self._images = [ page['imageinfo'][0]['url'] for page in self.__continued_query({ 'generator': 'images', 'gimlimit': 'max', 'prop': 'imageinfo', 'iiprop': 'url', }) if 'imageinfo' in page ] return self._images @property def coordinates(self): ''' Tuple of Decimals in the form of (lat, lon) or None ''' if not getattr(self, '_coordinates', False): query_params = { 'prop': 'coordinates', 'colimit': 'max', 'titles': self.title, } request = _wiki_request(query_params) if 'query' in request: coordinates = request['query']['pages'][self.pageid]['coordinates'] self._coordinates = (Decimal(coordinates[0]['lat']), Decimal(coordinates[0]['lon'])) else: self._coordinates = None return self._coordinates @property def references(self): ''' List of URLs of external links on a page. May include external links within page that aren't technically cited anywhere. ''' if not getattr(self, '_references', False): def add_protocol(url): return url if url.startswith('http') else 'http:' + url self._references = [ add_protocol(link['*']) for link in self.__continued_query({ 'prop': 'extlinks', 'ellimit': 'max' }) ] return self._references @property def links(self): ''' List of titles of Wikipedia page links on a page. .. note:: Only includes articles from namespace 0, meaning no Category, User talk, or other meta-Wikipedia pages. ''' if not getattr(self, '_links', False): self._links = [ link['title'] for link in self.__continued_query({ 'prop': 'links', 'plnamespace': 0, 'pllimit': 'max' }) ] return self._links @property def categories(self): ''' List of categories of a page. ''' if not getattr(self, '_categories', False): self._categories = [re.sub(r'^Category:', '', x) for x in [link['title'] for link in self.__continued_query({ 'prop': 'categories', 'cllimit': 'max' }) ]] return self._categories @property def sections(self): ''' List of section titles from the table of contents on the page. ''' if not getattr(self, '_sections', False): query_params = { 'action': 'parse', 'prop': 'sections', } query_params.update(self.__title_query_param) request = _wiki_request(query_params) self._sections = [section['line'] for section in request['parse']['sections']] return self._sections def section(self, section_title): ''' Get the plain text content of a section from `self.sections`. Returns None if `section_title` isn't found, otherwise returns a whitespace stripped string. This is a convenience method that wraps self.content. .. warning:: Calling `section` on a section that has subheadings will NOT return the full text of all of the subsections. It only gets the text between `section_title` and the next subheading, which is often empty. ''' section = u"== {} ==".format(section_title) try: index = self.content.index(section) + len(section) except ValueError: return None try: next_index = self.content.index("==", index) except ValueError: next_index = len(self.content) return self.content[index:next_index].lstrip("=").strip()
goldsmith/Wikipedia
wikipedia/wikipedia.py
WikipediaPage.images
python
def images(self): ''' List of URLs of images on the page. ''' if not getattr(self, '_images', False): self._images = [ page['imageinfo'][0]['url'] for page in self.__continued_query({ 'generator': 'images', 'gimlimit': 'max', 'prop': 'imageinfo', 'iiprop': 'url', }) if 'imageinfo' in page ] return self._images
List of URLs of images on the page.
train
https://github.com/goldsmith/Wikipedia/blob/2065c568502b19b8634241b47fd96930d1bf948d/wikipedia/wikipedia.py#L536-L553
[ "def __continued_query(self, query_params):\n '''\n Based on https://www.mediawiki.org/wiki/API:Query#Continuing_queries\n '''\n query_params.update(self.__title_query_param)\n\n last_continue = {}\n prop = query_params.get('prop', None)\n\n while True:\n params = query_params.copy()\n params.update(last_continue)\n\n request = _wiki_request(params)\n\n if 'query' not in request:\n break\n\n pages = request['query']['pages']\n if 'generator' in query_params:\n for datum in pages.values(): # in python 3.3+: \"yield from pages.values()\"\n yield datum\n else:\n for datum in pages[self.pageid][prop]:\n yield datum\n\n if 'continue' not in request:\n break\n\n last_continue = request['continue']\n" ]
class WikipediaPage(object): ''' Contains data from a Wikipedia page. Uses property methods to filter data from the raw HTML. ''' def __init__(self, title=None, pageid=None, redirect=True, preload=False, original_title=''): if title is not None: self.title = title self.original_title = original_title or title elif pageid is not None: self.pageid = pageid else: raise ValueError("Either a title or a pageid must be specified") self.__load(redirect=redirect, preload=preload) if preload: for prop in ('content', 'summary', 'images', 'references', 'links', 'sections'): getattr(self, prop) def __repr__(self): return stdout_encode(u'<WikipediaPage \'{}\'>'.format(self.title)) def __eq__(self, other): try: return ( self.pageid == other.pageid and self.title == other.title and self.url == other.url ) except: return False def __load(self, redirect=True, preload=False): ''' Load basic information from Wikipedia. Confirm that page exists and is not a disambiguation/redirect. Does not need to be called manually, should be called automatically during __init__. ''' query_params = { 'prop': 'info|pageprops', 'inprop': 'url', 'ppprop': 'disambiguation', 'redirects': '', } if not getattr(self, 'pageid', None): query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) query = request['query'] pageid = list(query['pages'].keys())[0] page = query['pages'][pageid] # missing is present if the page is missing if 'missing' in page: if hasattr(self, 'title'): raise PageError(self.title) else: raise PageError(pageid=self.pageid) # same thing for redirect, except it shows up in query instead of page for # whatever silly reason elif 'redirects' in query: if redirect: redirects = query['redirects'][0] if 'normalized' in query: normalized = query['normalized'][0] assert normalized['from'] == self.title, ODD_ERROR_MESSAGE from_title = normalized['to'] else: from_title = self.title assert redirects['from'] == from_title, ODD_ERROR_MESSAGE # change the title and reload the whole object self.__init__(redirects['to'], redirect=redirect, preload=preload) else: raise RedirectError(getattr(self, 'title', page['title'])) # since we only asked for disambiguation in ppprop, # if a pageprop is returned, # then the page must be a disambiguation page elif 'pageprops' in page: query_params = { 'prop': 'revisions', 'rvprop': 'content', 'rvparse': '', 'rvlimit': 1 } if hasattr(self, 'pageid'): query_params['pageids'] = self.pageid else: query_params['titles'] = self.title request = _wiki_request(query_params) html = request['query']['pages'][pageid]['revisions'][0]['*'] lis = BeautifulSoup(html, 'html.parser').find_all('li') filtered_lis = [li for li in lis if not 'tocsection' in ''.join(li.get('class', []))] may_refer_to = [li.a.get_text() for li in filtered_lis if li.a] raise DisambiguationError(getattr(self, 'title', page['title']), may_refer_to) else: self.pageid = pageid self.title = page['title'] self.url = page['fullurl'] def __continued_query(self, query_params): ''' Based on https://www.mediawiki.org/wiki/API:Query#Continuing_queries ''' query_params.update(self.__title_query_param) last_continue = {} prop = query_params.get('prop', None) while True: params = query_params.copy() params.update(last_continue) request = _wiki_request(params) if 'query' not in request: break pages = request['query']['pages'] if 'generator' in query_params: for datum in pages.values(): # in python 3.3+: "yield from pages.values()" yield datum else: for datum in pages[self.pageid][prop]: yield datum if 'continue' not in request: break last_continue = request['continue'] @property def __title_query_param(self): if getattr(self, 'title', None) is not None: return {'titles': self.title} else: return {'pageids': self.pageid} def html(self): ''' Get full page HTML. .. warning:: This can get pretty slow on long pages. ''' if not getattr(self, '_html', False): query_params = { 'prop': 'revisions', 'rvprop': 'content', 'rvlimit': 1, 'rvparse': '', 'titles': self.title } request = _wiki_request(query_params) self._html = request['query']['pages'][self.pageid]['revisions'][0]['*'] return self._html @property def content(self): ''' Plain text content of the page, excluding images, tables, and other data. ''' if not getattr(self, '_content', False): query_params = { 'prop': 'extracts|revisions', 'explaintext': '', 'rvprop': 'ids' } if not getattr(self, 'title', None) is None: query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) self._content = request['query']['pages'][self.pageid]['extract'] self._revision_id = request['query']['pages'][self.pageid]['revisions'][0]['revid'] self._parent_id = request['query']['pages'][self.pageid]['revisions'][0]['parentid'] return self._content @property def revision_id(self): ''' Revision ID of the page. The revision ID is a number that uniquely identifies the current version of the page. It can be used to create the permalink or for other direct API calls. See `Help:Page history <http://en.wikipedia.org/wiki/Wikipedia:Revision>`_ for more information. ''' if not getattr(self, '_revid', False): # fetch the content (side effect is loading the revid) self.content return self._revision_id @property def parent_id(self): ''' Revision ID of the parent version of the current revision of this page. See ``revision_id`` for more information. ''' if not getattr(self, '_parentid', False): # fetch the content (side effect is loading the revid) self.content return self._parent_id @property def summary(self): ''' Plain text summary of the page. ''' if not getattr(self, '_summary', False): query_params = { 'prop': 'extracts', 'explaintext': '', 'exintro': '', } if not getattr(self, 'title', None) is None: query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) self._summary = request['query']['pages'][self.pageid]['extract'] return self._summary @property @property def coordinates(self): ''' Tuple of Decimals in the form of (lat, lon) or None ''' if not getattr(self, '_coordinates', False): query_params = { 'prop': 'coordinates', 'colimit': 'max', 'titles': self.title, } request = _wiki_request(query_params) if 'query' in request: coordinates = request['query']['pages'][self.pageid]['coordinates'] self._coordinates = (Decimal(coordinates[0]['lat']), Decimal(coordinates[0]['lon'])) else: self._coordinates = None return self._coordinates @property def references(self): ''' List of URLs of external links on a page. May include external links within page that aren't technically cited anywhere. ''' if not getattr(self, '_references', False): def add_protocol(url): return url if url.startswith('http') else 'http:' + url self._references = [ add_protocol(link['*']) for link in self.__continued_query({ 'prop': 'extlinks', 'ellimit': 'max' }) ] return self._references @property def links(self): ''' List of titles of Wikipedia page links on a page. .. note:: Only includes articles from namespace 0, meaning no Category, User talk, or other meta-Wikipedia pages. ''' if not getattr(self, '_links', False): self._links = [ link['title'] for link in self.__continued_query({ 'prop': 'links', 'plnamespace': 0, 'pllimit': 'max' }) ] return self._links @property def categories(self): ''' List of categories of a page. ''' if not getattr(self, '_categories', False): self._categories = [re.sub(r'^Category:', '', x) for x in [link['title'] for link in self.__continued_query({ 'prop': 'categories', 'cllimit': 'max' }) ]] return self._categories @property def sections(self): ''' List of section titles from the table of contents on the page. ''' if not getattr(self, '_sections', False): query_params = { 'action': 'parse', 'prop': 'sections', } query_params.update(self.__title_query_param) request = _wiki_request(query_params) self._sections = [section['line'] for section in request['parse']['sections']] return self._sections def section(self, section_title): ''' Get the plain text content of a section from `self.sections`. Returns None if `section_title` isn't found, otherwise returns a whitespace stripped string. This is a convenience method that wraps self.content. .. warning:: Calling `section` on a section that has subheadings will NOT return the full text of all of the subsections. It only gets the text between `section_title` and the next subheading, which is often empty. ''' section = u"== {} ==".format(section_title) try: index = self.content.index(section) + len(section) except ValueError: return None try: next_index = self.content.index("==", index) except ValueError: next_index = len(self.content) return self.content[index:next_index].lstrip("=").strip()
goldsmith/Wikipedia
wikipedia/wikipedia.py
WikipediaPage.coordinates
python
def coordinates(self): ''' Tuple of Decimals in the form of (lat, lon) or None ''' if not getattr(self, '_coordinates', False): query_params = { 'prop': 'coordinates', 'colimit': 'max', 'titles': self.title, } request = _wiki_request(query_params) if 'query' in request: coordinates = request['query']['pages'][self.pageid]['coordinates'] self._coordinates = (Decimal(coordinates[0]['lat']), Decimal(coordinates[0]['lon'])) else: self._coordinates = None return self._coordinates
Tuple of Decimals in the form of (lat, lon) or None
train
https://github.com/goldsmith/Wikipedia/blob/2065c568502b19b8634241b47fd96930d1bf948d/wikipedia/wikipedia.py#L556-L575
[ "def _wiki_request(params):\n '''\n Make a request to the Wikipedia API using the given search parameters.\n Returns a parsed dict of the JSON response.\n '''\n global RATE_LIMIT_LAST_CALL\n global USER_AGENT\n\n params['format'] = 'json'\n if not 'action' in params:\n params['action'] = 'query'\n\n headers = {\n 'User-Agent': USER_AGENT\n }\n\n if RATE_LIMIT and RATE_LIMIT_LAST_CALL and \\\n RATE_LIMIT_LAST_CALL + RATE_LIMIT_MIN_WAIT > datetime.now():\n\n # it hasn't been long enough since the last API call\n # so wait until we're in the clear to make the request\n\n wait_time = (RATE_LIMIT_LAST_CALL + RATE_LIMIT_MIN_WAIT) - datetime.now()\n time.sleep(int(wait_time.total_seconds()))\n\n r = requests.get(API_URL, params=params, headers=headers)\n\n if RATE_LIMIT:\n RATE_LIMIT_LAST_CALL = datetime.now()\n\n return r.json()\n" ]
class WikipediaPage(object): ''' Contains data from a Wikipedia page. Uses property methods to filter data from the raw HTML. ''' def __init__(self, title=None, pageid=None, redirect=True, preload=False, original_title=''): if title is not None: self.title = title self.original_title = original_title or title elif pageid is not None: self.pageid = pageid else: raise ValueError("Either a title or a pageid must be specified") self.__load(redirect=redirect, preload=preload) if preload: for prop in ('content', 'summary', 'images', 'references', 'links', 'sections'): getattr(self, prop) def __repr__(self): return stdout_encode(u'<WikipediaPage \'{}\'>'.format(self.title)) def __eq__(self, other): try: return ( self.pageid == other.pageid and self.title == other.title and self.url == other.url ) except: return False def __load(self, redirect=True, preload=False): ''' Load basic information from Wikipedia. Confirm that page exists and is not a disambiguation/redirect. Does not need to be called manually, should be called automatically during __init__. ''' query_params = { 'prop': 'info|pageprops', 'inprop': 'url', 'ppprop': 'disambiguation', 'redirects': '', } if not getattr(self, 'pageid', None): query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) query = request['query'] pageid = list(query['pages'].keys())[0] page = query['pages'][pageid] # missing is present if the page is missing if 'missing' in page: if hasattr(self, 'title'): raise PageError(self.title) else: raise PageError(pageid=self.pageid) # same thing for redirect, except it shows up in query instead of page for # whatever silly reason elif 'redirects' in query: if redirect: redirects = query['redirects'][0] if 'normalized' in query: normalized = query['normalized'][0] assert normalized['from'] == self.title, ODD_ERROR_MESSAGE from_title = normalized['to'] else: from_title = self.title assert redirects['from'] == from_title, ODD_ERROR_MESSAGE # change the title and reload the whole object self.__init__(redirects['to'], redirect=redirect, preload=preload) else: raise RedirectError(getattr(self, 'title', page['title'])) # since we only asked for disambiguation in ppprop, # if a pageprop is returned, # then the page must be a disambiguation page elif 'pageprops' in page: query_params = { 'prop': 'revisions', 'rvprop': 'content', 'rvparse': '', 'rvlimit': 1 } if hasattr(self, 'pageid'): query_params['pageids'] = self.pageid else: query_params['titles'] = self.title request = _wiki_request(query_params) html = request['query']['pages'][pageid]['revisions'][0]['*'] lis = BeautifulSoup(html, 'html.parser').find_all('li') filtered_lis = [li for li in lis if not 'tocsection' in ''.join(li.get('class', []))] may_refer_to = [li.a.get_text() for li in filtered_lis if li.a] raise DisambiguationError(getattr(self, 'title', page['title']), may_refer_to) else: self.pageid = pageid self.title = page['title'] self.url = page['fullurl'] def __continued_query(self, query_params): ''' Based on https://www.mediawiki.org/wiki/API:Query#Continuing_queries ''' query_params.update(self.__title_query_param) last_continue = {} prop = query_params.get('prop', None) while True: params = query_params.copy() params.update(last_continue) request = _wiki_request(params) if 'query' not in request: break pages = request['query']['pages'] if 'generator' in query_params: for datum in pages.values(): # in python 3.3+: "yield from pages.values()" yield datum else: for datum in pages[self.pageid][prop]: yield datum if 'continue' not in request: break last_continue = request['continue'] @property def __title_query_param(self): if getattr(self, 'title', None) is not None: return {'titles': self.title} else: return {'pageids': self.pageid} def html(self): ''' Get full page HTML. .. warning:: This can get pretty slow on long pages. ''' if not getattr(self, '_html', False): query_params = { 'prop': 'revisions', 'rvprop': 'content', 'rvlimit': 1, 'rvparse': '', 'titles': self.title } request = _wiki_request(query_params) self._html = request['query']['pages'][self.pageid]['revisions'][0]['*'] return self._html @property def content(self): ''' Plain text content of the page, excluding images, tables, and other data. ''' if not getattr(self, '_content', False): query_params = { 'prop': 'extracts|revisions', 'explaintext': '', 'rvprop': 'ids' } if not getattr(self, 'title', None) is None: query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) self._content = request['query']['pages'][self.pageid]['extract'] self._revision_id = request['query']['pages'][self.pageid]['revisions'][0]['revid'] self._parent_id = request['query']['pages'][self.pageid]['revisions'][0]['parentid'] return self._content @property def revision_id(self): ''' Revision ID of the page. The revision ID is a number that uniquely identifies the current version of the page. It can be used to create the permalink or for other direct API calls. See `Help:Page history <http://en.wikipedia.org/wiki/Wikipedia:Revision>`_ for more information. ''' if not getattr(self, '_revid', False): # fetch the content (side effect is loading the revid) self.content return self._revision_id @property def parent_id(self): ''' Revision ID of the parent version of the current revision of this page. See ``revision_id`` for more information. ''' if not getattr(self, '_parentid', False): # fetch the content (side effect is loading the revid) self.content return self._parent_id @property def summary(self): ''' Plain text summary of the page. ''' if not getattr(self, '_summary', False): query_params = { 'prop': 'extracts', 'explaintext': '', 'exintro': '', } if not getattr(self, 'title', None) is None: query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) self._summary = request['query']['pages'][self.pageid]['extract'] return self._summary @property def images(self): ''' List of URLs of images on the page. ''' if not getattr(self, '_images', False): self._images = [ page['imageinfo'][0]['url'] for page in self.__continued_query({ 'generator': 'images', 'gimlimit': 'max', 'prop': 'imageinfo', 'iiprop': 'url', }) if 'imageinfo' in page ] return self._images @property @property def references(self): ''' List of URLs of external links on a page. May include external links within page that aren't technically cited anywhere. ''' if not getattr(self, '_references', False): def add_protocol(url): return url if url.startswith('http') else 'http:' + url self._references = [ add_protocol(link['*']) for link in self.__continued_query({ 'prop': 'extlinks', 'ellimit': 'max' }) ] return self._references @property def links(self): ''' List of titles of Wikipedia page links on a page. .. note:: Only includes articles from namespace 0, meaning no Category, User talk, or other meta-Wikipedia pages. ''' if not getattr(self, '_links', False): self._links = [ link['title'] for link in self.__continued_query({ 'prop': 'links', 'plnamespace': 0, 'pllimit': 'max' }) ] return self._links @property def categories(self): ''' List of categories of a page. ''' if not getattr(self, '_categories', False): self._categories = [re.sub(r'^Category:', '', x) for x in [link['title'] for link in self.__continued_query({ 'prop': 'categories', 'cllimit': 'max' }) ]] return self._categories @property def sections(self): ''' List of section titles from the table of contents on the page. ''' if not getattr(self, '_sections', False): query_params = { 'action': 'parse', 'prop': 'sections', } query_params.update(self.__title_query_param) request = _wiki_request(query_params) self._sections = [section['line'] for section in request['parse']['sections']] return self._sections def section(self, section_title): ''' Get the plain text content of a section from `self.sections`. Returns None if `section_title` isn't found, otherwise returns a whitespace stripped string. This is a convenience method that wraps self.content. .. warning:: Calling `section` on a section that has subheadings will NOT return the full text of all of the subsections. It only gets the text between `section_title` and the next subheading, which is often empty. ''' section = u"== {} ==".format(section_title) try: index = self.content.index(section) + len(section) except ValueError: return None try: next_index = self.content.index("==", index) except ValueError: next_index = len(self.content) return self.content[index:next_index].lstrip("=").strip()
goldsmith/Wikipedia
wikipedia/wikipedia.py
WikipediaPage.references
python
def references(self): ''' List of URLs of external links on a page. May include external links within page that aren't technically cited anywhere. ''' if not getattr(self, '_references', False): def add_protocol(url): return url if url.startswith('http') else 'http:' + url self._references = [ add_protocol(link['*']) for link in self.__continued_query({ 'prop': 'extlinks', 'ellimit': 'max' }) ] return self._references
List of URLs of external links on a page. May include external links within page that aren't technically cited anywhere.
train
https://github.com/goldsmith/Wikipedia/blob/2065c568502b19b8634241b47fd96930d1bf948d/wikipedia/wikipedia.py#L578-L596
[ "def __continued_query(self, query_params):\n '''\n Based on https://www.mediawiki.org/wiki/API:Query#Continuing_queries\n '''\n query_params.update(self.__title_query_param)\n\n last_continue = {}\n prop = query_params.get('prop', None)\n\n while True:\n params = query_params.copy()\n params.update(last_continue)\n\n request = _wiki_request(params)\n\n if 'query' not in request:\n break\n\n pages = request['query']['pages']\n if 'generator' in query_params:\n for datum in pages.values(): # in python 3.3+: \"yield from pages.values()\"\n yield datum\n else:\n for datum in pages[self.pageid][prop]:\n yield datum\n\n if 'continue' not in request:\n break\n\n last_continue = request['continue']\n" ]
class WikipediaPage(object): ''' Contains data from a Wikipedia page. Uses property methods to filter data from the raw HTML. ''' def __init__(self, title=None, pageid=None, redirect=True, preload=False, original_title=''): if title is not None: self.title = title self.original_title = original_title or title elif pageid is not None: self.pageid = pageid else: raise ValueError("Either a title or a pageid must be specified") self.__load(redirect=redirect, preload=preload) if preload: for prop in ('content', 'summary', 'images', 'references', 'links', 'sections'): getattr(self, prop) def __repr__(self): return stdout_encode(u'<WikipediaPage \'{}\'>'.format(self.title)) def __eq__(self, other): try: return ( self.pageid == other.pageid and self.title == other.title and self.url == other.url ) except: return False def __load(self, redirect=True, preload=False): ''' Load basic information from Wikipedia. Confirm that page exists and is not a disambiguation/redirect. Does not need to be called manually, should be called automatically during __init__. ''' query_params = { 'prop': 'info|pageprops', 'inprop': 'url', 'ppprop': 'disambiguation', 'redirects': '', } if not getattr(self, 'pageid', None): query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) query = request['query'] pageid = list(query['pages'].keys())[0] page = query['pages'][pageid] # missing is present if the page is missing if 'missing' in page: if hasattr(self, 'title'): raise PageError(self.title) else: raise PageError(pageid=self.pageid) # same thing for redirect, except it shows up in query instead of page for # whatever silly reason elif 'redirects' in query: if redirect: redirects = query['redirects'][0] if 'normalized' in query: normalized = query['normalized'][0] assert normalized['from'] == self.title, ODD_ERROR_MESSAGE from_title = normalized['to'] else: from_title = self.title assert redirects['from'] == from_title, ODD_ERROR_MESSAGE # change the title and reload the whole object self.__init__(redirects['to'], redirect=redirect, preload=preload) else: raise RedirectError(getattr(self, 'title', page['title'])) # since we only asked for disambiguation in ppprop, # if a pageprop is returned, # then the page must be a disambiguation page elif 'pageprops' in page: query_params = { 'prop': 'revisions', 'rvprop': 'content', 'rvparse': '', 'rvlimit': 1 } if hasattr(self, 'pageid'): query_params['pageids'] = self.pageid else: query_params['titles'] = self.title request = _wiki_request(query_params) html = request['query']['pages'][pageid]['revisions'][0]['*'] lis = BeautifulSoup(html, 'html.parser').find_all('li') filtered_lis = [li for li in lis if not 'tocsection' in ''.join(li.get('class', []))] may_refer_to = [li.a.get_text() for li in filtered_lis if li.a] raise DisambiguationError(getattr(self, 'title', page['title']), may_refer_to) else: self.pageid = pageid self.title = page['title'] self.url = page['fullurl'] def __continued_query(self, query_params): ''' Based on https://www.mediawiki.org/wiki/API:Query#Continuing_queries ''' query_params.update(self.__title_query_param) last_continue = {} prop = query_params.get('prop', None) while True: params = query_params.copy() params.update(last_continue) request = _wiki_request(params) if 'query' not in request: break pages = request['query']['pages'] if 'generator' in query_params: for datum in pages.values(): # in python 3.3+: "yield from pages.values()" yield datum else: for datum in pages[self.pageid][prop]: yield datum if 'continue' not in request: break last_continue = request['continue'] @property def __title_query_param(self): if getattr(self, 'title', None) is not None: return {'titles': self.title} else: return {'pageids': self.pageid} def html(self): ''' Get full page HTML. .. warning:: This can get pretty slow on long pages. ''' if not getattr(self, '_html', False): query_params = { 'prop': 'revisions', 'rvprop': 'content', 'rvlimit': 1, 'rvparse': '', 'titles': self.title } request = _wiki_request(query_params) self._html = request['query']['pages'][self.pageid]['revisions'][0]['*'] return self._html @property def content(self): ''' Plain text content of the page, excluding images, tables, and other data. ''' if not getattr(self, '_content', False): query_params = { 'prop': 'extracts|revisions', 'explaintext': '', 'rvprop': 'ids' } if not getattr(self, 'title', None) is None: query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) self._content = request['query']['pages'][self.pageid]['extract'] self._revision_id = request['query']['pages'][self.pageid]['revisions'][0]['revid'] self._parent_id = request['query']['pages'][self.pageid]['revisions'][0]['parentid'] return self._content @property def revision_id(self): ''' Revision ID of the page. The revision ID is a number that uniquely identifies the current version of the page. It can be used to create the permalink or for other direct API calls. See `Help:Page history <http://en.wikipedia.org/wiki/Wikipedia:Revision>`_ for more information. ''' if not getattr(self, '_revid', False): # fetch the content (side effect is loading the revid) self.content return self._revision_id @property def parent_id(self): ''' Revision ID of the parent version of the current revision of this page. See ``revision_id`` for more information. ''' if not getattr(self, '_parentid', False): # fetch the content (side effect is loading the revid) self.content return self._parent_id @property def summary(self): ''' Plain text summary of the page. ''' if not getattr(self, '_summary', False): query_params = { 'prop': 'extracts', 'explaintext': '', 'exintro': '', } if not getattr(self, 'title', None) is None: query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) self._summary = request['query']['pages'][self.pageid]['extract'] return self._summary @property def images(self): ''' List of URLs of images on the page. ''' if not getattr(self, '_images', False): self._images = [ page['imageinfo'][0]['url'] for page in self.__continued_query({ 'generator': 'images', 'gimlimit': 'max', 'prop': 'imageinfo', 'iiprop': 'url', }) if 'imageinfo' in page ] return self._images @property def coordinates(self): ''' Tuple of Decimals in the form of (lat, lon) or None ''' if not getattr(self, '_coordinates', False): query_params = { 'prop': 'coordinates', 'colimit': 'max', 'titles': self.title, } request = _wiki_request(query_params) if 'query' in request: coordinates = request['query']['pages'][self.pageid]['coordinates'] self._coordinates = (Decimal(coordinates[0]['lat']), Decimal(coordinates[0]['lon'])) else: self._coordinates = None return self._coordinates @property @property def links(self): ''' List of titles of Wikipedia page links on a page. .. note:: Only includes articles from namespace 0, meaning no Category, User talk, or other meta-Wikipedia pages. ''' if not getattr(self, '_links', False): self._links = [ link['title'] for link in self.__continued_query({ 'prop': 'links', 'plnamespace': 0, 'pllimit': 'max' }) ] return self._links @property def categories(self): ''' List of categories of a page. ''' if not getattr(self, '_categories', False): self._categories = [re.sub(r'^Category:', '', x) for x in [link['title'] for link in self.__continued_query({ 'prop': 'categories', 'cllimit': 'max' }) ]] return self._categories @property def sections(self): ''' List of section titles from the table of contents on the page. ''' if not getattr(self, '_sections', False): query_params = { 'action': 'parse', 'prop': 'sections', } query_params.update(self.__title_query_param) request = _wiki_request(query_params) self._sections = [section['line'] for section in request['parse']['sections']] return self._sections def section(self, section_title): ''' Get the plain text content of a section from `self.sections`. Returns None if `section_title` isn't found, otherwise returns a whitespace stripped string. This is a convenience method that wraps self.content. .. warning:: Calling `section` on a section that has subheadings will NOT return the full text of all of the subsections. It only gets the text between `section_title` and the next subheading, which is often empty. ''' section = u"== {} ==".format(section_title) try: index = self.content.index(section) + len(section) except ValueError: return None try: next_index = self.content.index("==", index) except ValueError: next_index = len(self.content) return self.content[index:next_index].lstrip("=").strip()
goldsmith/Wikipedia
wikipedia/wikipedia.py
WikipediaPage.links
python
def links(self): ''' List of titles of Wikipedia page links on a page. .. note:: Only includes articles from namespace 0, meaning no Category, User talk, or other meta-Wikipedia pages. ''' if not getattr(self, '_links', False): self._links = [ link['title'] for link in self.__continued_query({ 'prop': 'links', 'plnamespace': 0, 'pllimit': 'max' }) ] return self._links
List of titles of Wikipedia page links on a page. .. note:: Only includes articles from namespace 0, meaning no Category, User talk, or other meta-Wikipedia pages.
train
https://github.com/goldsmith/Wikipedia/blob/2065c568502b19b8634241b47fd96930d1bf948d/wikipedia/wikipedia.py#L599-L616
[ "def __continued_query(self, query_params):\n '''\n Based on https://www.mediawiki.org/wiki/API:Query#Continuing_queries\n '''\n query_params.update(self.__title_query_param)\n\n last_continue = {}\n prop = query_params.get('prop', None)\n\n while True:\n params = query_params.copy()\n params.update(last_continue)\n\n request = _wiki_request(params)\n\n if 'query' not in request:\n break\n\n pages = request['query']['pages']\n if 'generator' in query_params:\n for datum in pages.values(): # in python 3.3+: \"yield from pages.values()\"\n yield datum\n else:\n for datum in pages[self.pageid][prop]:\n yield datum\n\n if 'continue' not in request:\n break\n\n last_continue = request['continue']\n" ]
class WikipediaPage(object): ''' Contains data from a Wikipedia page. Uses property methods to filter data from the raw HTML. ''' def __init__(self, title=None, pageid=None, redirect=True, preload=False, original_title=''): if title is not None: self.title = title self.original_title = original_title or title elif pageid is not None: self.pageid = pageid else: raise ValueError("Either a title or a pageid must be specified") self.__load(redirect=redirect, preload=preload) if preload: for prop in ('content', 'summary', 'images', 'references', 'links', 'sections'): getattr(self, prop) def __repr__(self): return stdout_encode(u'<WikipediaPage \'{}\'>'.format(self.title)) def __eq__(self, other): try: return ( self.pageid == other.pageid and self.title == other.title and self.url == other.url ) except: return False def __load(self, redirect=True, preload=False): ''' Load basic information from Wikipedia. Confirm that page exists and is not a disambiguation/redirect. Does not need to be called manually, should be called automatically during __init__. ''' query_params = { 'prop': 'info|pageprops', 'inprop': 'url', 'ppprop': 'disambiguation', 'redirects': '', } if not getattr(self, 'pageid', None): query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) query = request['query'] pageid = list(query['pages'].keys())[0] page = query['pages'][pageid] # missing is present if the page is missing if 'missing' in page: if hasattr(self, 'title'): raise PageError(self.title) else: raise PageError(pageid=self.pageid) # same thing for redirect, except it shows up in query instead of page for # whatever silly reason elif 'redirects' in query: if redirect: redirects = query['redirects'][0] if 'normalized' in query: normalized = query['normalized'][0] assert normalized['from'] == self.title, ODD_ERROR_MESSAGE from_title = normalized['to'] else: from_title = self.title assert redirects['from'] == from_title, ODD_ERROR_MESSAGE # change the title and reload the whole object self.__init__(redirects['to'], redirect=redirect, preload=preload) else: raise RedirectError(getattr(self, 'title', page['title'])) # since we only asked for disambiguation in ppprop, # if a pageprop is returned, # then the page must be a disambiguation page elif 'pageprops' in page: query_params = { 'prop': 'revisions', 'rvprop': 'content', 'rvparse': '', 'rvlimit': 1 } if hasattr(self, 'pageid'): query_params['pageids'] = self.pageid else: query_params['titles'] = self.title request = _wiki_request(query_params) html = request['query']['pages'][pageid]['revisions'][0]['*'] lis = BeautifulSoup(html, 'html.parser').find_all('li') filtered_lis = [li for li in lis if not 'tocsection' in ''.join(li.get('class', []))] may_refer_to = [li.a.get_text() for li in filtered_lis if li.a] raise DisambiguationError(getattr(self, 'title', page['title']), may_refer_to) else: self.pageid = pageid self.title = page['title'] self.url = page['fullurl'] def __continued_query(self, query_params): ''' Based on https://www.mediawiki.org/wiki/API:Query#Continuing_queries ''' query_params.update(self.__title_query_param) last_continue = {} prop = query_params.get('prop', None) while True: params = query_params.copy() params.update(last_continue) request = _wiki_request(params) if 'query' not in request: break pages = request['query']['pages'] if 'generator' in query_params: for datum in pages.values(): # in python 3.3+: "yield from pages.values()" yield datum else: for datum in pages[self.pageid][prop]: yield datum if 'continue' not in request: break last_continue = request['continue'] @property def __title_query_param(self): if getattr(self, 'title', None) is not None: return {'titles': self.title} else: return {'pageids': self.pageid} def html(self): ''' Get full page HTML. .. warning:: This can get pretty slow on long pages. ''' if not getattr(self, '_html', False): query_params = { 'prop': 'revisions', 'rvprop': 'content', 'rvlimit': 1, 'rvparse': '', 'titles': self.title } request = _wiki_request(query_params) self._html = request['query']['pages'][self.pageid]['revisions'][0]['*'] return self._html @property def content(self): ''' Plain text content of the page, excluding images, tables, and other data. ''' if not getattr(self, '_content', False): query_params = { 'prop': 'extracts|revisions', 'explaintext': '', 'rvprop': 'ids' } if not getattr(self, 'title', None) is None: query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) self._content = request['query']['pages'][self.pageid]['extract'] self._revision_id = request['query']['pages'][self.pageid]['revisions'][0]['revid'] self._parent_id = request['query']['pages'][self.pageid]['revisions'][0]['parentid'] return self._content @property def revision_id(self): ''' Revision ID of the page. The revision ID is a number that uniquely identifies the current version of the page. It can be used to create the permalink or for other direct API calls. See `Help:Page history <http://en.wikipedia.org/wiki/Wikipedia:Revision>`_ for more information. ''' if not getattr(self, '_revid', False): # fetch the content (side effect is loading the revid) self.content return self._revision_id @property def parent_id(self): ''' Revision ID of the parent version of the current revision of this page. See ``revision_id`` for more information. ''' if not getattr(self, '_parentid', False): # fetch the content (side effect is loading the revid) self.content return self._parent_id @property def summary(self): ''' Plain text summary of the page. ''' if not getattr(self, '_summary', False): query_params = { 'prop': 'extracts', 'explaintext': '', 'exintro': '', } if not getattr(self, 'title', None) is None: query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) self._summary = request['query']['pages'][self.pageid]['extract'] return self._summary @property def images(self): ''' List of URLs of images on the page. ''' if not getattr(self, '_images', False): self._images = [ page['imageinfo'][0]['url'] for page in self.__continued_query({ 'generator': 'images', 'gimlimit': 'max', 'prop': 'imageinfo', 'iiprop': 'url', }) if 'imageinfo' in page ] return self._images @property def coordinates(self): ''' Tuple of Decimals in the form of (lat, lon) or None ''' if not getattr(self, '_coordinates', False): query_params = { 'prop': 'coordinates', 'colimit': 'max', 'titles': self.title, } request = _wiki_request(query_params) if 'query' in request: coordinates = request['query']['pages'][self.pageid]['coordinates'] self._coordinates = (Decimal(coordinates[0]['lat']), Decimal(coordinates[0]['lon'])) else: self._coordinates = None return self._coordinates @property def references(self): ''' List of URLs of external links on a page. May include external links within page that aren't technically cited anywhere. ''' if not getattr(self, '_references', False): def add_protocol(url): return url if url.startswith('http') else 'http:' + url self._references = [ add_protocol(link['*']) for link in self.__continued_query({ 'prop': 'extlinks', 'ellimit': 'max' }) ] return self._references @property @property def categories(self): ''' List of categories of a page. ''' if not getattr(self, '_categories', False): self._categories = [re.sub(r'^Category:', '', x) for x in [link['title'] for link in self.__continued_query({ 'prop': 'categories', 'cllimit': 'max' }) ]] return self._categories @property def sections(self): ''' List of section titles from the table of contents on the page. ''' if not getattr(self, '_sections', False): query_params = { 'action': 'parse', 'prop': 'sections', } query_params.update(self.__title_query_param) request = _wiki_request(query_params) self._sections = [section['line'] for section in request['parse']['sections']] return self._sections def section(self, section_title): ''' Get the plain text content of a section from `self.sections`. Returns None if `section_title` isn't found, otherwise returns a whitespace stripped string. This is a convenience method that wraps self.content. .. warning:: Calling `section` on a section that has subheadings will NOT return the full text of all of the subsections. It only gets the text between `section_title` and the next subheading, which is often empty. ''' section = u"== {} ==".format(section_title) try: index = self.content.index(section) + len(section) except ValueError: return None try: next_index = self.content.index("==", index) except ValueError: next_index = len(self.content) return self.content[index:next_index].lstrip("=").strip()
goldsmith/Wikipedia
wikipedia/wikipedia.py
WikipediaPage.categories
python
def categories(self): ''' List of categories of a page. ''' if not getattr(self, '_categories', False): self._categories = [re.sub(r'^Category:', '', x) for x in [link['title'] for link in self.__continued_query({ 'prop': 'categories', 'cllimit': 'max' }) ]] return self._categories
List of categories of a page.
train
https://github.com/goldsmith/Wikipedia/blob/2065c568502b19b8634241b47fd96930d1bf948d/wikipedia/wikipedia.py#L619-L633
[ "def __continued_query(self, query_params):\n '''\n Based on https://www.mediawiki.org/wiki/API:Query#Continuing_queries\n '''\n query_params.update(self.__title_query_param)\n\n last_continue = {}\n prop = query_params.get('prop', None)\n\n while True:\n params = query_params.copy()\n params.update(last_continue)\n\n request = _wiki_request(params)\n\n if 'query' not in request:\n break\n\n pages = request['query']['pages']\n if 'generator' in query_params:\n for datum in pages.values(): # in python 3.3+: \"yield from pages.values()\"\n yield datum\n else:\n for datum in pages[self.pageid][prop]:\n yield datum\n\n if 'continue' not in request:\n break\n\n last_continue = request['continue']\n" ]
class WikipediaPage(object): ''' Contains data from a Wikipedia page. Uses property methods to filter data from the raw HTML. ''' def __init__(self, title=None, pageid=None, redirect=True, preload=False, original_title=''): if title is not None: self.title = title self.original_title = original_title or title elif pageid is not None: self.pageid = pageid else: raise ValueError("Either a title or a pageid must be specified") self.__load(redirect=redirect, preload=preload) if preload: for prop in ('content', 'summary', 'images', 'references', 'links', 'sections'): getattr(self, prop) def __repr__(self): return stdout_encode(u'<WikipediaPage \'{}\'>'.format(self.title)) def __eq__(self, other): try: return ( self.pageid == other.pageid and self.title == other.title and self.url == other.url ) except: return False def __load(self, redirect=True, preload=False): ''' Load basic information from Wikipedia. Confirm that page exists and is not a disambiguation/redirect. Does not need to be called manually, should be called automatically during __init__. ''' query_params = { 'prop': 'info|pageprops', 'inprop': 'url', 'ppprop': 'disambiguation', 'redirects': '', } if not getattr(self, 'pageid', None): query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) query = request['query'] pageid = list(query['pages'].keys())[0] page = query['pages'][pageid] # missing is present if the page is missing if 'missing' in page: if hasattr(self, 'title'): raise PageError(self.title) else: raise PageError(pageid=self.pageid) # same thing for redirect, except it shows up in query instead of page for # whatever silly reason elif 'redirects' in query: if redirect: redirects = query['redirects'][0] if 'normalized' in query: normalized = query['normalized'][0] assert normalized['from'] == self.title, ODD_ERROR_MESSAGE from_title = normalized['to'] else: from_title = self.title assert redirects['from'] == from_title, ODD_ERROR_MESSAGE # change the title and reload the whole object self.__init__(redirects['to'], redirect=redirect, preload=preload) else: raise RedirectError(getattr(self, 'title', page['title'])) # since we only asked for disambiguation in ppprop, # if a pageprop is returned, # then the page must be a disambiguation page elif 'pageprops' in page: query_params = { 'prop': 'revisions', 'rvprop': 'content', 'rvparse': '', 'rvlimit': 1 } if hasattr(self, 'pageid'): query_params['pageids'] = self.pageid else: query_params['titles'] = self.title request = _wiki_request(query_params) html = request['query']['pages'][pageid]['revisions'][0]['*'] lis = BeautifulSoup(html, 'html.parser').find_all('li') filtered_lis = [li for li in lis if not 'tocsection' in ''.join(li.get('class', []))] may_refer_to = [li.a.get_text() for li in filtered_lis if li.a] raise DisambiguationError(getattr(self, 'title', page['title']), may_refer_to) else: self.pageid = pageid self.title = page['title'] self.url = page['fullurl'] def __continued_query(self, query_params): ''' Based on https://www.mediawiki.org/wiki/API:Query#Continuing_queries ''' query_params.update(self.__title_query_param) last_continue = {} prop = query_params.get('prop', None) while True: params = query_params.copy() params.update(last_continue) request = _wiki_request(params) if 'query' not in request: break pages = request['query']['pages'] if 'generator' in query_params: for datum in pages.values(): # in python 3.3+: "yield from pages.values()" yield datum else: for datum in pages[self.pageid][prop]: yield datum if 'continue' not in request: break last_continue = request['continue'] @property def __title_query_param(self): if getattr(self, 'title', None) is not None: return {'titles': self.title} else: return {'pageids': self.pageid} def html(self): ''' Get full page HTML. .. warning:: This can get pretty slow on long pages. ''' if not getattr(self, '_html', False): query_params = { 'prop': 'revisions', 'rvprop': 'content', 'rvlimit': 1, 'rvparse': '', 'titles': self.title } request = _wiki_request(query_params) self._html = request['query']['pages'][self.pageid]['revisions'][0]['*'] return self._html @property def content(self): ''' Plain text content of the page, excluding images, tables, and other data. ''' if not getattr(self, '_content', False): query_params = { 'prop': 'extracts|revisions', 'explaintext': '', 'rvprop': 'ids' } if not getattr(self, 'title', None) is None: query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) self._content = request['query']['pages'][self.pageid]['extract'] self._revision_id = request['query']['pages'][self.pageid]['revisions'][0]['revid'] self._parent_id = request['query']['pages'][self.pageid]['revisions'][0]['parentid'] return self._content @property def revision_id(self): ''' Revision ID of the page. The revision ID is a number that uniquely identifies the current version of the page. It can be used to create the permalink or for other direct API calls. See `Help:Page history <http://en.wikipedia.org/wiki/Wikipedia:Revision>`_ for more information. ''' if not getattr(self, '_revid', False): # fetch the content (side effect is loading the revid) self.content return self._revision_id @property def parent_id(self): ''' Revision ID of the parent version of the current revision of this page. See ``revision_id`` for more information. ''' if not getattr(self, '_parentid', False): # fetch the content (side effect is loading the revid) self.content return self._parent_id @property def summary(self): ''' Plain text summary of the page. ''' if not getattr(self, '_summary', False): query_params = { 'prop': 'extracts', 'explaintext': '', 'exintro': '', } if not getattr(self, 'title', None) is None: query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) self._summary = request['query']['pages'][self.pageid]['extract'] return self._summary @property def images(self): ''' List of URLs of images on the page. ''' if not getattr(self, '_images', False): self._images = [ page['imageinfo'][0]['url'] for page in self.__continued_query({ 'generator': 'images', 'gimlimit': 'max', 'prop': 'imageinfo', 'iiprop': 'url', }) if 'imageinfo' in page ] return self._images @property def coordinates(self): ''' Tuple of Decimals in the form of (lat, lon) or None ''' if not getattr(self, '_coordinates', False): query_params = { 'prop': 'coordinates', 'colimit': 'max', 'titles': self.title, } request = _wiki_request(query_params) if 'query' in request: coordinates = request['query']['pages'][self.pageid]['coordinates'] self._coordinates = (Decimal(coordinates[0]['lat']), Decimal(coordinates[0]['lon'])) else: self._coordinates = None return self._coordinates @property def references(self): ''' List of URLs of external links on a page. May include external links within page that aren't technically cited anywhere. ''' if not getattr(self, '_references', False): def add_protocol(url): return url if url.startswith('http') else 'http:' + url self._references = [ add_protocol(link['*']) for link in self.__continued_query({ 'prop': 'extlinks', 'ellimit': 'max' }) ] return self._references @property def links(self): ''' List of titles of Wikipedia page links on a page. .. note:: Only includes articles from namespace 0, meaning no Category, User talk, or other meta-Wikipedia pages. ''' if not getattr(self, '_links', False): self._links = [ link['title'] for link in self.__continued_query({ 'prop': 'links', 'plnamespace': 0, 'pllimit': 'max' }) ] return self._links @property @property def sections(self): ''' List of section titles from the table of contents on the page. ''' if not getattr(self, '_sections', False): query_params = { 'action': 'parse', 'prop': 'sections', } query_params.update(self.__title_query_param) request = _wiki_request(query_params) self._sections = [section['line'] for section in request['parse']['sections']] return self._sections def section(self, section_title): ''' Get the plain text content of a section from `self.sections`. Returns None if `section_title` isn't found, otherwise returns a whitespace stripped string. This is a convenience method that wraps self.content. .. warning:: Calling `section` on a section that has subheadings will NOT return the full text of all of the subsections. It only gets the text between `section_title` and the next subheading, which is often empty. ''' section = u"== {} ==".format(section_title) try: index = self.content.index(section) + len(section) except ValueError: return None try: next_index = self.content.index("==", index) except ValueError: next_index = len(self.content) return self.content[index:next_index].lstrip("=").strip()
goldsmith/Wikipedia
wikipedia/wikipedia.py
WikipediaPage.sections
python
def sections(self): ''' List of section titles from the table of contents on the page. ''' if not getattr(self, '_sections', False): query_params = { 'action': 'parse', 'prop': 'sections', } query_params.update(self.__title_query_param) request = _wiki_request(query_params) self._sections = [section['line'] for section in request['parse']['sections']] return self._sections
List of section titles from the table of contents on the page.
train
https://github.com/goldsmith/Wikipedia/blob/2065c568502b19b8634241b47fd96930d1bf948d/wikipedia/wikipedia.py#L636-L651
[ "def _wiki_request(params):\n '''\n Make a request to the Wikipedia API using the given search parameters.\n Returns a parsed dict of the JSON response.\n '''\n global RATE_LIMIT_LAST_CALL\n global USER_AGENT\n\n params['format'] = 'json'\n if not 'action' in params:\n params['action'] = 'query'\n\n headers = {\n 'User-Agent': USER_AGENT\n }\n\n if RATE_LIMIT and RATE_LIMIT_LAST_CALL and \\\n RATE_LIMIT_LAST_CALL + RATE_LIMIT_MIN_WAIT > datetime.now():\n\n # it hasn't been long enough since the last API call\n # so wait until we're in the clear to make the request\n\n wait_time = (RATE_LIMIT_LAST_CALL + RATE_LIMIT_MIN_WAIT) - datetime.now()\n time.sleep(int(wait_time.total_seconds()))\n\n r = requests.get(API_URL, params=params, headers=headers)\n\n if RATE_LIMIT:\n RATE_LIMIT_LAST_CALL = datetime.now()\n\n return r.json()\n" ]
class WikipediaPage(object): ''' Contains data from a Wikipedia page. Uses property methods to filter data from the raw HTML. ''' def __init__(self, title=None, pageid=None, redirect=True, preload=False, original_title=''): if title is not None: self.title = title self.original_title = original_title or title elif pageid is not None: self.pageid = pageid else: raise ValueError("Either a title or a pageid must be specified") self.__load(redirect=redirect, preload=preload) if preload: for prop in ('content', 'summary', 'images', 'references', 'links', 'sections'): getattr(self, prop) def __repr__(self): return stdout_encode(u'<WikipediaPage \'{}\'>'.format(self.title)) def __eq__(self, other): try: return ( self.pageid == other.pageid and self.title == other.title and self.url == other.url ) except: return False def __load(self, redirect=True, preload=False): ''' Load basic information from Wikipedia. Confirm that page exists and is not a disambiguation/redirect. Does not need to be called manually, should be called automatically during __init__. ''' query_params = { 'prop': 'info|pageprops', 'inprop': 'url', 'ppprop': 'disambiguation', 'redirects': '', } if not getattr(self, 'pageid', None): query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) query = request['query'] pageid = list(query['pages'].keys())[0] page = query['pages'][pageid] # missing is present if the page is missing if 'missing' in page: if hasattr(self, 'title'): raise PageError(self.title) else: raise PageError(pageid=self.pageid) # same thing for redirect, except it shows up in query instead of page for # whatever silly reason elif 'redirects' in query: if redirect: redirects = query['redirects'][0] if 'normalized' in query: normalized = query['normalized'][0] assert normalized['from'] == self.title, ODD_ERROR_MESSAGE from_title = normalized['to'] else: from_title = self.title assert redirects['from'] == from_title, ODD_ERROR_MESSAGE # change the title and reload the whole object self.__init__(redirects['to'], redirect=redirect, preload=preload) else: raise RedirectError(getattr(self, 'title', page['title'])) # since we only asked for disambiguation in ppprop, # if a pageprop is returned, # then the page must be a disambiguation page elif 'pageprops' in page: query_params = { 'prop': 'revisions', 'rvprop': 'content', 'rvparse': '', 'rvlimit': 1 } if hasattr(self, 'pageid'): query_params['pageids'] = self.pageid else: query_params['titles'] = self.title request = _wiki_request(query_params) html = request['query']['pages'][pageid]['revisions'][0]['*'] lis = BeautifulSoup(html, 'html.parser').find_all('li') filtered_lis = [li for li in lis if not 'tocsection' in ''.join(li.get('class', []))] may_refer_to = [li.a.get_text() for li in filtered_lis if li.a] raise DisambiguationError(getattr(self, 'title', page['title']), may_refer_to) else: self.pageid = pageid self.title = page['title'] self.url = page['fullurl'] def __continued_query(self, query_params): ''' Based on https://www.mediawiki.org/wiki/API:Query#Continuing_queries ''' query_params.update(self.__title_query_param) last_continue = {} prop = query_params.get('prop', None) while True: params = query_params.copy() params.update(last_continue) request = _wiki_request(params) if 'query' not in request: break pages = request['query']['pages'] if 'generator' in query_params: for datum in pages.values(): # in python 3.3+: "yield from pages.values()" yield datum else: for datum in pages[self.pageid][prop]: yield datum if 'continue' not in request: break last_continue = request['continue'] @property def __title_query_param(self): if getattr(self, 'title', None) is not None: return {'titles': self.title} else: return {'pageids': self.pageid} def html(self): ''' Get full page HTML. .. warning:: This can get pretty slow on long pages. ''' if not getattr(self, '_html', False): query_params = { 'prop': 'revisions', 'rvprop': 'content', 'rvlimit': 1, 'rvparse': '', 'titles': self.title } request = _wiki_request(query_params) self._html = request['query']['pages'][self.pageid]['revisions'][0]['*'] return self._html @property def content(self): ''' Plain text content of the page, excluding images, tables, and other data. ''' if not getattr(self, '_content', False): query_params = { 'prop': 'extracts|revisions', 'explaintext': '', 'rvprop': 'ids' } if not getattr(self, 'title', None) is None: query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) self._content = request['query']['pages'][self.pageid]['extract'] self._revision_id = request['query']['pages'][self.pageid]['revisions'][0]['revid'] self._parent_id = request['query']['pages'][self.pageid]['revisions'][0]['parentid'] return self._content @property def revision_id(self): ''' Revision ID of the page. The revision ID is a number that uniquely identifies the current version of the page. It can be used to create the permalink or for other direct API calls. See `Help:Page history <http://en.wikipedia.org/wiki/Wikipedia:Revision>`_ for more information. ''' if not getattr(self, '_revid', False): # fetch the content (side effect is loading the revid) self.content return self._revision_id @property def parent_id(self): ''' Revision ID of the parent version of the current revision of this page. See ``revision_id`` for more information. ''' if not getattr(self, '_parentid', False): # fetch the content (side effect is loading the revid) self.content return self._parent_id @property def summary(self): ''' Plain text summary of the page. ''' if not getattr(self, '_summary', False): query_params = { 'prop': 'extracts', 'explaintext': '', 'exintro': '', } if not getattr(self, 'title', None) is None: query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) self._summary = request['query']['pages'][self.pageid]['extract'] return self._summary @property def images(self): ''' List of URLs of images on the page. ''' if not getattr(self, '_images', False): self._images = [ page['imageinfo'][0]['url'] for page in self.__continued_query({ 'generator': 'images', 'gimlimit': 'max', 'prop': 'imageinfo', 'iiprop': 'url', }) if 'imageinfo' in page ] return self._images @property def coordinates(self): ''' Tuple of Decimals in the form of (lat, lon) or None ''' if not getattr(self, '_coordinates', False): query_params = { 'prop': 'coordinates', 'colimit': 'max', 'titles': self.title, } request = _wiki_request(query_params) if 'query' in request: coordinates = request['query']['pages'][self.pageid]['coordinates'] self._coordinates = (Decimal(coordinates[0]['lat']), Decimal(coordinates[0]['lon'])) else: self._coordinates = None return self._coordinates @property def references(self): ''' List of URLs of external links on a page. May include external links within page that aren't technically cited anywhere. ''' if not getattr(self, '_references', False): def add_protocol(url): return url if url.startswith('http') else 'http:' + url self._references = [ add_protocol(link['*']) for link in self.__continued_query({ 'prop': 'extlinks', 'ellimit': 'max' }) ] return self._references @property def links(self): ''' List of titles of Wikipedia page links on a page. .. note:: Only includes articles from namespace 0, meaning no Category, User talk, or other meta-Wikipedia pages. ''' if not getattr(self, '_links', False): self._links = [ link['title'] for link in self.__continued_query({ 'prop': 'links', 'plnamespace': 0, 'pllimit': 'max' }) ] return self._links @property def categories(self): ''' List of categories of a page. ''' if not getattr(self, '_categories', False): self._categories = [re.sub(r'^Category:', '', x) for x in [link['title'] for link in self.__continued_query({ 'prop': 'categories', 'cllimit': 'max' }) ]] return self._categories @property def section(self, section_title): ''' Get the plain text content of a section from `self.sections`. Returns None if `section_title` isn't found, otherwise returns a whitespace stripped string. This is a convenience method that wraps self.content. .. warning:: Calling `section` on a section that has subheadings will NOT return the full text of all of the subsections. It only gets the text between `section_title` and the next subheading, which is often empty. ''' section = u"== {} ==".format(section_title) try: index = self.content.index(section) + len(section) except ValueError: return None try: next_index = self.content.index("==", index) except ValueError: next_index = len(self.content) return self.content[index:next_index].lstrip("=").strip()
goldsmith/Wikipedia
wikipedia/wikipedia.py
WikipediaPage.section
python
def section(self, section_title): ''' Get the plain text content of a section from `self.sections`. Returns None if `section_title` isn't found, otherwise returns a whitespace stripped string. This is a convenience method that wraps self.content. .. warning:: Calling `section` on a section that has subheadings will NOT return the full text of all of the subsections. It only gets the text between `section_title` and the next subheading, which is often empty. ''' section = u"== {} ==".format(section_title) try: index = self.content.index(section) + len(section) except ValueError: return None try: next_index = self.content.index("==", index) except ValueError: next_index = len(self.content) return self.content[index:next_index].lstrip("=").strip()
Get the plain text content of a section from `self.sections`. Returns None if `section_title` isn't found, otherwise returns a whitespace stripped string. This is a convenience method that wraps self.content. .. warning:: Calling `section` on a section that has subheadings will NOT return the full text of all of the subsections. It only gets the text between `section_title` and the next subheading, which is often empty.
train
https://github.com/goldsmith/Wikipedia/blob/2065c568502b19b8634241b47fd96930d1bf948d/wikipedia/wikipedia.py#L653-L676
null
class WikipediaPage(object): ''' Contains data from a Wikipedia page. Uses property methods to filter data from the raw HTML. ''' def __init__(self, title=None, pageid=None, redirect=True, preload=False, original_title=''): if title is not None: self.title = title self.original_title = original_title or title elif pageid is not None: self.pageid = pageid else: raise ValueError("Either a title or a pageid must be specified") self.__load(redirect=redirect, preload=preload) if preload: for prop in ('content', 'summary', 'images', 'references', 'links', 'sections'): getattr(self, prop) def __repr__(self): return stdout_encode(u'<WikipediaPage \'{}\'>'.format(self.title)) def __eq__(self, other): try: return ( self.pageid == other.pageid and self.title == other.title and self.url == other.url ) except: return False def __load(self, redirect=True, preload=False): ''' Load basic information from Wikipedia. Confirm that page exists and is not a disambiguation/redirect. Does not need to be called manually, should be called automatically during __init__. ''' query_params = { 'prop': 'info|pageprops', 'inprop': 'url', 'ppprop': 'disambiguation', 'redirects': '', } if not getattr(self, 'pageid', None): query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) query = request['query'] pageid = list(query['pages'].keys())[0] page = query['pages'][pageid] # missing is present if the page is missing if 'missing' in page: if hasattr(self, 'title'): raise PageError(self.title) else: raise PageError(pageid=self.pageid) # same thing for redirect, except it shows up in query instead of page for # whatever silly reason elif 'redirects' in query: if redirect: redirects = query['redirects'][0] if 'normalized' in query: normalized = query['normalized'][0] assert normalized['from'] == self.title, ODD_ERROR_MESSAGE from_title = normalized['to'] else: from_title = self.title assert redirects['from'] == from_title, ODD_ERROR_MESSAGE # change the title and reload the whole object self.__init__(redirects['to'], redirect=redirect, preload=preload) else: raise RedirectError(getattr(self, 'title', page['title'])) # since we only asked for disambiguation in ppprop, # if a pageprop is returned, # then the page must be a disambiguation page elif 'pageprops' in page: query_params = { 'prop': 'revisions', 'rvprop': 'content', 'rvparse': '', 'rvlimit': 1 } if hasattr(self, 'pageid'): query_params['pageids'] = self.pageid else: query_params['titles'] = self.title request = _wiki_request(query_params) html = request['query']['pages'][pageid]['revisions'][0]['*'] lis = BeautifulSoup(html, 'html.parser').find_all('li') filtered_lis = [li for li in lis if not 'tocsection' in ''.join(li.get('class', []))] may_refer_to = [li.a.get_text() for li in filtered_lis if li.a] raise DisambiguationError(getattr(self, 'title', page['title']), may_refer_to) else: self.pageid = pageid self.title = page['title'] self.url = page['fullurl'] def __continued_query(self, query_params): ''' Based on https://www.mediawiki.org/wiki/API:Query#Continuing_queries ''' query_params.update(self.__title_query_param) last_continue = {} prop = query_params.get('prop', None) while True: params = query_params.copy() params.update(last_continue) request = _wiki_request(params) if 'query' not in request: break pages = request['query']['pages'] if 'generator' in query_params: for datum in pages.values(): # in python 3.3+: "yield from pages.values()" yield datum else: for datum in pages[self.pageid][prop]: yield datum if 'continue' not in request: break last_continue = request['continue'] @property def __title_query_param(self): if getattr(self, 'title', None) is not None: return {'titles': self.title} else: return {'pageids': self.pageid} def html(self): ''' Get full page HTML. .. warning:: This can get pretty slow on long pages. ''' if not getattr(self, '_html', False): query_params = { 'prop': 'revisions', 'rvprop': 'content', 'rvlimit': 1, 'rvparse': '', 'titles': self.title } request = _wiki_request(query_params) self._html = request['query']['pages'][self.pageid]['revisions'][0]['*'] return self._html @property def content(self): ''' Plain text content of the page, excluding images, tables, and other data. ''' if not getattr(self, '_content', False): query_params = { 'prop': 'extracts|revisions', 'explaintext': '', 'rvprop': 'ids' } if not getattr(self, 'title', None) is None: query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) self._content = request['query']['pages'][self.pageid]['extract'] self._revision_id = request['query']['pages'][self.pageid]['revisions'][0]['revid'] self._parent_id = request['query']['pages'][self.pageid]['revisions'][0]['parentid'] return self._content @property def revision_id(self): ''' Revision ID of the page. The revision ID is a number that uniquely identifies the current version of the page. It can be used to create the permalink or for other direct API calls. See `Help:Page history <http://en.wikipedia.org/wiki/Wikipedia:Revision>`_ for more information. ''' if not getattr(self, '_revid', False): # fetch the content (side effect is loading the revid) self.content return self._revision_id @property def parent_id(self): ''' Revision ID of the parent version of the current revision of this page. See ``revision_id`` for more information. ''' if not getattr(self, '_parentid', False): # fetch the content (side effect is loading the revid) self.content return self._parent_id @property def summary(self): ''' Plain text summary of the page. ''' if not getattr(self, '_summary', False): query_params = { 'prop': 'extracts', 'explaintext': '', 'exintro': '', } if not getattr(self, 'title', None) is None: query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = _wiki_request(query_params) self._summary = request['query']['pages'][self.pageid]['extract'] return self._summary @property def images(self): ''' List of URLs of images on the page. ''' if not getattr(self, '_images', False): self._images = [ page['imageinfo'][0]['url'] for page in self.__continued_query({ 'generator': 'images', 'gimlimit': 'max', 'prop': 'imageinfo', 'iiprop': 'url', }) if 'imageinfo' in page ] return self._images @property def coordinates(self): ''' Tuple of Decimals in the form of (lat, lon) or None ''' if not getattr(self, '_coordinates', False): query_params = { 'prop': 'coordinates', 'colimit': 'max', 'titles': self.title, } request = _wiki_request(query_params) if 'query' in request: coordinates = request['query']['pages'][self.pageid]['coordinates'] self._coordinates = (Decimal(coordinates[0]['lat']), Decimal(coordinates[0]['lon'])) else: self._coordinates = None return self._coordinates @property def references(self): ''' List of URLs of external links on a page. May include external links within page that aren't technically cited anywhere. ''' if not getattr(self, '_references', False): def add_protocol(url): return url if url.startswith('http') else 'http:' + url self._references = [ add_protocol(link['*']) for link in self.__continued_query({ 'prop': 'extlinks', 'ellimit': 'max' }) ] return self._references @property def links(self): ''' List of titles of Wikipedia page links on a page. .. note:: Only includes articles from namespace 0, meaning no Category, User talk, or other meta-Wikipedia pages. ''' if not getattr(self, '_links', False): self._links = [ link['title'] for link in self.__continued_query({ 'prop': 'links', 'plnamespace': 0, 'pllimit': 'max' }) ] return self._links @property def categories(self): ''' List of categories of a page. ''' if not getattr(self, '_categories', False): self._categories = [re.sub(r'^Category:', '', x) for x in [link['title'] for link in self.__continued_query({ 'prop': 'categories', 'cllimit': 'max' }) ]] return self._categories @property def sections(self): ''' List of section titles from the table of contents on the page. ''' if not getattr(self, '_sections', False): query_params = { 'action': 'parse', 'prop': 'sections', } query_params.update(self.__title_query_param) request = _wiki_request(query_params) self._sections = [section['line'] for section in request['parse']['sections']] return self._sections
chibisov/drf-extensions
docs/backdoc.py
_slugify
python
def _slugify(text, delim=u'-'): result = [] for word in _punct_re.split(text.lower()): word = word.encode('utf-8') if word: result.append(word) slugified = delim.join([i.decode('utf-8') for i in result]) return re.sub('[^a-zA-Z0-9\\s\\-]{1}', replace_char, slugified).lower()
Generates an ASCII-only slug.
train
https://github.com/chibisov/drf-extensions/blob/1d28a4b28890eab5cd19e93e042f8590c8c2fb8b/docs/backdoc.py#L1961-L1969
null
# -*- coding: utf-8 -*- #!/usr/bin/env python """ Backdoc is a tool for backbone-like documentation generation. Backdoc main goal is to help to generate one page documentation from one markdown source file. https://github.com/chibisov/backdoc """ import sys import argparse # -*- coding: utf-8 -*- #!/usr/bin/env python # Copyright (c) 2012 Trent Mick. # Copyright (c) 2007-2008 ActiveState Corp. # License: MIT (http://www.opensource.org/licenses/mit-license.php) r"""A fast and complete Python implementation of Markdown. [from http://daringfireball.net/projects/markdown/] > Markdown is a text-to-HTML filter; it translates an easy-to-read / > easy-to-write structured text format into HTML. Markdown's text > format is most similar to that of plain text email, and supports > features such as headers, *emphasis*, code blocks, blockquotes, and > links. > > Markdown's syntax is designed not as a generic markup language, but > specifically to serve as a front-end to (X)HTML. You can use span-level > HTML tags anywhere in a Markdown document, and you can use block level > HTML tags (like <div> and <table> as well). Module usage: >>> import markdown2 >>> markdown2.markdown("*boo!*") # or use `html = markdown_path(PATH)` u'<p><em>boo!</em></p>\n' >>> markdowner = Markdown() >>> markdowner.convert("*boo!*") u'<p><em>boo!</em></p>\n' >>> markdowner.convert("**boom!**") u'<p><strong>boom!</strong></p>\n' This implementation of Markdown implements the full "core" syntax plus a number of extras (e.g., code syntax coloring, footnotes) as described on <https://github.com/trentm/python-markdown2/wiki/Extras>. """ cmdln_desc = """A fast and complete Python implementation of Markdown, a text-to-HTML conversion tool for web writers. Supported extra syntax options (see -x|--extras option below and see <https://github.com/trentm/python-markdown2/wiki/Extras> for details): * code-friendly: Disable _ and __ for em and strong. * cuddled-lists: Allow lists to be cuddled to the preceding paragraph. * fenced-code-blocks: Allows a code block to not have to be indented by fencing it with '```' on a line before and after. Based on <http://github.github.com/github-flavored-markdown/> with support for syntax highlighting. * footnotes: Support footnotes as in use on daringfireball.net and implemented in other Markdown processors (tho not in Markdown.pl v1.0.1). * header-ids: Adds "id" attributes to headers. The id value is a slug of the header text. * html-classes: Takes a dict mapping html tag names (lowercase) to a string to use for a "class" tag attribute. Currently only supports "pre" and "code" tags. Add an issue if you require this for other tags. * markdown-in-html: Allow the use of `markdown="1"` in a block HTML tag to have markdown processing be done on its contents. Similar to <http://michelf.com/projects/php-markdown/extra/#markdown-attr> but with some limitations. * metadata: Extract metadata from a leading '---'-fenced block. See <https://github.com/trentm/python-markdown2/issues/77> for details. * nofollow: Add `rel="nofollow"` to add `<a>` tags with an href. See <http://en.wikipedia.org/wiki/Nofollow>. * pyshell: Treats unindented Python interactive shell sessions as <code> blocks. * link-patterns: Auto-link given regex patterns in text (e.g. bug number references, revision number references). * smarty-pants: Replaces ' and " with curly quotation marks or curly apostrophes. Replaces --, ---, ..., and . . . with en dashes, em dashes, and ellipses. * toc: The returned HTML string gets a new "toc_html" attribute which is a Table of Contents for the document. (experimental) * xml: Passes one-liner processing instructions and namespaced XML tags. * wiki-tables: Google Code Wiki-style tables. See <http://code.google.com/p/support/wiki/WikiSyntax#Tables>. """ # Dev Notes: # - Python's regex syntax doesn't have '\z', so I'm using '\Z'. I'm # not yet sure if there implications with this. Compare 'pydoc sre' # and 'perldoc perlre'. __version_info__ = (2, 1, 1) __version__ = '.'.join(map(str, __version_info__)) __author__ = "Trent Mick" import os import sys from pprint import pprint import re import logging try: from hashlib import md5 except ImportError: from md5 import md5 import optparse from random import random, randint import codecs #---- Python version compat try: from urllib.parse import quote # python3 except ImportError: from urllib import quote # python2 if sys.version_info[:2] < (2,4): from sets import Set as set def reversed(sequence): for i in sequence[::-1]: yield i # Use `bytes` for byte strings and `unicode` for unicode strings (str in Py3). if sys.version_info[0] <= 2: py3 = False try: bytes except NameError: bytes = str base_string_type = basestring elif sys.version_info[0] >= 3: py3 = True unicode = str base_string_type = str #---- globals DEBUG = False log = logging.getLogger("markdown") DEFAULT_TAB_WIDTH = 4 SECRET_SALT = bytes(randint(0, 1000000)) def _hash_text(s): return 'md5-' + md5(SECRET_SALT + s.encode("utf-8")).hexdigest() # Table of hash values for escaped characters: g_escape_table = dict([(ch, _hash_text(ch)) for ch in '\\`*_{}[]()>#+-.!']) #---- exceptions class MarkdownError(Exception): pass #---- public api def markdown_path(path, encoding="utf-8", html4tags=False, tab_width=DEFAULT_TAB_WIDTH, safe_mode=None, extras=None, link_patterns=None, use_file_vars=False): fp = codecs.open(path, 'r', encoding) text = fp.read() fp.close() return Markdown(html4tags=html4tags, tab_width=tab_width, safe_mode=safe_mode, extras=extras, link_patterns=link_patterns, use_file_vars=use_file_vars).convert(text) def markdown(text, html4tags=False, tab_width=DEFAULT_TAB_WIDTH, safe_mode=None, extras=None, link_patterns=None, use_file_vars=False): return Markdown(html4tags=html4tags, tab_width=tab_width, safe_mode=safe_mode, extras=extras, link_patterns=link_patterns, use_file_vars=use_file_vars).convert(text) class Markdown(object): # The dict of "extras" to enable in processing -- a mapping of # extra name to argument for the extra. Most extras do not have an # argument, in which case the value is None. # # This can be set via (a) subclassing and (b) the constructor # "extras" argument. extras = None urls = None titles = None html_blocks = None html_spans = None html_removed_text = "[HTML_REMOVED]" # for compat with markdown.py # Used to track when we're inside an ordered or unordered list # (see _ProcessListItems() for details): list_level = 0 _ws_only_line_re = re.compile(r"^[ \t]+$", re.M) def __init__(self, html4tags=False, tab_width=4, safe_mode=None, extras=None, link_patterns=None, use_file_vars=False): if html4tags: self.empty_element_suffix = ">" else: self.empty_element_suffix = " />" self.tab_width = tab_width # For compatibility with earlier markdown2.py and with # markdown.py's safe_mode being a boolean, # safe_mode == True -> "replace" if safe_mode is True: self.safe_mode = "replace" else: self.safe_mode = safe_mode # Massaging and building the "extras" info. if self.extras is None: self.extras = {} elif not isinstance(self.extras, dict): self.extras = dict([(e, None) for e in self.extras]) if extras: if not isinstance(extras, dict): extras = dict([(e, None) for e in extras]) self.extras.update(extras) assert isinstance(self.extras, dict) if "toc" in self.extras and not "header-ids" in self.extras: self.extras["header-ids"] = None # "toc" implies "header-ids" self._instance_extras = self.extras.copy() self.link_patterns = link_patterns self.use_file_vars = use_file_vars self._outdent_re = re.compile(r'^(\t|[ ]{1,%d})' % tab_width, re.M) self._escape_table = g_escape_table.copy() if "smarty-pants" in self.extras: self._escape_table['"'] = _hash_text('"') self._escape_table["'"] = _hash_text("'") def reset(self): self.urls = {} self.titles = {} self.html_blocks = {} self.html_spans = {} self.list_level = 0 self.extras = self._instance_extras.copy() if "footnotes" in self.extras: self.footnotes = {} self.footnote_ids = [] if "header-ids" in self.extras: self._count_from_header_id = {} # no `defaultdict` in Python 2.4 if "metadata" in self.extras: self.metadata = {} # Per <https://developer.mozilla.org/en-US/docs/HTML/Element/a> "rel" # should only be used in <a> tags with an "href" attribute. _a_nofollow = re.compile(r"<(a)([^>]*href=)", re.IGNORECASE) def convert(self, text): """Convert the given text.""" # Main function. The order in which other subs are called here is # essential. Link and image substitutions need to happen before # _EscapeSpecialChars(), so that any *'s or _'s in the <a> # and <img> tags get encoded. # Clear the global hashes. If we don't clear these, you get conflicts # from other articles when generating a page which contains more than # one article (e.g. an index page that shows the N most recent # articles): self.reset() if not isinstance(text, unicode): #TODO: perhaps shouldn't presume UTF-8 for string input? text = unicode(text, 'utf-8') if self.use_file_vars: # Look for emacs-style file variable hints. emacs_vars = self._get_emacs_vars(text) if "markdown-extras" in emacs_vars: splitter = re.compile("[ ,]+") for e in splitter.split(emacs_vars["markdown-extras"]): if '=' in e: ename, earg = e.split('=', 1) try: earg = int(earg) except ValueError: pass else: ename, earg = e, None self.extras[ename] = earg # Standardize line endings: text = re.sub("\r\n|\r", "\n", text) # Make sure $text ends with a couple of newlines: text += "\n\n" # Convert all tabs to spaces. text = self._detab(text) # Strip any lines consisting only of spaces and tabs. # This makes subsequent regexen easier to write, because we can # match consecutive blank lines with /\n+/ instead of something # contorted like /[ \t]*\n+/ . text = self._ws_only_line_re.sub("", text) # strip metadata from head and extract if "metadata" in self.extras: text = self._extract_metadata(text) text = self.preprocess(text) if self.safe_mode: text = self._hash_html_spans(text) # Turn block-level HTML blocks into hash entries text = self._hash_html_blocks(text, raw=True) # Strip link definitions, store in hashes. if "footnotes" in self.extras: # Must do footnotes first because an unlucky footnote defn # looks like a link defn: # [^4]: this "looks like a link defn" text = self._strip_footnote_definitions(text) text = self._strip_link_definitions(text) text = self._run_block_gamut(text) if "footnotes" in self.extras: text = self._add_footnotes(text) text = self.postprocess(text) text = self._unescape_special_chars(text) if self.safe_mode: text = self._unhash_html_spans(text) if "nofollow" in self.extras: text = self._a_nofollow.sub(r'<\1 rel="nofollow"\2', text) text += "\n" rv = UnicodeWithAttrs(text) if "toc" in self.extras: rv._toc = self._toc if "metadata" in self.extras: rv.metadata = self.metadata return rv def postprocess(self, text): """A hook for subclasses to do some postprocessing of the html, if desired. This is called before unescaping of special chars and unhashing of raw HTML spans. """ return text def preprocess(self, text): """A hook for subclasses to do some preprocessing of the Markdown, if desired. This is called after basic formatting of the text, but prior to any extras, safe mode, etc. processing. """ return text # Is metadata if the content starts with '---'-fenced `key: value` # pairs. E.g. (indented for presentation): # --- # foo: bar # another-var: blah blah # --- _metadata_pat = re.compile("""^---[ \t]*\n((?:[ \t]*[^ \t:]+[ \t]*:[^\n]*\n)+)---[ \t]*\n""") def _extract_metadata(self, text): # fast test if not text.startswith("---"): return text match = self._metadata_pat.match(text) if not match: return text tail = text[len(match.group(0)):] metadata_str = match.group(1).strip() for line in metadata_str.split('\n'): key, value = line.split(':', 1) self.metadata[key.strip()] = value.strip() return tail _emacs_oneliner_vars_pat = re.compile(r"-\*-\s*([^\r\n]*?)\s*-\*-", re.UNICODE) # This regular expression is intended to match blocks like this: # PREFIX Local Variables: SUFFIX # PREFIX mode: Tcl SUFFIX # PREFIX End: SUFFIX # Some notes: # - "[ \t]" is used instead of "\s" to specifically exclude newlines # - "(\r\n|\n|\r)" is used instead of "$" because the sre engine does # not like anything other than Unix-style line terminators. _emacs_local_vars_pat = re.compile(r"""^ (?P<prefix>(?:[^\r\n|\n|\r])*?) [\ \t]*Local\ Variables:[\ \t]* (?P<suffix>.*?)(?:\r\n|\n|\r) (?P<content>.*?\1End:) """, re.IGNORECASE | re.MULTILINE | re.DOTALL | re.VERBOSE) def _get_emacs_vars(self, text): """Return a dictionary of emacs-style local variables. Parsing is done loosely according to this spec (and according to some in-practice deviations from this): http://www.gnu.org/software/emacs/manual/html_node/emacs/Specifying-File-Variables.html#Specifying-File-Variables """ emacs_vars = {} SIZE = pow(2, 13) # 8kB # Search near the start for a '-*-'-style one-liner of variables. head = text[:SIZE] if "-*-" in head: match = self._emacs_oneliner_vars_pat.search(head) if match: emacs_vars_str = match.group(1) assert '\n' not in emacs_vars_str emacs_var_strs = [s.strip() for s in emacs_vars_str.split(';') if s.strip()] if len(emacs_var_strs) == 1 and ':' not in emacs_var_strs[0]: # While not in the spec, this form is allowed by emacs: # -*- Tcl -*- # where the implied "variable" is "mode". This form # is only allowed if there are no other variables. emacs_vars["mode"] = emacs_var_strs[0].strip() else: for emacs_var_str in emacs_var_strs: try: variable, value = emacs_var_str.strip().split(':', 1) except ValueError: log.debug("emacs variables error: malformed -*- " "line: %r", emacs_var_str) continue # Lowercase the variable name because Emacs allows "Mode" # or "mode" or "MoDe", etc. emacs_vars[variable.lower()] = value.strip() tail = text[-SIZE:] if "Local Variables" in tail: match = self._emacs_local_vars_pat.search(tail) if match: prefix = match.group("prefix") suffix = match.group("suffix") lines = match.group("content").splitlines(0) #print "prefix=%r, suffix=%r, content=%r, lines: %s"\ # % (prefix, suffix, match.group("content"), lines) # Validate the Local Variables block: proper prefix and suffix # usage. for i, line in enumerate(lines): if not line.startswith(prefix): log.debug("emacs variables error: line '%s' " "does not use proper prefix '%s'" % (line, prefix)) return {} # Don't validate suffix on last line. Emacs doesn't care, # neither should we. if i != len(lines)-1 and not line.endswith(suffix): log.debug("emacs variables error: line '%s' " "does not use proper suffix '%s'" % (line, suffix)) return {} # Parse out one emacs var per line. continued_for = None for line in lines[:-1]: # no var on the last line ("PREFIX End:") if prefix: line = line[len(prefix):] # strip prefix if suffix: line = line[:-len(suffix)] # strip suffix line = line.strip() if continued_for: variable = continued_for if line.endswith('\\'): line = line[:-1].rstrip() else: continued_for = None emacs_vars[variable] += ' ' + line else: try: variable, value = line.split(':', 1) except ValueError: log.debug("local variables error: missing colon " "in local variables entry: '%s'" % line) continue # Do NOT lowercase the variable name, because Emacs only # allows "mode" (and not "Mode", "MoDe", etc.) in this block. value = value.strip() if value.endswith('\\'): value = value[:-1].rstrip() continued_for = variable else: continued_for = None emacs_vars[variable] = value # Unquote values. for var, val in list(emacs_vars.items()): if len(val) > 1 and (val.startswith('"') and val.endswith('"') or val.startswith('"') and val.endswith('"')): emacs_vars[var] = val[1:-1] return emacs_vars # Cribbed from a post by Bart Lateur: # <http://www.nntp.perl.org/group/perl.macperl.anyperl/154> _detab_re = re.compile(r'(.*?)\t', re.M) def _detab_sub(self, match): g1 = match.group(1) return g1 + (' ' * (self.tab_width - len(g1) % self.tab_width)) def _detab(self, text): r"""Remove (leading?) tabs from a file. >>> m = Markdown() >>> m._detab("\tfoo") ' foo' >>> m._detab(" \tfoo") ' foo' >>> m._detab("\t foo") ' foo' >>> m._detab(" foo") ' foo' >>> m._detab(" foo\n\tbar\tblam") ' foo\n bar blam' """ if '\t' not in text: return text return self._detab_re.subn(self._detab_sub, text)[0] # I broke out the html5 tags here and add them to _block_tags_a and # _block_tags_b. This way html5 tags are easy to keep track of. _html5tags = '|article|aside|header|hgroup|footer|nav|section|figure|figcaption' _block_tags_a = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del' _block_tags_a += _html5tags _strict_tag_block_re = re.compile(r""" ( # save in \1 ^ # start of line (with re.M) <(%s) # start tag = \2 \b # word break (.*\n)*? # any number of lines, minimally matching </\2> # the matching end tag [ \t]* # trailing spaces/tabs (?=\n+|\Z) # followed by a newline or end of document ) """ % _block_tags_a, re.X | re.M) _block_tags_b = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math' _block_tags_b += _html5tags _liberal_tag_block_re = re.compile(r""" ( # save in \1 ^ # start of line (with re.M) <(%s) # start tag = \2 \b # word break (.*\n)*? # any number of lines, minimally matching .*</\2> # the matching end tag [ \t]* # trailing spaces/tabs (?=\n+|\Z) # followed by a newline or end of document ) """ % _block_tags_b, re.X | re.M) _html_markdown_attr_re = re.compile( r'''\s+markdown=("1"|'1')''') def _hash_html_block_sub(self, match, raw=False): html = match.group(1) if raw and self.safe_mode: html = self._sanitize_html(html) elif 'markdown-in-html' in self.extras and 'markdown=' in html: first_line = html.split('\n', 1)[0] m = self._html_markdown_attr_re.search(first_line) if m: lines = html.split('\n') middle = '\n'.join(lines[1:-1]) last_line = lines[-1] first_line = first_line[:m.start()] + first_line[m.end():] f_key = _hash_text(first_line) self.html_blocks[f_key] = first_line l_key = _hash_text(last_line) self.html_blocks[l_key] = last_line return ''.join(["\n\n", f_key, "\n\n", middle, "\n\n", l_key, "\n\n"]) key = _hash_text(html) self.html_blocks[key] = html return "\n\n" + key + "\n\n" def _hash_html_blocks(self, text, raw=False): """Hashify HTML blocks We only want to do this for block-level HTML tags, such as headers, lists, and tables. That's because we still want to wrap <p>s around "paragraphs" that are wrapped in non-block-level tags, such as anchors, phrase emphasis, and spans. The list of tags we're looking for is hard-coded. @param raw {boolean} indicates if these are raw HTML blocks in the original source. It makes a difference in "safe" mode. """ if '<' not in text: return text # Pass `raw` value into our calls to self._hash_html_block_sub. hash_html_block_sub = _curry(self._hash_html_block_sub, raw=raw) # First, look for nested blocks, e.g.: # <div> # <div> # tags for inner block must be indented. # </div> # </div> # # The outermost tags must start at the left margin for this to match, and # the inner nested divs must be indented. # We need to do this before the next, more liberal match, because the next # match will start at the first `<div>` and stop at the first `</div>`. text = self._strict_tag_block_re.sub(hash_html_block_sub, text) # Now match more liberally, simply from `\n<tag>` to `</tag>\n` text = self._liberal_tag_block_re.sub(hash_html_block_sub, text) # Special case just for <hr />. It was easier to make a special # case than to make the other regex more complicated. if "<hr" in text: _hr_tag_re = _hr_tag_re_from_tab_width(self.tab_width) text = _hr_tag_re.sub(hash_html_block_sub, text) # Special case for standalone HTML comments: if "<!--" in text: start = 0 while True: # Delimiters for next comment block. try: start_idx = text.index("<!--", start) except ValueError: break try: end_idx = text.index("-->", start_idx) + 3 except ValueError: break # Start position for next comment block search. start = end_idx # Validate whitespace before comment. if start_idx: # - Up to `tab_width - 1` spaces before start_idx. for i in range(self.tab_width - 1): if text[start_idx - 1] != ' ': break start_idx -= 1 if start_idx == 0: break # - Must be preceded by 2 newlines or hit the start of # the document. if start_idx == 0: pass elif start_idx == 1 and text[0] == '\n': start_idx = 0 # to match minute detail of Markdown.pl regex elif text[start_idx-2:start_idx] == '\n\n': pass else: break # Validate whitespace after comment. # - Any number of spaces and tabs. while end_idx < len(text): if text[end_idx] not in ' \t': break end_idx += 1 # - Must be following by 2 newlines or hit end of text. if text[end_idx:end_idx+2] not in ('', '\n', '\n\n'): continue # Escape and hash (must match `_hash_html_block_sub`). html = text[start_idx:end_idx] if raw and self.safe_mode: html = self._sanitize_html(html) key = _hash_text(html) self.html_blocks[key] = html text = text[:start_idx] + "\n\n" + key + "\n\n" + text[end_idx:] if "xml" in self.extras: # Treat XML processing instructions and namespaced one-liner # tags as if they were block HTML tags. E.g., if standalone # (i.e. are their own paragraph), the following do not get # wrapped in a <p> tag: # <?foo bar?> # # <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="chapter_1.md"/> _xml_oneliner_re = _xml_oneliner_re_from_tab_width(self.tab_width) text = _xml_oneliner_re.sub(hash_html_block_sub, text) return text def _strip_link_definitions(self, text): # Strips link definitions from text, stores the URLs and titles in # hash references. less_than_tab = self.tab_width - 1 # Link defs are in the form: # [id]: url "optional title" _link_def_re = re.compile(r""" ^[ ]{0,%d}\[(.+)\]: # id = \1 [ \t]* \n? # maybe *one* newline [ \t]* <?(.+?)>? # url = \2 [ \t]* (?: \n? # maybe one newline [ \t]* (?<=\s) # lookbehind for whitespace ['"(] ([^\n]*) # title = \3 ['")] [ \t]* )? # title is optional (?:\n+|\Z) """ % less_than_tab, re.X | re.M | re.U) return _link_def_re.sub(self._extract_link_def_sub, text) def _extract_link_def_sub(self, match): id, url, title = match.groups() key = id.lower() # Link IDs are case-insensitive self.urls[key] = self._encode_amps_and_angles(url) if title: self.titles[key] = title return "" def _extract_footnote_def_sub(self, match): id, text = match.groups() text = _dedent(text, skip_first_line=not text.startswith('\n')).strip() normed_id = re.sub(r'\W', '-', id) # Ensure footnote text ends with a couple newlines (for some # block gamut matches). self.footnotes[normed_id] = text + "\n\n" return "" def _strip_footnote_definitions(self, text): """A footnote definition looks like this: [^note-id]: Text of the note. May include one or more indented paragraphs. Where, - The 'note-id' can be pretty much anything, though typically it is the number of the footnote. - The first paragraph may start on the next line, like so: [^note-id]: Text of the note. """ less_than_tab = self.tab_width - 1 footnote_def_re = re.compile(r''' ^[ ]{0,%d}\[\^(.+)\]: # id = \1 [ \t]* ( # footnote text = \2 # First line need not start with the spaces. (?:\s*.*\n+) (?: (?:[ ]{%d} | \t) # Subsequent lines must be indented. .*\n+ )* ) # Lookahead for non-space at line-start, or end of doc. (?:(?=^[ ]{0,%d}\S)|\Z) ''' % (less_than_tab, self.tab_width, self.tab_width), re.X | re.M) return footnote_def_re.sub(self._extract_footnote_def_sub, text) _hr_data = [ ('*', re.compile(r"^[ ]{0,3}\*(.*?)$", re.M)), ('-', re.compile(r"^[ ]{0,3}\-(.*?)$", re.M)), ('_', re.compile(r"^[ ]{0,3}\_(.*?)$", re.M)), ] def _run_block_gamut(self, text): # These are all the transformations that form block-level # tags like paragraphs, headers, and list items. if "fenced-code-blocks" in self.extras: text = self._do_fenced_code_blocks(text) text = self._do_headers(text) # Do Horizontal Rules: # On the number of spaces in horizontal rules: The spec is fuzzy: "If # you wish, you may use spaces between the hyphens or asterisks." # Markdown.pl 1.0.1's hr regexes limit the number of spaces between the # hr chars to one or two. We'll reproduce that limit here. hr = "\n<hr"+self.empty_element_suffix+"\n" for ch, regex in self._hr_data: if ch in text: for m in reversed(list(regex.finditer(text))): tail = m.group(1).rstrip() if not tail.strip(ch + ' ') and tail.count(" ") == 0: start, end = m.span() text = text[:start] + hr + text[end:] text = self._do_lists(text) if "pyshell" in self.extras: text = self._prepare_pyshell_blocks(text) if "wiki-tables" in self.extras: text = self._do_wiki_tables(text) text = self._do_code_blocks(text) text = self._do_block_quotes(text) # We already ran _HashHTMLBlocks() before, in Markdown(), but that # was to escape raw HTML in the original Markdown source. This time, # we're escaping the markup we've just created, so that we don't wrap # <p> tags around block-level tags. text = self._hash_html_blocks(text) text = self._form_paragraphs(text) return text def _pyshell_block_sub(self, match): lines = match.group(0).splitlines(0) _dedentlines(lines) indent = ' ' * self.tab_width s = ('\n' # separate from possible cuddled paragraph + indent + ('\n'+indent).join(lines) + '\n\n') return s def _prepare_pyshell_blocks(self, text): """Ensure that Python interactive shell sessions are put in code blocks -- even if not properly indented. """ if ">>>" not in text: return text less_than_tab = self.tab_width - 1 _pyshell_block_re = re.compile(r""" ^([ ]{0,%d})>>>[ ].*\n # first line ^(\1.*\S+.*\n)* # any number of subsequent lines ^\n # ends with a blank line """ % less_than_tab, re.M | re.X) return _pyshell_block_re.sub(self._pyshell_block_sub, text) def _wiki_table_sub(self, match): ttext = match.group(0).strip() #print 'wiki table: %r' % match.group(0) rows = [] for line in ttext.splitlines(0): line = line.strip()[2:-2].strip() row = [c.strip() for c in re.split(r'(?<!\\)\|\|', line)] rows.append(row) #pprint(rows) hlines = ['<table>', '<tbody>'] for row in rows: hrow = ['<tr>'] for cell in row: hrow.append('<td>') hrow.append(self._run_span_gamut(cell)) hrow.append('</td>') hrow.append('</tr>') hlines.append(''.join(hrow)) hlines += ['</tbody>', '</table>'] return '\n'.join(hlines) + '\n' def _do_wiki_tables(self, text): # Optimization. if "||" not in text: return text less_than_tab = self.tab_width - 1 wiki_table_re = re.compile(r''' (?:(?<=\n\n)|\A\n?) # leading blank line ^([ ]{0,%d})\|\|.+?\|\|[ ]*\n # first line (^\1\|\|.+?\|\|\n)* # any number of subsequent lines ''' % less_than_tab, re.M | re.X) return wiki_table_re.sub(self._wiki_table_sub, text) def _run_span_gamut(self, text): # These are all the transformations that occur *within* block-level # tags like paragraphs, headers, and list items. text = self._do_code_spans(text) text = self._escape_special_chars(text) # Process anchor and image tags. text = self._do_links(text) # Make links out of things like `<http://example.com/>` # Must come after _do_links(), because you can use < and > # delimiters in inline links like [this](<url>). text = self._do_auto_links(text) if "link-patterns" in self.extras: text = self._do_link_patterns(text) text = self._encode_amps_and_angles(text) text = self._do_italics_and_bold(text) if "smarty-pants" in self.extras: text = self._do_smart_punctuation(text) # Do hard breaks: text = re.sub(r" {2,}\n", " <br%s\n" % self.empty_element_suffix, text) return text # "Sorta" because auto-links are identified as "tag" tokens. _sorta_html_tokenize_re = re.compile(r""" ( # tag </? (?:\w+) # tag name (?:\s+(?:[\w-]+:)?[\w-]+=(?:".*?"|'.*?'))* # attributes \s*/?> | # auto-link (e.g., <http://www.activestate.com/>) <\w+[^>]*> | <!--.*?--> # comment | <\?.*?\?> # processing instruction ) """, re.X) def _escape_special_chars(self, text): # Python markdown note: the HTML tokenization here differs from # that in Markdown.pl, hence the behaviour for subtle cases can # differ (I believe the tokenizer here does a better job because # it isn't susceptible to unmatched '<' and '>' in HTML tags). # Note, however, that '>' is not allowed in an auto-link URL # here. escaped = [] is_html_markup = False for token in self._sorta_html_tokenize_re.split(text): if is_html_markup: # Within tags/HTML-comments/auto-links, encode * and _ # so they don't conflict with their use in Markdown for # italics and strong. We're replacing each such # character with its corresponding MD5 checksum value; # this is likely overkill, but it should prevent us from # colliding with the escape values by accident. escaped.append(token.replace('*', self._escape_table['*']) .replace('_', self._escape_table['_'])) else: escaped.append(self._encode_backslash_escapes(token)) is_html_markup = not is_html_markup return ''.join(escaped) def _hash_html_spans(self, text): # Used for safe_mode. def _is_auto_link(s): if ':' in s and self._auto_link_re.match(s): return True elif '@' in s and self._auto_email_link_re.match(s): return True return False tokens = [] is_html_markup = False for token in self._sorta_html_tokenize_re.split(text): if is_html_markup and not _is_auto_link(token): sanitized = self._sanitize_html(token) key = _hash_text(sanitized) self.html_spans[key] = sanitized tokens.append(key) else: tokens.append(token) is_html_markup = not is_html_markup return ''.join(tokens) def _unhash_html_spans(self, text): for key, sanitized in list(self.html_spans.items()): text = text.replace(key, sanitized) return text def _sanitize_html(self, s): if self.safe_mode == "replace": return self.html_removed_text elif self.safe_mode == "escape": replacements = [ ('&', '&amp;'), ('<', '&lt;'), ('>', '&gt;'), ] for before, after in replacements: s = s.replace(before, after) return s else: raise MarkdownError("invalid value for 'safe_mode': %r (must be " "'escape' or 'replace')" % self.safe_mode) _tail_of_inline_link_re = re.compile(r''' # Match tail of: [text](/url/) or [text](/url/ "title") \( # literal paren [ \t]* (?P<url> # \1 <.*?> | .*? ) [ \t]* ( # \2 (['"]) # quote char = \3 (?P<title>.*?) \3 # matching quote )? # title is optional \) ''', re.X | re.S) _tail_of_reference_link_re = re.compile(r''' # Match tail of: [text][id] [ ]? # one optional space (?:\n[ ]*)? # one optional newline followed by spaces \[ (?P<id>.*?) \] ''', re.X | re.S) def _do_links(self, text): """Turn Markdown link shortcuts into XHTML <a> and <img> tags. This is a combination of Markdown.pl's _DoAnchors() and _DoImages(). They are done together because that simplified the approach. It was necessary to use a different approach than Markdown.pl because of the lack of atomic matching support in Python's regex engine used in $g_nested_brackets. """ MAX_LINK_TEXT_SENTINEL = 3000 # markdown2 issue 24 # `anchor_allowed_pos` is used to support img links inside # anchors, but not anchors inside anchors. An anchor's start # pos must be `>= anchor_allowed_pos`. anchor_allowed_pos = 0 curr_pos = 0 while True: # Handle the next link. # The next '[' is the start of: # - an inline anchor: [text](url "title") # - a reference anchor: [text][id] # - an inline img: ![text](url "title") # - a reference img: ![text][id] # - a footnote ref: [^id] # (Only if 'footnotes' extra enabled) # - a footnote defn: [^id]: ... # (Only if 'footnotes' extra enabled) These have already # been stripped in _strip_footnote_definitions() so no # need to watch for them. # - a link definition: [id]: url "title" # These have already been stripped in # _strip_link_definitions() so no need to watch for them. # - not markup: [...anything else... try: start_idx = text.index('[', curr_pos) except ValueError: break text_length = len(text) # Find the matching closing ']'. # Markdown.pl allows *matching* brackets in link text so we # will here too. Markdown.pl *doesn't* currently allow # matching brackets in img alt text -- we'll differ in that # regard. bracket_depth = 0 for p in range(start_idx+1, min(start_idx+MAX_LINK_TEXT_SENTINEL, text_length)): ch = text[p] if ch == ']': bracket_depth -= 1 if bracket_depth < 0: break elif ch == '[': bracket_depth += 1 else: # Closing bracket not found within sentinel length. # This isn't markup. curr_pos = start_idx + 1 continue link_text = text[start_idx+1:p] # Possibly a footnote ref? if "footnotes" in self.extras and link_text.startswith("^"): normed_id = re.sub(r'\W', '-', link_text[1:]) if normed_id in self.footnotes: self.footnote_ids.append(normed_id) result = '<sup class="footnote-ref" id="fnref-%s">' \ '<a href="#fn-%s">%s</a></sup>' \ % (normed_id, normed_id, len(self.footnote_ids)) text = text[:start_idx] + result + text[p+1:] else: # This id isn't defined, leave the markup alone. curr_pos = p+1 continue # Now determine what this is by the remainder. p += 1 if p == text_length: return text # Inline anchor or img? if text[p] == '(': # attempt at perf improvement match = self._tail_of_inline_link_re.match(text, p) if match: # Handle an inline anchor or img. is_img = start_idx > 0 and text[start_idx-1] == "!" if is_img: start_idx -= 1 url, title = match.group("url"), match.group("title") if url and url[0] == '<': url = url[1:-1] # '<url>' -> 'url' # We've got to encode these to avoid conflicting # with italics/bold. url = url.replace('*', self._escape_table['*']) \ .replace('_', self._escape_table['_']) if title: title_str = ' title="%s"' % ( _xml_escape_attr(title) .replace('*', self._escape_table['*']) .replace('_', self._escape_table['_'])) else: title_str = '' if is_img: result = '<img src="%s" alt="%s"%s%s' \ % (url.replace('"', '&quot;'), _xml_escape_attr(link_text), title_str, self.empty_element_suffix) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) curr_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] elif start_idx >= anchor_allowed_pos: result_head = '<a href="%s"%s>' % (url, title_str) result = '%s%s</a>' % (result_head, link_text) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) # <img> allowed from curr_pos on, <a> from # anchor_allowed_pos on. curr_pos = start_idx + len(result_head) anchor_allowed_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] else: # Anchor not allowed here. curr_pos = start_idx + 1 continue # Reference anchor or img? else: match = self._tail_of_reference_link_re.match(text, p) if match: # Handle a reference-style anchor or img. is_img = start_idx > 0 and text[start_idx-1] == "!" if is_img: start_idx -= 1 link_id = match.group("id").lower() if not link_id: link_id = link_text.lower() # for links like [this][] if link_id in self.urls: url = self.urls[link_id] # We've got to encode these to avoid conflicting # with italics/bold. url = url.replace('*', self._escape_table['*']) \ .replace('_', self._escape_table['_']) title = self.titles.get(link_id) if title: before = title title = _xml_escape_attr(title) \ .replace('*', self._escape_table['*']) \ .replace('_', self._escape_table['_']) title_str = ' title="%s"' % title else: title_str = '' if is_img: result = '<img src="%s" alt="%s"%s%s' \ % (url.replace('"', '&quot;'), link_text.replace('"', '&quot;'), title_str, self.empty_element_suffix) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) curr_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] elif start_idx >= anchor_allowed_pos: result = '<a href="%s"%s>%s</a>' \ % (url, title_str, link_text) result_head = '<a href="%s"%s>' % (url, title_str) result = '%s%s</a>' % (result_head, link_text) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) # <img> allowed from curr_pos on, <a> from # anchor_allowed_pos on. curr_pos = start_idx + len(result_head) anchor_allowed_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] else: # Anchor not allowed here. curr_pos = start_idx + 1 else: # This id isn't defined, leave the markup alone. curr_pos = match.end() continue # Otherwise, it isn't markup. curr_pos = start_idx + 1 return text def header_id_from_text(self, text, prefix, n): """Generate a header id attribute value from the given header HTML content. This is only called if the "header-ids" extra is enabled. Subclasses may override this for different header ids. @param text {str} The text of the header tag @param prefix {str} The requested prefix for header ids. This is the value of the "header-ids" extra key, if any. Otherwise, None. @param n {int} The <hN> tag number, i.e. `1` for an <h1> tag. @returns {str} The value for the header tag's "id" attribute. Return None to not have an id attribute and to exclude this header from the TOC (if the "toc" extra is specified). """ header_id = _slugify(text) if prefix and isinstance(prefix, base_string_type): header_id = prefix + '-' + header_id if header_id in self._count_from_header_id: self._count_from_header_id[header_id] += 1 header_id += '-%s' % self._count_from_header_id[header_id] else: self._count_from_header_id[header_id] = 1 return header_id _toc = None def _toc_add_entry(self, level, id, name): if self._toc is None: self._toc = [] self._toc.append((level, id, self._unescape_special_chars(name))) _setext_h_re = re.compile(r'^(.+)[ \t]*\n(=+|-+)[ \t]*\n+', re.M) def _setext_h_sub(self, match): n = {"=": 1, "-": 2}[match.group(2)[0]] demote_headers = self.extras.get("demote-headers") if demote_headers: n = min(n + demote_headers, 6) header_id_attr = "" if "header-ids" in self.extras: header_id = self.header_id_from_text(match.group(1), self.extras["header-ids"], n) if header_id: header_id_attr = ' id="%s"' % header_id html = self._run_span_gamut(match.group(1)) if "toc" in self.extras and header_id: self._toc_add_entry(n, header_id, html) return "<h%d%s>%s</h%d>\n\n" % (n, header_id_attr, html, n) _atx_h_re = re.compile(r''' ^(\#{1,6}) # \1 = string of #'s [ \t]+ (.+?) # \2 = Header text [ \t]* (?<!\\) # ensure not an escaped trailing '#' \#* # optional closing #'s (not counted) \n+ ''', re.X | re.M) def _atx_h_sub(self, match): n = len(match.group(1)) demote_headers = self.extras.get("demote-headers") if demote_headers: n = min(n + demote_headers, 6) header_id_attr = "" if "header-ids" in self.extras: header_id = self.header_id_from_text(match.group(2), self.extras["header-ids"], n) if header_id: header_id_attr = ' id="%s"' % header_id html = self._run_span_gamut(match.group(2)) if "toc" in self.extras and header_id: self._toc_add_entry(n, header_id, html) return "<h%d%s>%s</h%d>\n\n" % (n, header_id_attr, html, n) def _do_headers(self, text): # Setext-style headers: # Header 1 # ======== # # Header 2 # -------- text = self._setext_h_re.sub(self._setext_h_sub, text) # atx-style headers: # # Header 1 # ## Header 2 # ## Header 2 with closing hashes ## # ... # ###### Header 6 text = self._atx_h_re.sub(self._atx_h_sub, text) return text _marker_ul_chars = '*+-' _marker_any = r'(?:[%s]|\d+\.)' % _marker_ul_chars _marker_ul = '(?:[%s])' % _marker_ul_chars _marker_ol = r'(?:\d+\.)' def _list_sub(self, match): lst = match.group(1) lst_type = match.group(3) in self._marker_ul_chars and "ul" or "ol" result = self._process_list_items(lst) if self.list_level: return "<%s>\n%s</%s>\n" % (lst_type, result, lst_type) else: return "<%s>\n%s</%s>\n\n" % (lst_type, result, lst_type) def _do_lists(self, text): # Form HTML ordered (numbered) and unordered (bulleted) lists. # Iterate over each *non-overlapping* list match. pos = 0 while True: # Find the *first* hit for either list style (ul or ol). We # match ul and ol separately to avoid adjacent lists of different # types running into each other (see issue #16). hits = [] for marker_pat in (self._marker_ul, self._marker_ol): less_than_tab = self.tab_width - 1 whole_list = r''' ( # \1 = whole list ( # \2 [ ]{0,%d} (%s) # \3 = first list item marker [ \t]+ (?!\ *\3\ ) # '- - - ...' isn't a list. See 'not_quite_a_list' test case. ) (?:.+?) ( # \4 \Z | \n{2,} (?=\S) (?! # Negative lookahead for another list item marker [ \t]* %s[ \t]+ ) ) ) ''' % (less_than_tab, marker_pat, marker_pat) if self.list_level: # sub-list list_re = re.compile("^"+whole_list, re.X | re.M | re.S) else: list_re = re.compile(r"(?:(?<=\n\n)|\A\n?)"+whole_list, re.X | re.M | re.S) match = list_re.search(text, pos) if match: hits.append((match.start(), match)) if not hits: break hits.sort() match = hits[0][1] start, end = match.span() text = text[:start] + self._list_sub(match) + text[end:] pos = end return text _list_item_re = re.compile(r''' (\n)? # leading line = \1 (^[ \t]*) # leading whitespace = \2 (?P<marker>%s) [ \t]+ # list marker = \3 ((?:.+?) # list item text = \4 (\n{1,2})) # eols = \5 (?= \n* (\Z | \2 (?P<next_marker>%s) [ \t]+)) ''' % (_marker_any, _marker_any), re.M | re.X | re.S) _last_li_endswith_two_eols = False def _list_item_sub(self, match): item = match.group(4) leading_line = match.group(1) leading_space = match.group(2) if leading_line or "\n\n" in item or self._last_li_endswith_two_eols: item = self._run_block_gamut(self._outdent(item)) else: # Recursion for sub-lists: item = self._do_lists(self._outdent(item)) if item.endswith('\n'): item = item[:-1] item = self._run_span_gamut(item) self._last_li_endswith_two_eols = (len(match.group(5)) == 2) return "<li>%s</li>\n" % item def _process_list_items(self, list_str): # Process the contents of a single ordered or unordered list, # splitting it into individual list items. # The $g_list_level global keeps track of when we're inside a list. # Each time we enter a list, we increment it; when we leave a list, # we decrement. If it's zero, we're not in a list anymore. # # We do this because when we're not inside a list, we want to treat # something like this: # # I recommend upgrading to version # 8. Oops, now this line is treated # as a sub-list. # # As a single paragraph, despite the fact that the second line starts # with a digit-period-space sequence. # # Whereas when we're inside a list (or sub-list), that line will be # treated as the start of a sub-list. What a kludge, huh? This is # an aspect of Markdown's syntax that's hard to parse perfectly # without resorting to mind-reading. Perhaps the solution is to # change the syntax rules such that sub-lists must start with a # starting cardinal number; e.g. "1." or "a.". self.list_level += 1 self._last_li_endswith_two_eols = False list_str = list_str.rstrip('\n') + '\n' list_str = self._list_item_re.sub(self._list_item_sub, list_str) self.list_level -= 1 return list_str def _get_pygments_lexer(self, lexer_name): try: from pygments import lexers, util except ImportError: return None try: return lexers.get_lexer_by_name(lexer_name) except util.ClassNotFound: return None def _color_with_pygments(self, codeblock, lexer, **formatter_opts): import pygments import pygments.formatters class HtmlCodeFormatter(pygments.formatters.HtmlFormatter): def _wrap_code(self, inner): """A function for use in a Pygments Formatter which wraps in <code> tags. """ yield 0, "<code>" for tup in inner: yield tup yield 0, "</code>" def wrap(self, source, outfile): """Return the source with a code, pre, and div.""" return self._wrap_div(self._wrap_pre(self._wrap_code(source))) formatter_opts.setdefault("cssclass", "codehilite") formatter = HtmlCodeFormatter(**formatter_opts) return pygments.highlight(codeblock, lexer, formatter) def _code_block_sub(self, match, is_fenced_code_block=False): lexer_name = None if is_fenced_code_block: lexer_name = match.group(1) if lexer_name: formatter_opts = self.extras['fenced-code-blocks'] or {} codeblock = match.group(2) codeblock = codeblock[:-1] # drop one trailing newline else: codeblock = match.group(1) codeblock = self._outdent(codeblock) codeblock = self._detab(codeblock) codeblock = codeblock.lstrip('\n') # trim leading newlines codeblock = codeblock.rstrip() # trim trailing whitespace # Note: "code-color" extra is DEPRECATED. if "code-color" in self.extras and codeblock.startswith(":::"): lexer_name, rest = codeblock.split('\n', 1) lexer_name = lexer_name[3:].strip() codeblock = rest.lstrip("\n") # Remove lexer declaration line. formatter_opts = self.extras['code-color'] or {} if lexer_name: lexer = self._get_pygments_lexer(lexer_name) if lexer: colored = self._color_with_pygments(codeblock, lexer, **formatter_opts) return "\n\n%s\n\n" % colored codeblock = self._encode_code(codeblock) pre_class_str = self._html_class_str_from_tag("pre") code_class_str = self._html_class_str_from_tag("code") return "\n\n<pre%s><code%s>%s\n</code></pre>\n\n" % ( pre_class_str, code_class_str, codeblock) def _html_class_str_from_tag(self, tag): """Get the appropriate ' class="..."' string (note the leading space), if any, for the given tag. """ if "html-classes" not in self.extras: return "" try: html_classes_from_tag = self.extras["html-classes"] except TypeError: return "" else: if tag in html_classes_from_tag: return ' class="%s"' % html_classes_from_tag[tag] return "" def _do_code_blocks(self, text): """Process Markdown `<pre><code>` blocks.""" code_block_re = re.compile(r''' (?:\n\n|\A\n?) ( # $1 = the code block -- one or more lines, starting with a space/tab (?: (?:[ ]{%d} | \t) # Lines must start with a tab or a tab-width of spaces .*\n+ )+ ) ((?=^[ ]{0,%d}\S)|\Z) # Lookahead for non-space at line-start, or end of doc ''' % (self.tab_width, self.tab_width), re.M | re.X) return code_block_re.sub(self._code_block_sub, text) _fenced_code_block_re = re.compile(r''' (?:\n\n|\A\n?) ^```([\w+-]+)?[ \t]*\n # opening fence, $1 = optional lang (.*?) # $2 = code block content ^```[ \t]*\n # closing fence ''', re.M | re.X | re.S) def _fenced_code_block_sub(self, match): return self._code_block_sub(match, is_fenced_code_block=True); def _do_fenced_code_blocks(self, text): """Process ```-fenced unindented code blocks ('fenced-code-blocks' extra).""" return self._fenced_code_block_re.sub(self._fenced_code_block_sub, text) # Rules for a code span: # - backslash escapes are not interpreted in a code span # - to include one or or a run of more backticks the delimiters must # be a longer run of backticks # - cannot start or end a code span with a backtick; pad with a # space and that space will be removed in the emitted HTML # See `test/tm-cases/escapes.text` for a number of edge-case # examples. _code_span_re = re.compile(r''' (?<!\\) (`+) # \1 = Opening run of ` (?!`) # See Note A test/tm-cases/escapes.text (.+?) # \2 = The code block (?<!`) \1 # Matching closer (?!`) ''', re.X | re.S) def _code_span_sub(self, match): c = match.group(2).strip(" \t") c = self._encode_code(c) return "<code>%s</code>" % c def _do_code_spans(self, text): # * Backtick quotes are used for <code></code> spans. # # * You can use multiple backticks as the delimiters if you want to # include literal backticks in the code span. So, this input: # # Just type ``foo `bar` baz`` at the prompt. # # Will translate to: # # <p>Just type <code>foo `bar` baz</code> at the prompt.</p> # # There's no arbitrary limit to the number of backticks you # can use as delimters. If you need three consecutive backticks # in your code, use four for delimiters, etc. # # * You can use spaces to get literal backticks at the edges: # # ... type `` `bar` `` ... # # Turns to: # # ... type <code>`bar`</code> ... return self._code_span_re.sub(self._code_span_sub, text) def _encode_code(self, text): """Encode/escape certain characters inside Markdown code runs. The point is that in code, these characters are literals, and lose their special Markdown meanings. """ replacements = [ # Encode all ampersands; HTML entities are not # entities within a Markdown code span. ('&', '&amp;'), # Do the angle bracket song and dance: ('<', '&lt;'), ('>', '&gt;'), ] for before, after in replacements: text = text.replace(before, after) hashed = _hash_text(text) self._escape_table[text] = hashed return hashed _strong_re = re.compile(r"(\*\*|__)(?=\S)(.+?[*_]*)(?<=\S)\1", re.S) _em_re = re.compile(r"(\*|_)(?=\S)(.+?)(?<=\S)\1", re.S) _code_friendly_strong_re = re.compile(r"\*\*(?=\S)(.+?[*_]*)(?<=\S)\*\*", re.S) _code_friendly_em_re = re.compile(r"\*(?=\S)(.+?)(?<=\S)\*", re.S) def _do_italics_and_bold(self, text): # <strong> must go first: if "code-friendly" in self.extras: text = self._code_friendly_strong_re.sub(r"<strong>\1</strong>", text) text = self._code_friendly_em_re.sub(r"<em>\1</em>", text) else: text = self._strong_re.sub(r"<strong>\2</strong>", text) text = self._em_re.sub(r"<em>\2</em>", text) return text # "smarty-pants" extra: Very liberal in interpreting a single prime as an # apostrophe; e.g. ignores the fact that "round", "bout", "twer", and # "twixt" can be written without an initial apostrophe. This is fine because # using scare quotes (single quotation marks) is rare. _apostrophe_year_re = re.compile(r"'(\d\d)(?=(\s|,|;|\.|\?|!|$))") _contractions = ["tis", "twas", "twer", "neath", "o", "n", "round", "bout", "twixt", "nuff", "fraid", "sup"] def _do_smart_contractions(self, text): text = self._apostrophe_year_re.sub(r"&#8217;\1", text) for c in self._contractions: text = text.replace("'%s" % c, "&#8217;%s" % c) text = text.replace("'%s" % c.capitalize(), "&#8217;%s" % c.capitalize()) return text # Substitute double-quotes before single-quotes. _opening_single_quote_re = re.compile(r"(?<!\S)'(?=\S)") _opening_double_quote_re = re.compile(r'(?<!\S)"(?=\S)') _closing_single_quote_re = re.compile(r"(?<=\S)'") _closing_double_quote_re = re.compile(r'(?<=\S)"(?=(\s|,|;|\.|\?|!|$))') def _do_smart_punctuation(self, text): """Fancifies 'single quotes', "double quotes", and apostrophes. Converts --, ---, and ... into en dashes, em dashes, and ellipses. Inspiration is: <http://daringfireball.net/projects/smartypants/> See "test/tm-cases/smarty_pants.text" for a full discussion of the support here and <http://code.google.com/p/python-markdown2/issues/detail?id=42> for a discussion of some diversion from the original SmartyPants. """ if "'" in text: # guard for perf text = self._do_smart_contractions(text) text = self._opening_single_quote_re.sub("&#8216;", text) text = self._closing_single_quote_re.sub("&#8217;", text) if '"' in text: # guard for perf text = self._opening_double_quote_re.sub("&#8220;", text) text = self._closing_double_quote_re.sub("&#8221;", text) text = text.replace("---", "&#8212;") text = text.replace("--", "&#8211;") text = text.replace("...", "&#8230;") text = text.replace(" . . . ", "&#8230;") text = text.replace(". . .", "&#8230;") return text _block_quote_re = re.compile(r''' ( # Wrap whole match in \1 ( ^[ \t]*>[ \t]? # '>' at the start of a line .+\n # rest of the first line (.+\n)* # subsequent consecutive lines \n* # blanks )+ ) ''', re.M | re.X) _bq_one_level_re = re.compile('^[ \t]*>[ \t]?', re.M); _html_pre_block_re = re.compile(r'(\s*<pre>.+?</pre>)', re.S) def _dedent_two_spaces_sub(self, match): return re.sub(r'(?m)^ ', '', match.group(1)) def _block_quote_sub(self, match): bq = match.group(1) bq = self._bq_one_level_re.sub('', bq) # trim one level of quoting bq = self._ws_only_line_re.sub('', bq) # trim whitespace-only lines bq = self._run_block_gamut(bq) # recurse bq = re.sub('(?m)^', ' ', bq) # These leading spaces screw with <pre> content, so we need to fix that: bq = self._html_pre_block_re.sub(self._dedent_two_spaces_sub, bq) return "<blockquote>\n%s\n</blockquote>\n\n" % bq def _do_block_quotes(self, text): if '>' not in text: return text return self._block_quote_re.sub(self._block_quote_sub, text) def _form_paragraphs(self, text): # Strip leading and trailing lines: text = text.strip('\n') # Wrap <p> tags. grafs = [] for i, graf in enumerate(re.split(r"\n{2,}", text)): if graf in self.html_blocks: # Unhashify HTML blocks grafs.append(self.html_blocks[graf]) else: cuddled_list = None if "cuddled-lists" in self.extras: # Need to put back trailing '\n' for `_list_item_re` # match at the end of the paragraph. li = self._list_item_re.search(graf + '\n') # Two of the same list marker in this paragraph: a likely # candidate for a list cuddled to preceding paragraph # text (issue 33). Note the `[-1]` is a quick way to # consider numeric bullets (e.g. "1." and "2.") to be # equal. if (li and len(li.group(2)) <= 3 and li.group("next_marker") and li.group("marker")[-1] == li.group("next_marker")[-1]): start = li.start() cuddled_list = self._do_lists(graf[start:]).rstrip("\n") assert cuddled_list.startswith("<ul>") or cuddled_list.startswith("<ol>") graf = graf[:start] # Wrap <p> tags. graf = self._run_span_gamut(graf) grafs.append("<p>" + graf.lstrip(" \t") + "</p>") if cuddled_list: grafs.append(cuddled_list) return "\n\n".join(grafs) def _add_footnotes(self, text): if self.footnotes: footer = [ '<div class="footnotes">', '<hr' + self.empty_element_suffix, '<ol>', ] for i, id in enumerate(self.footnote_ids): if i != 0: footer.append('') footer.append('<li id="fn-%s">' % id) footer.append(self._run_block_gamut(self.footnotes[id])) backlink = ('<a href="#fnref-%s" ' 'class="footnoteBackLink" ' 'title="Jump back to footnote %d in the text.">' '&#8617;</a>' % (id, i+1)) if footer[-1].endswith("</p>"): footer[-1] = footer[-1][:-len("</p>")] \ + '&nbsp;' + backlink + "</p>" else: footer.append("\n<p>%s</p>" % backlink) footer.append('</li>') footer.append('</ol>') footer.append('</div>') return text + '\n\n' + '\n'.join(footer) else: return text # Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin: # http://bumppo.net/projects/amputator/ _ampersand_re = re.compile(r'&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)') _naked_lt_re = re.compile(r'<(?![a-z/?\$!])', re.I) _naked_gt_re = re.compile(r'''(?<![a-z0-9?!/'"-])>''', re.I) def _encode_amps_and_angles(self, text): # Smart processing for ampersands and angle brackets that need # to be encoded. text = self._ampersand_re.sub('&amp;', text) # Encode naked <'s text = self._naked_lt_re.sub('&lt;', text) # Encode naked >'s # Note: Other markdown implementations (e.g. Markdown.pl, PHP # Markdown) don't do this. text = self._naked_gt_re.sub('&gt;', text) return text def _encode_backslash_escapes(self, text): for ch, escape in list(self._escape_table.items()): text = text.replace("\\"+ch, escape) return text _auto_link_re = re.compile(r'<((https?|ftp):[^\'">\s]+)>', re.I) def _auto_link_sub(self, match): g1 = match.group(1) return '<a href="%s">%s</a>' % (g1, g1) _auto_email_link_re = re.compile(r""" < (?:mailto:)? ( [-.\w]+ \@ [-\w]+(\.[-\w]+)*\.[a-z]+ ) > """, re.I | re.X | re.U) def _auto_email_link_sub(self, match): return self._encode_email_address( self._unescape_special_chars(match.group(1))) def _do_auto_links(self, text): text = self._auto_link_re.sub(self._auto_link_sub, text) text = self._auto_email_link_re.sub(self._auto_email_link_sub, text) return text def _encode_email_address(self, addr): # Input: an email address, e.g. "foo@example.com" # # Output: the email address as a mailto link, with each character # of the address encoded as either a decimal or hex entity, in # the hopes of foiling most address harvesting spam bots. E.g.: # # <a href="&#x6D;&#97;&#105;&#108;&#x74;&#111;:&#102;&#111;&#111;&#64;&#101; # x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;">&#102;&#111;&#111; # &#64;&#101;x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;</a> # # Based on a filter by Matthew Wickline, posted to the BBEdit-Talk # mailing list: <http://tinyurl.com/yu7ue> chars = [_xml_encode_email_char_at_random(ch) for ch in "mailto:" + addr] # Strip the mailto: from the visible part. addr = '<a href="%s">%s</a>' \ % (''.join(chars), ''.join(chars[7:])) return addr def _do_link_patterns(self, text): """Caveat emptor: there isn't much guarding against link patterns being formed inside other standard Markdown links, e.g. inside a [link def][like this]. Dev Notes: *Could* consider prefixing regexes with a negative lookbehind assertion to attempt to guard against this. """ link_from_hash = {} for regex, repl in self.link_patterns: replacements = [] for match in regex.finditer(text): if hasattr(repl, "__call__"): href = repl(match) else: href = match.expand(repl) replacements.append((match.span(), href)) for (start, end), href in reversed(replacements): escaped_href = ( href.replace('"', '&quot;') # b/c of attr quote # To avoid markdown <em> and <strong>: .replace('*', self._escape_table['*']) .replace('_', self._escape_table['_'])) link = '<a href="%s">%s</a>' % (escaped_href, text[start:end]) hash = _hash_text(link) link_from_hash[hash] = link text = text[:start] + hash + text[end:] for hash, link in list(link_from_hash.items()): text = text.replace(hash, link) return text def _unescape_special_chars(self, text): # Swap back in all the special characters we've hidden. for ch, hash in list(self._escape_table.items()): text = text.replace(hash, ch) return text def _outdent(self, text): # Remove one level of line-leading tabs or spaces return self._outdent_re.sub('', text) class MarkdownWithExtras(Markdown): """A markdowner class that enables most extras: - footnotes - code-color (only has effect if 'pygments' Python module on path) These are not included: - pyshell (specific to Python-related documenting) - code-friendly (because it *disables* part of the syntax) - link-patterns (because you need to specify some actual link-patterns anyway) """ extras = ["footnotes", "code-color"] #---- internal support functions class UnicodeWithAttrs(unicode): """A subclass of unicode used for the return value of conversion to possibly attach some attributes. E.g. the "toc_html" attribute when the "toc" extra is used. """ metadata = None _toc = None def toc_html(self): """Return the HTML for the current TOC. This expects the `_toc` attribute to have been set on this instance. """ if self._toc is None: return None def indent(): return ' ' * (len(h_stack) - 1) lines = [] h_stack = [0] # stack of header-level numbers for level, id, name in self._toc: if level > h_stack[-1]: lines.append("%s<ul>" % indent()) h_stack.append(level) elif level == h_stack[-1]: lines[-1] += "</li>" else: while level < h_stack[-1]: h_stack.pop() if not lines[-1].endswith("</li>"): lines[-1] += "</li>" lines.append("%s</ul></li>" % indent()) lines.append('%s<li><a href="#%s">%s</a>' % ( indent(), id, name)) while len(h_stack) > 1: h_stack.pop() if not lines[-1].endswith("</li>"): lines[-1] += "</li>" lines.append("%s</ul>" % indent()) return '\n'.join(lines) + '\n' toc_html = property(toc_html) ## {{{ http://code.activestate.com/recipes/577257/ (r1) import re char_map = {u'À': 'A', u'Á': 'A', u'Â': 'A', u'Ã': 'A', u'Ä': 'Ae', u'Å': 'A', u'Æ': 'A', u'Ā': 'A', u'Ą': 'A', u'Ă': 'A', u'Ç': 'C', u'Ć': 'C', u'Č': 'C', u'Ĉ': 'C', u'Ċ': 'C', u'Ď': 'D', u'Đ': 'D', u'È': 'E', u'É': 'E', u'Ê': 'E', u'Ë': 'E', u'Ē': 'E', u'Ę': 'E', u'Ě': 'E', u'Ĕ': 'E', u'Ė': 'E', u'Ĝ': 'G', u'Ğ': 'G', u'Ġ': 'G', u'Ģ': 'G', u'Ĥ': 'H', u'Ħ': 'H', u'Ì': 'I', u'Í': 'I', u'Î': 'I', u'Ï': 'I', u'Ī': 'I', u'Ĩ': 'I', u'Ĭ': 'I', u'Į': 'I', u'İ': 'I', u'IJ': 'IJ', u'Ĵ': 'J', u'Ķ': 'K', u'Ľ': 'K', u'Ĺ': 'K', u'Ļ': 'K', u'Ŀ': 'K', u'Ł': 'L', u'Ñ': 'N', u'Ń': 'N', u'Ň': 'N', u'Ņ': 'N', u'Ŋ': 'N', u'Ò': 'O', u'Ó': 'O', u'Ô': 'O', u'Õ': 'O', u'Ö': 'Oe', u'Ø': 'O', u'Ō': 'O', u'Ő': 'O', u'Ŏ': 'O', u'Œ': 'OE', u'Ŕ': 'R', u'Ř': 'R', u'Ŗ': 'R', u'Ś': 'S', u'Ş': 'S', u'Ŝ': 'S', u'Ș': 'S', u'Š': 'S', u'Ť': 'T', u'Ţ': 'T', u'Ŧ': 'T', u'Ț': 'T', u'Ù': 'U', u'Ú': 'U', u'Û': 'U', u'Ü': 'Ue', u'Ū': 'U', u'Ů': 'U', u'Ű': 'U', u'Ŭ': 'U', u'Ũ': 'U', u'Ų': 'U', u'Ŵ': 'W', u'Ŷ': 'Y', u'Ÿ': 'Y', u'Ý': 'Y', u'Ź': 'Z', u'Ż': 'Z', u'Ž': 'Z', u'à': 'a', u'á': 'a', u'â': 'a', u'ã': 'a', u'ä': 'ae', u'ā': 'a', u'ą': 'a', u'ă': 'a', u'å': 'a', u'æ': 'ae', u'ç': 'c', u'ć': 'c', u'č': 'c', u'ĉ': 'c', u'ċ': 'c', u'ď': 'd', u'đ': 'd', u'è': 'e', u'é': 'e', u'ê': 'e', u'ë': 'e', u'ē': 'e', u'ę': 'e', u'ě': 'e', u'ĕ': 'e', u'ė': 'e', u'ƒ': 'f', u'ĝ': 'g', u'ğ': 'g', u'ġ': 'g', u'ģ': 'g', u'ĥ': 'h', u'ħ': 'h', u'ì': 'i', u'í': 'i', u'î': 'i', u'ï': 'i', u'ī': 'i', u'ĩ': 'i', u'ĭ': 'i', u'į': 'i', u'ı': 'i', u'ij': 'ij', u'ĵ': 'j', u'ķ': 'k', u'ĸ': 'k', u'ł': 'l', u'ľ': 'l', u'ĺ': 'l', u'ļ': 'l', u'ŀ': 'l', u'ñ': 'n', u'ń': 'n', u'ň': 'n', u'ņ': 'n', u'ʼn': 'n', u'ŋ': 'n', u'ò': 'o', u'ó': 'o', u'ô': 'o', u'õ': 'o', u'ö': 'oe', u'ø': 'o', u'ō': 'o', u'ő': 'o', u'ŏ': 'o', u'œ': 'oe', u'ŕ': 'r', u'ř': 'r', u'ŗ': 'r', u'ś': 's', u'š': 's', u'ť': 't', u'ù': 'u', u'ú': 'u', u'û': 'u', u'ü': 'ue', u'ū': 'u', u'ů': 'u', u'ű': 'u', u'ŭ': 'u', u'ũ': 'u', u'ų': 'u', u'ŵ': 'w', u'ÿ': 'y', u'ý': 'y', u'ŷ': 'y', u'ż': 'z', u'ź': 'z', u'ž': 'z', u'ß': 'ss', u'ſ': 'ss', u'Α': 'A', u'Ά': 'A', u'Ἀ': 'A', u'Ἁ': 'A', u'Ἂ': 'A', u'Ἃ': 'A', u'Ἄ': 'A', u'Ἅ': 'A', u'Ἆ': 'A', u'Ἇ': 'A', u'ᾈ': 'A', u'ᾉ': 'A', u'ᾊ': 'A', u'ᾋ': 'A', u'ᾌ': 'A', u'ᾍ': 'A', u'ᾎ': 'A', u'ᾏ': 'A', u'Ᾰ': 'A', u'Ᾱ': 'A', u'Ὰ': 'A', u'Ά': 'A', u'ᾼ': 'A', u'Β': 'B', u'Γ': 'G', u'Δ': 'D', u'Ε': 'E', u'Έ': 'E', u'Ἐ': 'E', u'Ἑ': 'E', u'Ἒ': 'E', u'Ἓ': 'E', u'Ἔ': 'E', u'Ἕ': 'E', u'Έ': 'E', u'Ὲ': 'E', u'Ζ': 'Z', u'Η': 'I', u'Ή': 'I', u'Ἠ': 'I', u'Ἡ': 'I', u'Ἢ': 'I', u'Ἣ': 'I', u'Ἤ': 'I', u'Ἥ': 'I', u'Ἦ': 'I', u'Ἧ': 'I', u'ᾘ': 'I', u'ᾙ': 'I', u'ᾚ': 'I', u'ᾛ': 'I', u'ᾜ': 'I', u'ᾝ': 'I', u'ᾞ': 'I', u'ᾟ': 'I', u'Ὴ': 'I', u'Ή': 'I', u'ῌ': 'I', u'Θ': 'TH', u'Ι': 'I', u'Ί': 'I', u'Ϊ': 'I', u'Ἰ': 'I', u'Ἱ': 'I', u'Ἲ': 'I', u'Ἳ': 'I', u'Ἴ': 'I', u'Ἵ': 'I', u'Ἶ': 'I', u'Ἷ': 'I', u'Ῐ': 'I', u'Ῑ': 'I', u'Ὶ': 'I', u'Ί': 'I', u'Κ': 'K', u'Λ': 'L', u'Μ': 'M', u'Ν': 'N', u'Ξ': 'KS', u'Ο': 'O', u'Ό': 'O', u'Ὀ': 'O', u'Ὁ': 'O', u'Ὂ': 'O', u'Ὃ': 'O', u'Ὄ': 'O', u'Ὅ': 'O', u'Ὸ': 'O', u'Ό': 'O', u'Π': 'P', u'Ρ': 'R', u'Ῥ': 'R', u'Σ': 'S', u'Τ': 'T', u'Υ': 'Y', u'Ύ': 'Y', u'Ϋ': 'Y', u'Ὑ': 'Y', u'Ὓ': 'Y', u'Ὕ': 'Y', u'Ὗ': 'Y', u'Ῠ': 'Y', u'Ῡ': 'Y', u'Ὺ': 'Y', u'Ύ': 'Y', u'Φ': 'F', u'Χ': 'X', u'Ψ': 'PS', u'Ω': 'O', u'Ώ': 'O', u'Ὠ': 'O', u'Ὡ': 'O', u'Ὢ': 'O', u'Ὣ': 'O', u'Ὤ': 'O', u'Ὥ': 'O', u'Ὦ': 'O', u'Ὧ': 'O', u'ᾨ': 'O', u'ᾩ': 'O', u'ᾪ': 'O', u'ᾫ': 'O', u'ᾬ': 'O', u'ᾭ': 'O', u'ᾮ': 'O', u'ᾯ': 'O', u'Ὼ': 'O', u'Ώ': 'O', u'ῼ': 'O', u'α': 'a', u'ά': 'a', u'ἀ': 'a', u'ἁ': 'a', u'ἂ': 'a', u'ἃ': 'a', u'ἄ': 'a', u'ἅ': 'a', u'ἆ': 'a', u'ἇ': 'a', u'ᾀ': 'a', u'ᾁ': 'a', u'ᾂ': 'a', u'ᾃ': 'a', u'ᾄ': 'a', u'ᾅ': 'a', u'ᾆ': 'a', u'ᾇ': 'a', u'ὰ': 'a', u'ά': 'a', u'ᾰ': 'a', u'ᾱ': 'a', u'ᾲ': 'a', u'ᾳ': 'a', u'ᾴ': 'a', u'ᾶ': 'a', u'ᾷ': 'a', u'β': 'b', u'γ': 'g', u'δ': 'd', u'ε': 'e', u'έ': 'e', u'ἐ': 'e', u'ἑ': 'e', u'ἒ': 'e', u'ἓ': 'e', u'ἔ': 'e', u'ἕ': 'e', u'ὲ': 'e', u'έ': 'e', u'ζ': 'z', u'η': 'i', u'ή': 'i', u'ἠ': 'i', u'ἡ': 'i', u'ἢ': 'i', u'ἣ': 'i', u'ἤ': 'i', u'ἥ': 'i', u'ἦ': 'i', u'ἧ': 'i', u'ᾐ': 'i', u'ᾑ': 'i', u'ᾒ': 'i', u'ᾓ': 'i', u'ᾔ': 'i', u'ᾕ': 'i', u'ᾖ': 'i', u'ᾗ': 'i', u'ὴ': 'i', u'ή': 'i', u'ῂ': 'i', u'ῃ': 'i', u'ῄ': 'i', u'ῆ': 'i', u'ῇ': 'i', u'θ': 'th', u'ι': 'i', u'ί': 'i', u'ϊ': 'i', u'ΐ': 'i', u'ἰ': 'i', u'ἱ': 'i', u'ἲ': 'i', u'ἳ': 'i', u'ἴ': 'i', u'ἵ': 'i', u'ἶ': 'i', u'ἷ': 'i', u'ὶ': 'i', u'ί': 'i', u'ῐ': 'i', u'ῑ': 'i', u'ῒ': 'i', u'ΐ': 'i', u'ῖ': 'i', u'ῗ': 'i', u'κ': 'k', u'λ': 'l', u'μ': 'm', u'ν': 'n', u'ξ': 'ks', u'ο': 'o', u'ό': 'o', u'ὀ': 'o', u'ὁ': 'o', u'ὂ': 'o', u'ὃ': 'o', u'ὄ': 'o', u'ὅ': 'o', u'ὸ': 'o', u'ό': 'o', u'π': 'p', u'ρ': 'r', u'ῤ': 'r', u'ῥ': 'r', u'σ': 's', u'ς': 's', u'τ': 't', u'υ': 'y', u'ύ': 'y', u'ϋ': 'y', u'ΰ': 'y', u'ὐ': 'y', u'ὑ': 'y', u'ὒ': 'y', u'ὓ': 'y', u'ὔ': 'y', u'ὕ': 'y', u'ὖ': 'y', u'ὗ': 'y', u'ὺ': 'y', u'ύ': 'y', u'ῠ': 'y', u'ῡ': 'y', u'ῢ': 'y', u'ΰ': 'y', u'ῦ': 'y', u'ῧ': 'y', u'φ': 'f', u'χ': 'x', u'ψ': 'ps', u'ω': 'o', u'ώ': 'o', u'ὠ': 'o', u'ὡ': 'o', u'ὢ': 'o', u'ὣ': 'o', u'ὤ': 'o', u'ὥ': 'o', u'ὦ': 'o', u'ὧ': 'o', u'ᾠ': 'o', u'ᾡ': 'o', u'ᾢ': 'o', u'ᾣ': 'o', u'ᾤ': 'o', u'ᾥ': 'o', u'ᾦ': 'o', u'ᾧ': 'o', u'ὼ': 'o', u'ώ': 'o', u'ῲ': 'o', u'ῳ': 'o', u'ῴ': 'o', u'ῶ': 'o', u'ῷ': 'o', u'¨': '', u'΅': '', u'᾿': '', u'῾': '', u'῍': '', u'῝': '', u'῎': '', u'῞': '', u'῏': '', u'῟': '', u'῀': '', u'῁': '', u'΄': '', u'΅': '', u'`': '', u'῭': '', u'ͺ': '', u'᾽': '', u'А': 'A', u'Б': 'B', u'В': 'V', u'Г': 'G', u'Д': 'D', u'Е': 'E', u'Ё': 'YO', u'Ж': 'ZH', u'З': 'Z', u'И': 'I', u'Й': 'J', u'К': 'K', u'Л': 'L', u'М': 'M', u'Н': 'N', u'О': 'O', u'П': 'P', u'Р': 'R', u'С': 'S', u'Т': 'T', u'У': 'U', u'Ф': 'F', u'Х': 'H', u'Ц': 'TS', u'Ч': 'CH', u'Ш': 'SH', u'Щ': 'SCH', u'Ы': 'YI', u'Э': 'E', u'Ю': 'YU', u'Я': 'YA', u'а': 'A', u'б': 'B', u'в': 'V', u'г': 'G', u'д': 'D', u'е': 'E', u'ё': 'YO', u'ж': 'ZH', u'з': 'Z', u'и': 'I', u'й': 'J', u'к': 'K', u'л': 'L', u'м': 'M', u'н': 'N', u'о': 'O', u'п': 'P', u'р': 'R', u'с': 'S', u'т': 'T', u'у': 'U', u'ф': 'F', u'х': 'H', u'ц': 'TS', u'ч': 'CH', u'ш': 'SH', u'щ': 'SCH', u'ы': 'YI', u'э': 'E', u'ю': 'YU', u'я': 'YA', u'Ъ': '', u'ъ': '', u'Ь': '', u'ь': '', u'ð': 'd', u'Ð': 'D', u'þ': 'th', u'Þ': 'TH',u'ა': 'a', u'ბ': 'b', u'გ': 'g', u'დ': 'd', u'ე': 'e', u'ვ': 'v', u'ზ': 'z', u'თ': 't', u'ი': 'i', u'კ': 'k', u'ლ': 'l', u'მ': 'm', u'ნ': 'n', u'ო': 'o', u'პ': 'p', u'ჟ': 'zh', u'რ': 'r', u'ს': 's', u'ტ': 't', u'უ': 'u', u'ფ': 'p', u'ქ': 'k', u'ღ': 'gh', u'ყ': 'q', u'შ': 'sh', u'ჩ': 'ch', u'ც': 'ts', u'ძ': 'dz', u'წ': 'ts', u'ჭ': 'ch', u'ხ': 'kh', u'ჯ': 'j', u'ჰ': 'h' } def replace_char(m): char = m.group() if char_map.has_key(char): return char_map[char] else: return char _punct_re = re.compile(r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.]+') ## end of http://code.activestate.com/recipes/577257/ }}} # From http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52549 def _curry(*args, **kwargs): function, args = args[0], args[1:] def result(*rest, **kwrest): combined = kwargs.copy() combined.update(kwrest) return function(*args + rest, **combined) return result # Recipe: regex_from_encoded_pattern (1.0) def _regex_from_encoded_pattern(s): """'foo' -> re.compile(re.escape('foo')) '/foo/' -> re.compile('foo') '/foo/i' -> re.compile('foo', re.I) """ if s.startswith('/') and s.rfind('/') != 0: # Parse it: /PATTERN/FLAGS idx = s.rfind('/') pattern, flags_str = s[1:idx], s[idx+1:] flag_from_char = { "i": re.IGNORECASE, "l": re.LOCALE, "s": re.DOTALL, "m": re.MULTILINE, "u": re.UNICODE, } flags = 0 for char in flags_str: try: flags |= flag_from_char[char] except KeyError: raise ValueError("unsupported regex flag: '%s' in '%s' " "(must be one of '%s')" % (char, s, ''.join(list(flag_from_char.keys())))) return re.compile(s[1:idx], flags) else: # not an encoded regex return re.compile(re.escape(s)) # Recipe: dedent (0.1.2) def _dedentlines(lines, tabsize=8, skip_first_line=False): """_dedentlines(lines, tabsize=8, skip_first_line=False) -> dedented lines "lines" is a list of lines to dedent. "tabsize" is the tab width to use for indent width calculations. "skip_first_line" is a boolean indicating if the first line should be skipped for calculating the indent width and for dedenting. This is sometimes useful for docstrings and similar. Same as dedent() except operates on a sequence of lines. Note: the lines list is modified **in-place**. """ DEBUG = False if DEBUG: print("dedent: dedent(..., tabsize=%d, skip_first_line=%r)"\ % (tabsize, skip_first_line)) indents = [] margin = None for i, line in enumerate(lines): if i == 0 and skip_first_line: continue indent = 0 for ch in line: if ch == ' ': indent += 1 elif ch == '\t': indent += tabsize - (indent % tabsize) elif ch in '\r\n': continue # skip all-whitespace lines else: break else: continue # skip all-whitespace lines if DEBUG: print("dedent: indent=%d: %r" % (indent, line)) if margin is None: margin = indent else: margin = min(margin, indent) if DEBUG: print("dedent: margin=%r" % margin) if margin is not None and margin > 0: for i, line in enumerate(lines): if i == 0 and skip_first_line: continue removed = 0 for j, ch in enumerate(line): if ch == ' ': removed += 1 elif ch == '\t': removed += tabsize - (removed % tabsize) elif ch in '\r\n': if DEBUG: print("dedent: %r: EOL -> strip up to EOL" % line) lines[i] = lines[i][j:] break else: raise ValueError("unexpected non-whitespace char %r in " "line %r while removing %d-space margin" % (ch, line, margin)) if DEBUG: print("dedent: %r: %r -> removed %d/%d"\ % (line, ch, removed, margin)) if removed == margin: lines[i] = lines[i][j+1:] break elif removed > margin: lines[i] = ' '*(removed-margin) + lines[i][j+1:] break else: if removed: lines[i] = lines[i][removed:] return lines def _dedent(text, tabsize=8, skip_first_line=False): """_dedent(text, tabsize=8, skip_first_line=False) -> dedented text "text" is the text to dedent. "tabsize" is the tab width to use for indent width calculations. "skip_first_line" is a boolean indicating if the first line should be skipped for calculating the indent width and for dedenting. This is sometimes useful for docstrings and similar. textwrap.dedent(s), but don't expand tabs to spaces """ lines = text.splitlines(1) _dedentlines(lines, tabsize=tabsize, skip_first_line=skip_first_line) return ''.join(lines) class _memoized(object): """Decorator that caches a function's return value each time it is called. If called later with the same arguments, the cached value is returned, and not re-evaluated. http://wiki.python.org/moin/PythonDecoratorLibrary """ def __init__(self, func): self.func = func self.cache = {} def __call__(self, *args): try: return self.cache[args] except KeyError: self.cache[args] = value = self.func(*args) return value except TypeError: # uncachable -- for instance, passing a list as an argument. # Better to not cache than to blow up entirely. return self.func(*args) def __repr__(self): """Return the function's docstring.""" return self.func.__doc__ def _xml_oneliner_re_from_tab_width(tab_width): """Standalone XML processing instruction regex.""" return re.compile(r""" (?: (?<=\n\n) # Starting after a blank line | # or \A\n? # the beginning of the doc ) ( # save in $1 [ ]{0,%d} (?: <\?\w+\b\s+.*?\?> # XML processing instruction | <\w+:\w+\b\s+.*?/> # namespaced single tag ) [ \t]* (?=\n{2,}|\Z) # followed by a blank line or end of document ) """ % (tab_width - 1), re.X) _xml_oneliner_re_from_tab_width = _memoized(_xml_oneliner_re_from_tab_width) def _hr_tag_re_from_tab_width(tab_width): return re.compile(r""" (?: (?<=\n\n) # Starting after a blank line | # or \A\n? # the beginning of the doc ) ( # save in \1 [ ]{0,%d} <(hr) # start tag = \2 \b # word break ([^<>])*? # /?> # the matching end tag [ \t]* (?=\n{2,}|\Z) # followed by a blank line or end of document ) """ % (tab_width - 1), re.X) _hr_tag_re_from_tab_width = _memoized(_hr_tag_re_from_tab_width) def _xml_escape_attr(attr, skip_single_quote=True): """Escape the given string for use in an HTML/XML tag attribute. By default this doesn't bother with escaping `'` to `&#39;`, presuming that the tag attribute is surrounded by double quotes. """ escaped = (attr .replace('&', '&amp;') .replace('"', '&quot;') .replace('<', '&lt;') .replace('>', '&gt;')) if not skip_single_quote: escaped = escaped.replace("'", "&#39;") return escaped def _xml_encode_email_char_at_random(ch): r = random() # Roughly 10% raw, 45% hex, 45% dec. # '@' *must* be encoded. I [John Gruber] insist. # Issue 26: '_' must be encoded. if r > 0.9 and ch not in "@_": return ch elif r < 0.45: # The [1:] is to drop leading '0': 0x63 -> x63 return '&#%s;' % hex(ord(ch))[1:] else: return '&#%s;' % ord(ch) #---- mainline class _NoReflowFormatter(optparse.IndentedHelpFormatter): """An optparse formatter that does NOT reflow the description.""" def format_description(self, description): return description or "" def _test(): import doctest doctest.testmod() def main(argv=None): if argv is None: argv = sys.argv if not logging.root.handlers: logging.basicConfig() usage = "usage: %prog [PATHS...]" version = "%prog "+__version__ parser = optparse.OptionParser(prog="markdown2", usage=usage, version=version, description=cmdln_desc, formatter=_NoReflowFormatter()) parser.add_option("-v", "--verbose", dest="log_level", action="store_const", const=logging.DEBUG, help="more verbose output") parser.add_option("--encoding", help="specify encoding of text content") parser.add_option("--html4tags", action="store_true", default=False, help="use HTML 4 style for empty element tags") parser.add_option("-s", "--safe", metavar="MODE", dest="safe_mode", help="sanitize literal HTML: 'escape' escapes " "HTML meta chars, 'replace' replaces with an " "[HTML_REMOVED] note") parser.add_option("-x", "--extras", action="append", help="Turn on specific extra features (not part of " "the core Markdown spec). See above.") parser.add_option("--use-file-vars", help="Look for and use Emacs-style 'markdown-extras' " "file var to turn on extras. See " "<https://github.com/trentm/python-markdown2/wiki/Extras>") parser.add_option("--link-patterns-file", help="path to a link pattern file") parser.add_option("--self-test", action="store_true", help="run internal self-tests (some doctests)") parser.add_option("--compare", action="store_true", help="run against Markdown.pl as well (for testing)") parser.set_defaults(log_level=logging.INFO, compare=False, encoding="utf-8", safe_mode=None, use_file_vars=False) opts, paths = parser.parse_args() log.setLevel(opts.log_level) if opts.self_test: return _test() if opts.extras: extras = {} for s in opts.extras: splitter = re.compile("[,;: ]+") for e in splitter.split(s): if '=' in e: ename, earg = e.split('=', 1) try: earg = int(earg) except ValueError: pass else: ename, earg = e, None extras[ename] = earg else: extras = None if opts.link_patterns_file: link_patterns = [] f = open(opts.link_patterns_file) try: for i, line in enumerate(f.readlines()): if not line.strip(): continue if line.lstrip().startswith("#"): continue try: pat, href = line.rstrip().rsplit(None, 1) except ValueError: raise MarkdownError("%s:%d: invalid link pattern line: %r" % (opts.link_patterns_file, i+1, line)) link_patterns.append( (_regex_from_encoded_pattern(pat), href)) finally: f.close() else: link_patterns = None from os.path import join, dirname, abspath, exists markdown_pl = join(dirname(dirname(abspath(__file__))), "test", "Markdown.pl") if not paths: paths = ['-'] for path in paths: if path == '-': text = sys.stdin.read() else: fp = codecs.open(path, 'r', opts.encoding) text = fp.read() fp.close() if opts.compare: from subprocess import Popen, PIPE print("==== Markdown.pl ====") p = Popen('perl %s' % markdown_pl, shell=True, stdin=PIPE, stdout=PIPE, close_fds=True) p.stdin.write(text.encode('utf-8')) p.stdin.close() perl_html = p.stdout.read().decode('utf-8') if py3: sys.stdout.write(perl_html) else: sys.stdout.write(perl_html.encode( sys.stdout.encoding or "utf-8", 'xmlcharrefreplace')) print("==== markdown2.py ====") html = markdown(text, html4tags=opts.html4tags, safe_mode=opts.safe_mode, extras=extras, link_patterns=link_patterns, use_file_vars=opts.use_file_vars) if py3: sys.stdout.write(html) else: sys.stdout.write(html.encode( sys.stdout.encoding or "utf-8", 'xmlcharrefreplace')) if extras and "toc" in extras: log.debug("toc_html: " + html.toc_html.encode(sys.stdout.encoding or "utf-8", 'xmlcharrefreplace')) if opts.compare: test_dir = join(dirname(dirname(abspath(__file__))), "test") if exists(join(test_dir, "test_markdown2.py")): sys.path.insert(0, test_dir) from test_markdown2 import norm_html_from_html norm_html = norm_html_from_html(html) norm_perl_html = norm_html_from_html(perl_html) else: norm_html = html norm_perl_html = perl_html print("==== match? %r ====" % (norm_perl_html == norm_html)) template_html = u'''<!DOCTYPE html> <!-- Backdoc is a tool for backbone-like documentation generation. Backdoc main goal is to help to generate one page documentation from one markdown source file. https://github.com/chibisov/backdoc --> <html lang="ru"> <head> <meta charset="UTF-8"/> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> <meta name="HandheldFriendly" content="true" /> <title><!-- title --></title> <!-- Bootstrap --> <style type="text/css"> /*! * Bootstrap v3.0.0 * * Copyright 2013 Twitter, Inc * Licensed under the Apache License v2.0 * http://www.apache.org/licenses/LICENSE-2.0 * * Designed and built with all the love in the world by @mdo and @fat. *//*! normalize.css v2.1.0 | MIT License | git.io/normalize */ article,aside,details,figcaption,figure,footer,header,hgroup,main,nav,section,summary{display:block}audio,canvas,video{display:inline-block}audio:not([controls]){display:none;height:0}[hidden]{display:none}html{font-family:sans-serif;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%}body{margin:0}a:focus{outline:thin dotted}a:active,a:hover{outline:0}h1{margin:.67em 0;font-size:2em}abbr[title]{border-bottom:1px dotted}b,strong{font-weight:bold}dfn{font-style:italic}hr{height:0;-moz-box-sizing:content-box;box-sizing:content-box}mark{color:#000;background:#ff0}code,kbd,pre,samp{font-family:monospace,serif;font-size:1em}pre{white-space:pre-wrap}q{quotes:"\201C" "\201D" "\2018" "\2019"}small{font-size:80%}sub,sup{position:relative;font-size:75%;line-height:0;vertical-align:baseline}sup{top:-0.5em}sub{bottom:-0.25em}img{border:0}svg:not(:root){overflow:hidden}figure{margin:0}fieldset{padding:.35em .625em .75em;margin:0 2px;border:1px solid #c0c0c0}legend{padding:0;border:0}button,input,select,textarea{margin:0;font-family:inherit;font-size:100%}button,input{line-height:normal}button,select{text-transform:none}button,html input[type="button"],input[type="reset"],input[type="submit"]{cursor:pointer;-webkit-appearance:button}button[disabled],html input[disabled]{cursor:default}input[type="checkbox"],input[type="radio"]{padding:0;box-sizing:border-box}input[type="search"]{-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;-webkit-appearance:textfield}input[type="search"]::-webkit-search-cancel-button,input[type="search"]::-webkit-search-decoration{-webkit-appearance:none}button::-moz-focus-inner,input::-moz-focus-inner{padding:0;border:0}textarea{overflow:auto;vertical-align:top}table{border-collapse:collapse;border-spacing:0}@media print{*{color:#000!important;text-shadow:none!important;background:transparent!important;box-shadow:none!important}a,a:visited{text-decoration:underline}a[href]:after{content:" (" attr(href) ")"}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100%!important}@page{margin:2cm .5cm}p,h2,h3{orphans:3;widows:3}h2,h3{page-break-after:avoid}.navbar{display:none}.table td,.table th{background-color:#fff!important}.btn>.caret,.dropup>.btn>.caret{border-top-color:#000!important}.label{border:1px solid #000}.table{border-collapse:collapse!important}.table-bordered th,.table-bordered td{border:1px solid #ddd!important}}*{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}html{font-size:62.5%;-webkit-tap-highlight-color:rgba(0,0,0,0)}body{font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px;line-height:1.428571429;color:#333;background-color:#fff}input,button,select,textarea{font-family:inherit;font-size:inherit;line-height:inherit}a{color:#428bca;text-decoration:none}a:hover,a:focus{color:#2a6496;text-decoration:underline}a:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}img{vertical-align:middle}.img-responsive{display:inline-block;height:auto;max-width:100%}.img-rounded{border-radius:6px}.img-circle{border-radius:500px}hr{margin-top:20px;margin-bottom:20px;border:0;border-top:1px solid #eee}p{margin:0 0 10px}.lead{margin-bottom:20px;font-size:16.099999999999998px;font-weight:200;line-height:1.4}@media(min-width:768px){.lead{font-size:21px}}small{font-size:85%}cite{font-style:normal}.text-muted{color:#999}.text-primary{color:#428bca}.text-warning{color:#c09853}.text-danger{color:#b94a48}.text-success{color:#468847}.text-info{color:#3a87ad}.text-left{text-align:left}.text-right{text-align:right}.text-center{text-align:center}h1,h2,h3,h4,h5,h6,.h1,.h2,.h3,.h4,.h5,.h6{font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-weight:500;line-height:1.1}h1 small,h2 small,h3 small,h4 small,h5 small,h6 small,.h1 small,.h2 small,.h3 small,.h4 small,.h5 small,.h6 small{font-weight:normal;line-height:1;color:#999}h1,h2,h3{margin-top:20px;margin-bottom:10px}h4,h5,h6{margin-top:10px;margin-bottom:10px}h1,.h1{font-size:38px}h2,.h2{font-size:32px}h3,.h3{font-size:24px}h4,.h4{font-size:18px}h5,.h5{font-size:14px}h6,.h6{font-size:12px}h1 small,.h1 small{font-size:24px}h2 small,.h2 small{font-size:18px}h3 small,.h3 small,h4 small,.h4 small{font-size:14px}.page-header{padding-bottom:9px;margin:40px 0 20px;border-bottom:1px solid #eee}ul,ol{margin-top:0;margin-bottom:10px}ul ul,ol ul,ul ol,ol ol{margin-bottom:0}.list-unstyled{padding-left:0;list-style:none}.list-inline{padding-left:0;list-style:none}.list-inline>li{display:inline-block;padding-right:5px;padding-left:5px}dl{margin-bottom:20px}dt,dd{line-height:1.428571429}dt{font-weight:bold}dd{margin-left:0}.dl-horizontal dt{float:left;width:160px;overflow:hidden;clear:left;text-align:right;text-overflow:ellipsis;white-space:nowrap}.dl-horizontal dd{margin-left:180px}.dl-horizontal dd:before,.dl-horizontal dd:after{display:table;content:" "}.dl-horizontal dd:after{clear:both}.dl-horizontal dd:before,.dl-horizontal dd:after{display:table;content:" "}.dl-horizontal dd:after{clear:both}abbr[title],abbr[data-original-title]{cursor:help;border-bottom:1px dotted #999}abbr.initialism{font-size:90%;text-transform:uppercase}blockquote{padding:10px 20px;margin:0 0 20px;border-left:5px solid #eee}blockquote p{font-size:17.5px;font-weight:300;line-height:1.25}blockquote p:last-child{margin-bottom:0}blockquote small{display:block;line-height:1.428571429;color:#999}blockquote small:before{content:'\2014 \00A0'}blockquote.pull-right{float:right;padding-right:15px;padding-left:0;border-right:5px solid #eee;border-left:0}blockquote.pull-right p,blockquote.pull-right small{text-align:right}blockquote.pull-right small:before{content:''}blockquote.pull-right small:after{content:'\00A0 \2014'}q:before,q:after,blockquote:before,blockquote:after{content:""}address{display:block;margin-bottom:20px;font-style:normal;line-height:1.428571429}code,pre{font-family:Monaco,Menlo,Consolas,"Courier New",monospace}code{padding:2px 4px;font-size:90%;color:#c7254e;white-space:nowrap;background-color:#f9f2f4;border-radius:4px}pre{display:block;padding:9.5px;margin:0 0 10px;font-size:13px;line-height:1.428571429;color:#333;word-break:break-all;word-wrap:break-word;background-color:#f5f5f5;border:1px solid #ccc;border-radius:4px}pre.prettyprint{margin-bottom:20px}pre code{padding:0;color:inherit;white-space:pre-wrap;background-color:transparent;border:0}.pre-scrollable{max-height:340px;overflow-y:scroll}.container{margin-right:auto;margin-left:auto}.container:before,.container:after{display:table;content:" "}.container:after{clear:both}.container:before,.container:after{display:table;content:" "}.container:after{clear:both}.row:before,.row:after{display:table;content:" "}.row:after{clear:both}.row:before,.row:after{display:table;content:" "}.row:after{clear:both}@media(min-width:768px){.row{margin-right:-15px;margin-left:-15px}}.row .row{margin-right:-15px;margin-left:-15px}.col-1,.col-2,.col-3,.col-4,.col-5,.col-6,.col-7,.col-8,.col-9,.col-10,.col-11,.col-12,.col-sm-1,.col-sm-2,.col-sm-3,.col-sm-4,.col-sm-5,.col-sm-6,.col-sm-7,.col-sm-8,.col-sm-9,.col-sm-10,.col-sm-11,.col-sm-12,.col-lg-1,.col-lg-2,.col-lg-3,.col-lg-4,.col-lg-5,.col-lg-6,.col-lg-7,.col-lg-8,.col-lg-9,.col-lg-10,.col-lg-11,.col-lg-12{position:relative;min-height:1px;padding-right:15px;padding-left:15px}.col-1,.col-2,.col-3,.col-4,.col-5,.col-6,.col-7,.col-8,.col-9,.col-10,.col-11,.col-12{float:left}.col-1{width:8.333333333333332%}.col-2{width:16.666666666666664%}.col-3{width:25%}.col-4{width:33.33333333333333%}.col-5{width:41.66666666666667%}.col-6{width:50%}.col-7{width:58.333333333333336%}.col-8{width:66.66666666666666%}.col-9{width:75%}.col-10{width:83.33333333333334%}.col-11{width:91.66666666666666%}.col-12{width:100%}@media(min-width:768px){.container{max-width:728px}.col-sm-1,.col-sm-2,.col-sm-3,.col-sm-4,.col-sm-5,.col-sm-6,.col-sm-7,.col-sm-8,.col-sm-9,.col-sm-10,.col-sm-11,.col-sm-12{float:left}.col-sm-1{width:8.333333333333332%}.col-sm-2{width:16.666666666666664%}.col-sm-3{width:25%}.col-sm-4{width:33.33333333333333%}.col-sm-5{width:41.66666666666667%}.col-sm-6{width:50%}.col-sm-7{width:58.333333333333336%}.col-sm-8{width:66.66666666666666%}.col-sm-9{width:75%}.col-sm-10{width:83.33333333333334%}.col-sm-11{width:91.66666666666666%}.col-sm-12{width:100%}.col-push-1{left:8.333333333333332%}.col-push-2{left:16.666666666666664%}.col-push-3{left:25%}.col-push-4{left:33.33333333333333%}.col-push-5{left:41.66666666666667%}.col-push-6{left:50%}.col-push-7{left:58.333333333333336%}.col-push-8{left:66.66666666666666%}.col-push-9{left:75%}.col-push-10{left:83.33333333333334%}.col-push-11{left:91.66666666666666%}.col-pull-1{right:8.333333333333332%}.col-pull-2{right:16.666666666666664%}.col-pull-3{right:25%}.col-pull-4{right:33.33333333333333%}.col-pull-5{right:41.66666666666667%}.col-pull-6{right:50%}.col-pull-7{right:58.333333333333336%}.col-pull-8{right:66.66666666666666%}.col-pull-9{right:75%}.col-pull-10{right:83.33333333333334%}.col-pull-11{right:91.66666666666666%}}@media(min-width:992px){.container{max-width:940px}.col-lg-1,.col-lg-2,.col-lg-3,.col-lg-4,.col-lg-5,.col-lg-6,.col-lg-7,.col-lg-8,.col-lg-9,.col-lg-10,.col-lg-11,.col-lg-12{float:left}.col-lg-1{width:8.333333333333332%}.col-lg-2{width:16.666666666666664%}.col-lg-3{width:25%}.col-lg-4{width:33.33333333333333%}.col-lg-5{width:41.66666666666667%}.col-lg-6{width:50%}.col-lg-7{width:58.333333333333336%}.col-lg-8{width:66.66666666666666%}.col-lg-9{width:75%}.col-lg-10{width:83.33333333333334%}.col-lg-11{width:91.66666666666666%}.col-lg-12{width:100%}.col-offset-1{margin-left:8.333333333333332%}.col-offset-2{margin-left:16.666666666666664%}.col-offset-3{margin-left:25%}.col-offset-4{margin-left:33.33333333333333%}.col-offset-5{margin-left:41.66666666666667%}.col-offset-6{margin-left:50%}.col-offset-7{margin-left:58.333333333333336%}.col-offset-8{margin-left:66.66666666666666%}.col-offset-9{margin-left:75%}.col-offset-10{margin-left:83.33333333333334%}.col-offset-11{margin-left:91.66666666666666%}}@media(min-width:1200px){.container{max-width:1170px}}table{max-width:100%;background-color:transparent}th{text-align:left}.table{width:100%;margin-bottom:20px}.table thead>tr>th,.table tbody>tr>th,.table tfoot>tr>th,.table thead>tr>td,.table tbody>tr>td,.table tfoot>tr>td{padding:8px;line-height:1.428571429;vertical-align:top;border-top:1px solid #ddd}.table thead>tr>th{vertical-align:bottom}.table caption+thead tr:first-child th,.table colgroup+thead tr:first-child th,.table thead:first-child tr:first-child th,.table caption+thead tr:first-child td,.table colgroup+thead tr:first-child td,.table thead:first-child tr:first-child td{border-top:0}.table tbody+tbody{border-top:2px solid #ddd}.table .table{background-color:#fff}.table-condensed thead>tr>th,.table-condensed tbody>tr>th,.table-condensed tfoot>tr>th,.table-condensed thead>tr>td,.table-condensed tbody>tr>td,.table-condensed tfoot>tr>td{padding:5px}.table-bordered{border:1px solid #ddd}.table-bordered>thead>tr>th,.table-bordered>tbody>tr>th,.table-bordered>tfoot>tr>th,.table-bordered>thead>tr>td,.table-bordered>tbody>tr>td,.table-bordered>tfoot>tr>td{border:1px solid #ddd}.table-striped>tbody>tr:nth-child(odd)>td,.table-striped>tbody>tr:nth-child(odd)>th{background-color:#f9f9f9}.table-hover>tbody>tr:hover>td,.table-hover>tbody>tr:hover>th{background-color:#f5f5f5}table col[class^="col-"]{display:table-column;float:none}table td[class^="col-"],table th[class^="col-"]{display:table-cell;float:none}.table>thead>tr>td.active,.table>tbody>tr>td.active,.table>tfoot>tr>td.active,.table>thead>tr>th.active,.table>tbody>tr>th.active,.table>tfoot>tr>th.active,.table>thead>tr.active>td,.table>tbody>tr.active>td,.table>tfoot>tr.active>td,.table>thead>tr.active>th,.table>tbody>tr.active>th,.table>tfoot>tr.active>th{background-color:#f5f5f5}.table>thead>tr>td.success,.table>tbody>tr>td.success,.table>tfoot>tr>td.success,.table>thead>tr>th.success,.table>tbody>tr>th.success,.table>tfoot>tr>th.success,.table>thead>tr.success>td,.table>tbody>tr.success>td,.table>tfoot>tr.success>td,.table>thead>tr.success>th,.table>tbody>tr.success>th,.table>tfoot>tr.success>th{background-color:#dff0d8;border-color:#d6e9c6}.table>thead>tr>td.danger,.table>tbody>tr>td.danger,.table>tfoot>tr>td.danger,.table>thead>tr>th.danger,.table>tbody>tr>th.danger,.table>tfoot>tr>th.danger,.table>thead>tr.danger>td,.table>tbody>tr.danger>td,.table>tfoot>tr.danger>td,.table>thead>tr.danger>th,.table>tbody>tr.danger>th,.table>tfoot>tr.danger>th{background-color:#f2dede;border-color:#eed3d7}.table>thead>tr>td.warning,.table>tbody>tr>td.warning,.table>tfoot>tr>td.warning,.table>thead>tr>th.warning,.table>tbody>tr>th.warning,.table>tfoot>tr>th.warning,.table>thead>tr.warning>td,.table>tbody>tr.warning>td,.table>tfoot>tr.warning>td,.table>thead>tr.warning>th,.table>tbody>tr.warning>th,.table>tfoot>tr.warning>th{background-color:#fcf8e3;border-color:#fbeed5}.table-hover>tbody>tr>td.success:hover,.table-hover>tbody>tr>th.success:hover,.table-hover>tbody>tr.success:hover>td{background-color:#d0e9c6;border-color:#c9e2b3}.table-hover>tbody>tr>td.danger:hover,.table-hover>tbody>tr>th.danger:hover,.table-hover>tbody>tr.danger:hover>td{background-color:#ebcccc;border-color:#e6c1c7}.table-hover>tbody>tr>td.warning:hover,.table-hover>tbody>tr>th.warning:hover,.table-hover>tbody>tr.warning:hover>td{background-color:#faf2cc;border-color:#f8e5be}fieldset{padding:0;margin:0;border:0}legend{display:block;width:100%;padding:0;margin-bottom:20px;font-size:21px;line-height:inherit;color:#333;border:0;border-bottom:1px solid #e5e5e5}label{display:inline-block;margin-bottom:5px;font-weight:bold}input[type="search"]{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}input[type="radio"],input[type="checkbox"]{margin:4px 0 0;margin-top:1px \9;line-height:normal}input[type="file"]{display:block}select[multiple],select[size]{height:auto}select optgroup{font-family:inherit;font-size:inherit;font-style:inherit}input[type="file"]:focus,input[type="radio"]:focus,input[type="checkbox"]:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}input[type="number"]::-webkit-outer-spin-button,input[type="number"]::-webkit-inner-spin-button{height:auto}.form-control:-moz-placeholder{color:#999}.form-control::-moz-placeholder{color:#999}.form-control:-ms-input-placeholder{color:#999}.form-control::-webkit-input-placeholder{color:#999}.form-control{display:block;width:100%;height:38px;padding:8px 12px;font-size:14px;line-height:1.428571429;color:#555;vertical-align:middle;background-color:#fff;border:1px solid #ccc;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);-webkit-transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s;transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s}.form-control:focus{border-color:rgba(82,168,236,0.8);outline:0;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6)}.form-control[disabled],.form-control[readonly],fieldset[disabled] .form-control{cursor:not-allowed;background-color:#eee}textarea.form-control{height:auto}.form-group{margin-bottom:15px}.radio,.checkbox{display:block;min-height:20px;padding-left:20px;margin-top:10px;margin-bottom:10px;vertical-align:middle}.radio label,.checkbox label{display:inline;margin-bottom:0;font-weight:normal;cursor:pointer}.radio input[type="radio"],.radio-inline input[type="radio"],.checkbox input[type="checkbox"],.checkbox-inline input[type="checkbox"]{float:left;margin-left:-20px}.radio+.radio,.checkbox+.checkbox{margin-top:-5px}.radio-inline,.checkbox-inline{display:inline-block;padding-left:20px;margin-bottom:0;font-weight:normal;vertical-align:middle;cursor:pointer}.radio-inline+.radio-inline,.checkbox-inline+.checkbox-inline{margin-top:0;margin-left:10px}.form-control.input-large{height:56px;padding:14px 16px;font-size:18px;border-radius:6px}.form-control.input-small{height:30px;padding:5px 10px;font-size:12px;border-radius:3px}select.input-large{height:56px;line-height:56px}select.input-small{height:30px;line-height:30px}.has-warning .help-block,.has-warning .control-label{color:#c09853}.has-warning .form-control{padding-right:32px;border-color:#c09853;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075)}.has-warning .form-control:focus{border-color:#a47e3c;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #dbc59e;box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #dbc59e}.has-warning .input-group-addon{color:#c09853;background-color:#fcf8e3;border-color:#c09853}.has-error .help-block,.has-error .control-label{color:#b94a48}.has-error .form-control{padding-right:32px;border-color:#b94a48;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075)}.has-error .form-control:focus{border-color:#953b39;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #d59392;box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #d59392}.has-error .input-group-addon{color:#b94a48;background-color:#f2dede;border-color:#b94a48}.has-success .help-block,.has-success .control-label{color:#468847}.has-success .form-control{padding-right:32px;border-color:#468847;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075)}.has-success .form-control:focus{border-color:#356635;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7aba7b;box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7aba7b}.has-success .input-group-addon{color:#468847;background-color:#dff0d8;border-color:#468847}.help-block{display:block;margin-top:5px;margin-bottom:10px;color:#737373}.input-group{display:table;border-collapse:separate}.input-group.col{float:none;padding-right:0;padding-left:0}.input-group .form-control{width:100%;margin-bottom:0}.input-group-addon,.input-group-btn,.input-group .form-control{display:table-cell}.input-group-addon:not(:first-child):not(:last-child),.input-group-btn:not(:first-child):not(:last-child),.input-group .form-control:not(:first-child):not(:last-child){border-radius:0}.input-group-addon,.input-group-btn{width:1%;white-space:nowrap;vertical-align:middle}.input-group-addon{padding:8px 12px;font-size:14px;font-weight:normal;line-height:1.428571429;text-align:center;background-color:#eee;border:1px solid #ccc;border-radius:4px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.input-group-addon.input-small{padding:5px 10px;font-size:12px;border-radius:3px}.input-group-addon.input-large{padding:14px 16px;font-size:18px;border-radius:6px}.input-group .form-control:first-child,.input-group-addon:first-child,.input-group-btn:first-child>.btn,.input-group-btn:first-child>.dropdown-toggle,.input-group-btn:last-child>.btn:not(:last-child):not(.dropdown-toggle){border-top-right-radius:0;border-bottom-right-radius:0}.input-group-addon:first-child{border-right:0}.input-group .form-control:last-child,.input-group-addon:last-child,.input-group-btn:last-child>.btn,.input-group-btn:last-child>.dropdown-toggle,.input-group-btn:first-child>.btn:not(:first-child){border-bottom-left-radius:0;border-top-left-radius:0}.input-group-addon:last-child{border-left:0}.input-group-btn{position:relative;white-space:nowrap}.input-group-btn>.btn{position:relative}.input-group-btn>.btn+.btn{margin-left:-4px}.input-group-btn>.btn:hover,.input-group-btn>.btn:active{z-index:2}.form-inline .form-control,.form-inline .radio,.form-inline .checkbox{display:inline-block}.form-inline .radio,.form-inline .checkbox{margin-top:0;margin-bottom:0}.form-horizontal .control-label{padding-top:6px}.form-horizontal .form-group:before,.form-horizontal .form-group:after{display:table;content:" "}.form-horizontal .form-group:after{clear:both}.form-horizontal .form-group:before,.form-horizontal .form-group:after{display:table;content:" "}.form-horizontal .form-group:after{clear:both}@media(min-width:768px){.form-horizontal .form-group{margin-right:-15px;margin-left:-15px}}.form-horizontal .form-group .row{margin-right:-15px;margin-left:-15px}@media(min-width:768px){.form-horizontal .control-label{text-align:right}}.btn{display:inline-block;padding:8px 12px;margin-bottom:0;font-size:14px;font-weight:500;line-height:1.428571429;text-align:center;white-space:nowrap;vertical-align:middle;cursor:pointer;border:1px solid transparent;border-radius:4px}.btn:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn:hover,.btn:focus{color:#fff;text-decoration:none}.btn:active,.btn.active{outline:0;-webkit-box-shadow:inset 0 3px 5px rgba(0,0,0,0.125);box-shadow:inset 0 3px 5px rgba(0,0,0,0.125)}.btn.disabled,.btn[disabled],fieldset[disabled] .btn{pointer-events:none;cursor:default;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;box-shadow:none}.btn-default{color:#fff;background-color:#474949;border-color:#474949}.btn-default:hover,.btn-default:focus,.btn-default:active,.btn-default.active{background-color:#3a3c3c;border-color:#2e2f2f}.btn-default.disabled,.btn-default[disabled],fieldset[disabled] .btn-default,.btn-default.disabled:hover,.btn-default[disabled]:hover,fieldset[disabled] .btn-default:hover,.btn-default.disabled:focus,.btn-default[disabled]:focus,fieldset[disabled] .btn-default:focus,.btn-default.disabled:active,.btn-default[disabled]:active,fieldset[disabled] .btn-default:active,.btn-default.disabled.active,.btn-default[disabled].active,fieldset[disabled] .btn-default.active{background-color:#474949;border-color:#474949}.btn-primary{color:#fff;background-color:#428bca;border-color:#428bca}.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active{background-color:#357ebd;border-color:#3071a9}.btn-primary.disabled,.btn-primary[disabled],fieldset[disabled] .btn-primary,.btn-primary.disabled:hover,.btn-primary[disabled]:hover,fieldset[disabled] .btn-primary:hover,.btn-primary.disabled:focus,.btn-primary[disabled]:focus,fieldset[disabled] .btn-primary:focus,.btn-primary.disabled:active,.btn-primary[disabled]:active,fieldset[disabled] .btn-primary:active,.btn-primary.disabled.active,.btn-primary[disabled].active,fieldset[disabled] .btn-primary.active{background-color:#428bca;border-color:#428bca}.btn-warning{color:#fff;background-color:#f0ad4e;border-color:#f0ad4e}.btn-warning:hover,.btn-warning:focus,.btn-warning:active,.btn-warning.active{background-color:#eea236;border-color:#ec971f}.btn-warning.disabled,.btn-warning[disabled],fieldset[disabled] .btn-warning,.btn-warning.disabled:hover,.btn-warning[disabled]:hover,fieldset[disabled] .btn-warning:hover,.btn-warning.disabled:focus,.btn-warning[disabled]:focus,fieldset[disabled] .btn-warning:focus,.btn-warning.disabled:active,.btn-warning[disabled]:active,fieldset[disabled] .btn-warning:active,.btn-warning.disabled.active,.btn-warning[disabled].active,fieldset[disabled] .btn-warning.active{background-color:#f0ad4e;border-color:#f0ad4e}.btn-danger{color:#fff;background-color:#d9534f;border-color:#d9534f}.btn-danger:hover,.btn-danger:focus,.btn-danger:active,.btn-danger.active{background-color:#d43f3a;border-color:#c9302c}.btn-danger.disabled,.btn-danger[disabled],fieldset[disabled] .btn-danger,.btn-danger.disabled:hover,.btn-danger[disabled]:hover,fieldset[disabled] .btn-danger:hover,.btn-danger.disabled:focus,.btn-danger[disabled]:focus,fieldset[disabled] .btn-danger:focus,.btn-danger.disabled:active,.btn-danger[disabled]:active,fieldset[disabled] .btn-danger:active,.btn-danger.disabled.active,.btn-danger[disabled].active,fieldset[disabled] .btn-danger.active{background-color:#d9534f;border-color:#d9534f}.btn-success{color:#fff;background-color:#5cb85c;border-color:#5cb85c}.btn-success:hover,.btn-success:focus,.btn-success:active,.btn-success.active{background-color:#4cae4c;border-color:#449d44}.btn-success.disabled,.btn-success[disabled],fieldset[disabled] .btn-success,.btn-success.disabled:hover,.btn-success[disabled]:hover,fieldset[disabled] .btn-success:hover,.btn-success.disabled:focus,.btn-success[disabled]:focus,fieldset[disabled] .btn-success:focus,.btn-success.disabled:active,.btn-success[disabled]:active,fieldset[disabled] .btn-success:active,.btn-success.disabled.active,.btn-success[disabled].active,fieldset[disabled] .btn-success.active{background-color:#5cb85c;border-color:#5cb85c}.btn-info{color:#fff;background-color:#5bc0de;border-color:#5bc0de}.btn-info:hover,.btn-info:focus,.btn-info:active,.btn-info.active{background-color:#46b8da;border-color:#31b0d5}.btn-info.disabled,.btn-info[disabled],fieldset[disabled] .btn-info,.btn-info.disabled:hover,.btn-info[disabled]:hover,fieldset[disabled] .btn-info:hover,.btn-info.disabled:focus,.btn-info[disabled]:focus,fieldset[disabled] .btn-info:focus,.btn-info.disabled:active,.btn-info[disabled]:active,fieldset[disabled] .btn-info:active,.btn-info.disabled.active,.btn-info[disabled].active,fieldset[disabled] .btn-info.active{background-color:#5bc0de;border-color:#5bc0de}.btn-link{font-weight:normal;color:#428bca;cursor:pointer;border-radius:0}.btn-link,.btn-link:active,.btn-link[disabled],fieldset[disabled] .btn-link{background-color:transparent;-webkit-box-shadow:none;box-shadow:none}.btn-link,.btn-link:hover,.btn-link:focus,.btn-link:active{border-color:transparent}.btn-link:hover,.btn-link:focus{color:#2a6496;text-decoration:underline;background-color:transparent}.btn-link[disabled]:hover,fieldset[disabled] .btn-link:hover,.btn-link[disabled]:focus,fieldset[disabled] .btn-link:focus{color:#333;text-decoration:none}.btn-large{padding:14px 16px;font-size:18px;border-radius:6px}.btn-small{padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}.btn-block{display:block;width:100%;padding-right:0;padding-left:0}.btn-block+.btn-block{margin-top:5px}input[type="submit"].btn-block,input[type="reset"].btn-block,input[type="button"].btn-block{width:100%}.fade{opacity:0;-webkit-transition:opacity .15s linear;transition:opacity .15s linear}.fade.in{opacity:1}.collapse{display:none}.collapse.in{display:block}.collapsing{position:relative;height:0;overflow:hidden;-webkit-transition:height .35s ease;transition:height .35s ease}.caret{display:inline-block;width:0;height:0;margin-left:2px;vertical-align:middle;border-top:4px solid #000;border-right:4px solid transparent;border-left:4px solid transparent;content:""}.dropdown-menu{position:absolute;top:100%;left:0;z-index:1000;display:none;float:left;min-width:160px;padding:5px 0;margin:2px 0 0;list-style:none;background-color:#fff;border:1px solid #ccc;border:1px solid rgba(0,0,0,0.15);border-radius:4px;-webkit-box-shadow:0 6px 12px rgba(0,0,0,0.175);box-shadow:0 6px 12px rgba(0,0,0,0.175);background-clip:padding-box}.dropdown-menu.pull-right{right:0;left:auto}.dropdown-menu .divider{height:1px;margin:9px 0;overflow:hidden;background-color:#e5e5e5}.dropdown-menu>li>a{display:block;padding:3px 20px;clear:both;font-weight:normal;line-height:1.428571429;color:#333;white-space:nowrap}.dropdown-menu>li>a:hover,.dropdown-menu>li>a:focus{color:#fff;text-decoration:none;background-color:#357ebd;background-image:-webkit-gradient(linear,left 0,left 100%,from(#428bca),to(#357ebd));background-image:-webkit-linear-gradient(top,#428bca,0%,#357ebd,100%);background-image:-moz-linear-gradient(top,#428bca 0,#357ebd 100%);background-image:linear-gradient(to bottom,#428bca 0,#357ebd 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff428bca',endColorstr='#ff357ebd',GradientType=0)}.dropdown-menu>.active>a,.dropdown-menu>.active>a:hover,.dropdown-menu>.active>a:focus{color:#fff;text-decoration:none;background-color:#357ebd;background-image:-webkit-gradient(linear,left 0,left 100%,from(#428bca),to(#357ebd));background-image:-webkit-linear-gradient(top,#428bca,0%,#357ebd,100%);background-image:-moz-linear-gradient(top,#428bca 0,#357ebd 100%);background-image:linear-gradient(to bottom,#428bca 0,#357ebd 100%);background-repeat:repeat-x;outline:0;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff428bca',endColorstr='#ff357ebd',GradientType=0)}.dropdown-menu>.disabled>a,.dropdown-menu>.disabled>a:hover,.dropdown-menu>.disabled>a:focus{color:#999}.dropdown-menu>.disabled>a:hover,.dropdown-menu>.disabled>a:focus{text-decoration:none;cursor:not-allowed;background-color:transparent;background-image:none;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.open>.dropdown-menu{display:block}.open>a{outline:0}.dropdown-header{display:block;padding:3px 20px;font-size:12px;line-height:1.428571429;color:#999}.dropdown-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:990}.pull-right>.dropdown-menu{right:0;left:auto}.dropup .caret,.navbar-fixed-bottom .dropdown .caret{border-top:0;border-bottom:4px solid #000;content:""}.dropup .dropdown-menu,.navbar-fixed-bottom .dropdown .dropdown-menu{top:auto;bottom:100%;margin-bottom:1px}.list-group{padding-left:0;margin-bottom:20px;background-color:#fff}.list-group-item{position:relative;display:block;padding:10px 30px 10px 15px;margin-bottom:-1px;border:1px solid #ddd}.list-group-item:first-child{border-top-right-radius:4px;border-top-left-radius:4px}.list-group-item:last-child{margin-bottom:0;border-bottom-right-radius:4px;border-bottom-left-radius:4px}.list-group-item>.badge{float:right;margin-right:-15px}.list-group-item-heading{margin-top:0;margin-bottom:5px}.list-group-item-text{margin-bottom:0;line-height:1.3}a.list-group-item .list-group-item-heading{color:#333}a.list-group-item .list-group-item-text{color:#555}a.list-group-item:hover,a.list-group-item:focus{text-decoration:none;background-color:#f5f5f5}a.list-group-item.active{z-index:2;color:#fff;background-color:#428bca;border-color:#428bca}a.list-group-item.active .list-group-item-heading{color:inherit}a.list-group-item.active .list-group-item-text{color:#e1edf7}.panel{padding:15px;margin-bottom:20px;background-color:#fff;border:1px solid #ddd;border-radius:4px;-webkit-box-shadow:0 1px 1px rgba(0,0,0,0.05);box-shadow:0 1px 1px rgba(0,0,0,0.05)}.panel-heading{padding:10px 15px;margin:-15px -15px 15px;background-color:#f5f5f5;border-bottom:1px solid #ddd;border-top-right-radius:3px;border-top-left-radius:3px}.panel-title{margin-top:0;margin-bottom:0;font-size:17.5px;font-weight:500}.panel-footer{padding:10px 15px;margin:15px -15px -15px;background-color:#f5f5f5;border-top:1px solid #ddd;border-bottom-right-radius:3px;border-bottom-left-radius:3px}.panel-primary{border-color:#428bca}.panel-primary .panel-heading{color:#fff;background-color:#428bca;border-color:#428bca}.panel-success{border-color:#d6e9c6}.panel-success .panel-heading{color:#468847;background-color:#dff0d8;border-color:#d6e9c6}.panel-warning{border-color:#fbeed5}.panel-warning .panel-heading{color:#c09853;background-color:#fcf8e3;border-color:#fbeed5}.panel-danger{border-color:#eed3d7}.panel-danger .panel-heading{color:#b94a48;background-color:#f2dede;border-color:#eed3d7}.panel-info{border-color:#bce8f1}.panel-info .panel-heading{color:#3a87ad;background-color:#d9edf7;border-color:#bce8f1}.list-group-flush{margin:15px -15px -15px}.list-group-flush .list-group-item{border-width:1px 0}.list-group-flush .list-group-item:first-child{border-top-right-radius:0;border-top-left-radius:0}.list-group-flush .list-group-item:last-child{border-bottom:0}.well{min-height:20px;padding:19px;margin-bottom:20px;background-color:#f5f5f5;border:1px solid #e3e3e3;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.05);box-shadow:inset 0 1px 1px rgba(0,0,0,0.05)}.well blockquote{border-color:#ddd;border-color:rgba(0,0,0,0.15)}.well-large{padding:24px;border-radius:6px}.well-small{padding:9px;border-radius:3px}.close{float:right;font-size:21px;font-weight:bold;line-height:1;color:#000;text-shadow:0 1px 0 #fff;opacity:.2;filter:alpha(opacity=20)}.close:hover,.close:focus{color:#000;text-decoration:none;cursor:pointer;opacity:.5;filter:alpha(opacity=50)}button.close{padding:0;cursor:pointer;background:transparent;border:0;-webkit-appearance:none}.nav{padding-left:0;margin-bottom:0;list-style:none}.nav:before,.nav:after{display:table;content:" "}.nav:after{clear:both}.nav:before,.nav:after{display:table;content:" "}.nav:after{clear:both}.nav>li{position:relative;display:block}.nav>li>a{position:relative;display:block;padding:10px 15px}.nav>li>a:hover,.nav>li>a:focus{text-decoration:none;background-color:#eee}.nav>li.disabled>a{color:#999}.nav>li.disabled>a:hover,.nav>li.disabled>a:focus{color:#999;text-decoration:none;cursor:not-allowed;background-color:transparent}.nav>li+.nav-header{margin-top:9px}.nav.open>a,.nav.open>a:hover,.nav.open>a:focus{color:#fff;background-color:#428bca;border-color:#428bca}.nav.open>a .caret,.nav.open>a:hover .caret,.nav.open>a:focus .caret{border-top-color:#fff;border-bottom-color:#fff}.nav>.pull-right{float:right}.nav .nav-divider{height:1px;margin:9px 0;overflow:hidden;background-color:#e5e5e5}.nav-tabs{border-bottom:1px solid #ddd}.nav-tabs>li{float:left;margin-bottom:-1px}.nav-tabs>li>a{margin-right:2px;line-height:1.428571429;border:1px solid transparent;border-radius:4px 4px 0 0}.nav-tabs>li>a:hover{border-color:#eee}.nav-tabs>li.active>a,.nav-tabs>li.active>a:hover,.nav-tabs>li.active>a:focus{color:#555;cursor:default;background-color:#fff;border:1px solid #ddd;border-bottom-color:transparent}.nav-tabs.nav-justified{width:100%;border-bottom:0}.nav-tabs.nav-justified>li{display:table-cell;float:none;width:1%}.nav-tabs.nav-justified>li>a{text-align:center}.nav-tabs.nav-justified>li>a{margin-right:0;border-bottom:1px solid #ddd}.nav-tabs.nav-justified>.active>a{border-bottom-color:#fff}.nav-pills>li{float:left}.nav-pills>li>a{border-radius:5px}.nav-pills>li+li{margin-left:2px}.nav-pills>li.active>a,.nav-pills>li.active>a:hover,.nav-pills>li.active>a:focus{color:#fff;background-color:#428bca}.nav-stacked>li{float:none}.nav-stacked>li+li>a{margin-top:2px;margin-left:0}.nav-justified{width:100%}.nav-justified>li{display:table-cell;float:none;width:1%}.nav-justified>li>a{text-align:center}.nav-tabs-justified{border-bottom:0}.nav-tabs-justified>li>a{margin-right:0;border-bottom:1px solid #ddd}.nav-tabs-justified>.active>a{border-bottom-color:#fff}.tabbable:before,.tabbable:after{display:table;content:" "}.tabbable:after{clear:both}.tabbable:before,.tabbable:after{display:table;content:" "}.tabbable:after{clear:both}.tab-content>.tab-pane,.pill-content>.pill-pane{display:none}.tab-content>.active,.pill-content>.active{display:block}.nav .caret{border-top-color:#428bca;border-bottom-color:#428bca}.nav a:hover .caret{border-top-color:#2a6496;border-bottom-color:#2a6496}.nav-tabs .dropdown-menu{margin-top:-1px;border-top-right-radius:0;border-top-left-radius:0}.navbar{position:relative;min-height:50px;padding-right:15px;padding-left:15px;margin-bottom:20px;background-color:#eee;border-radius:4px}.navbar:before,.navbar:after{display:table;content:" "}.navbar:after{clear:both}.navbar:before,.navbar:after{display:table;content:" "}.navbar:after{clear:both}.navbar-nav{margin-top:10px;margin-bottom:15px}.navbar-nav>li>a{padding-top:15px;padding-bottom:15px;line-height:20px;color:#777;border-radius:4px}.navbar-nav>li>a:hover,.navbar-nav>li>a:focus{color:#333;background-color:transparent}.navbar-nav>.active>a,.navbar-nav>.active>a:hover,.navbar-nav>.active>a:focus{color:#555;background-color:#d5d5d5}.navbar-nav>.disabled>a,.navbar-nav>.disabled>a:hover,.navbar-nav>.disabled>a:focus{color:#ccc;background-color:transparent}.navbar-nav.pull-right{width:100%}.navbar-static-top{border-radius:0}.navbar-fixed-top,.navbar-fixed-bottom{position:fixed;right:0;left:0;z-index:1030;border-radius:0}.navbar-fixed-top{top:0}.navbar-fixed-bottom{bottom:0;margin-bottom:0}.navbar-brand{display:block;max-width:200px;padding:15px 15px;margin-right:auto;margin-left:auto;font-size:18px;font-weight:500;line-height:20px;color:#777;text-align:center}.navbar-brand:hover,.navbar-brand:focus{color:#5e5e5e;text-decoration:none;background-color:transparent}.navbar-toggle{position:absolute;top:9px;right:10px;width:48px;height:32px;padding:8px 12px;background-color:transparent;border:1px solid #ddd;border-radius:4px}.navbar-toggle:hover,.navbar-toggle:focus{background-color:#ddd}.navbar-toggle .icon-bar{display:block;width:22px;height:2px;background-color:#ccc;border-radius:1px}.navbar-toggle .icon-bar+.icon-bar{margin-top:4px}.navbar-form{margin-top:6px;margin-bottom:6px}.navbar-form .form-control,.navbar-form .radio,.navbar-form .checkbox{display:inline-block}.navbar-form .radio,.navbar-form .checkbox{margin-top:0;margin-bottom:0}.navbar-nav>li>.dropdown-menu{margin-top:0;border-top-right-radius:0;border-top-left-radius:0}.navbar-fixed-bottom .navbar-nav>li>.dropdown-menu{border-bottom-right-radius:0;border-bottom-left-radius:0}.navbar-nav>.dropdown>a:hover .caret,.navbar-nav>.dropdown>a:focus .caret{border-top-color:#333;border-bottom-color:#333}.navbar-nav>.open>a,.navbar-nav>.open>a:hover,.navbar-nav>.open>a:focus{color:#555;background-color:#d5d5d5}.navbar-nav>.open>a .caret,.navbar-nav>.open>a:hover .caret,.navbar-nav>.open>a:focus .caret{border-top-color:#555;border-bottom-color:#555}.navbar-nav>.dropdown>a .caret{border-top-color:#777;border-bottom-color:#777}.navbar-nav.pull-right>li>.dropdown-menu,.navbar-nav>li>.dropdown-menu.pull-right{right:0;left:auto}.navbar-inverse{background-color:#222}.navbar-inverse .navbar-brand{color:#999}.navbar-inverse .navbar-brand:hover,.navbar-inverse .navbar-brand:focus{color:#fff;background-color:transparent}.navbar-inverse .navbar-text{color:#999}.navbar-inverse .navbar-nav>li>a{color:#999}.navbar-inverse .navbar-nav>li>a:hover,.navbar-inverse .navbar-nav>li>a:focus{color:#fff;background-color:transparent}.navbar-inverse .navbar-nav>.active>a,.navbar-inverse .navbar-nav>.active>a:hover,.navbar-inverse .navbar-nav>.active>a:focus{color:#fff;background-color:#080808}.navbar-inverse .navbar-nav>.disabled>a,.navbar-inverse .navbar-nav>.disabled>a:hover,.navbar-inverse .navbar-nav>.disabled>a:focus{color:#444;background-color:transparent}.navbar-inverse .navbar-toggle{border-color:#333}.navbar-inverse .navbar-toggle:hover,.navbar-inverse .navbar-toggle:focus{background-color:#333}.navbar-inverse .navbar-toggle .icon-bar{background-color:#fff}.navbar-inverse .navbar-nav>.open>a,.navbar-inverse .navbar-nav>.open>a:hover,.navbar-inverse .navbar-nav>.open>a:focus{color:#fff;background-color:#080808}.navbar-inverse .navbar-nav>.dropdown>a:hover .caret{border-top-color:#fff;border-bottom-color:#fff}.navbar-inverse .navbar-nav>.dropdown>a .caret{border-top-color:#999;border-bottom-color:#999}.navbar-inverse .navbar-nav>.open>a .caret,.navbar-inverse .navbar-nav>.open>a:hover .caret,.navbar-inverse .navbar-nav>.open>a:focus .caret{border-top-color:#fff;border-bottom-color:#fff}@media screen and (min-width:768px){.navbar-brand{float:left;margin-right:5px;margin-left:-15px}.navbar-nav{float:left;margin-top:0;margin-bottom:0}.navbar-nav>li{float:left}.navbar-nav>li>a{border-radius:0}.navbar-nav.pull-right{float:right;width:auto}.navbar-toggle{position:relative;top:auto;left:auto;display:none}.nav-collapse.collapse{display:block!important;height:auto!important;overflow:visible!important}}.navbar-btn{margin-top:6px}.navbar-text{margin-top:15px;margin-bottom:15px}.navbar-link{color:#777}.navbar-link:hover{color:#333}.navbar-inverse .navbar-link{color:#999}.navbar-inverse .navbar-link:hover{color:#fff}.btn .caret{border-top-color:#fff}.dropup .btn .caret{border-bottom-color:#fff}.btn-group,.btn-group-vertical{position:relative;display:inline-block;vertical-align:middle}.btn-group>.btn,.btn-group-vertical>.btn{position:relative;float:left}.btn-group>.btn:hover,.btn-group-vertical>.btn:hover,.btn-group>.btn:active,.btn-group-vertical>.btn:active{z-index:2}.btn-group .btn+.btn{margin-left:-1px}.btn-toolbar:before,.btn-toolbar:after{display:table;content:" "}.btn-toolbar:after{clear:both}.btn-toolbar:before,.btn-toolbar:after{display:table;content:" "}.btn-toolbar:after{clear:both}.btn-toolbar .btn-group{float:left}.btn-toolbar>.btn+.btn,.btn-toolbar>.btn-group+.btn,.btn-toolbar>.btn+.btn-group,.btn-toolbar>.btn-group+.btn-group{margin-left:5px}.btn-group>.btn:not(:first-child):not(:last-child):not(.dropdown-toggle){border-radius:0}.btn-group>.btn:first-child{margin-left:0}.btn-group>.btn:first-child:not(:last-child):not(.dropdown-toggle){border-top-right-radius:0;border-bottom-right-radius:0}.btn-group>.btn:last-child:not(:first-child),.btn-group>.dropdown-toggle:not(:first-child){border-bottom-left-radius:0;border-top-left-radius:0}.btn-group>.btn-group{float:left}.btn-group>.btn-group:not(:first-child):not(:last-child)>.btn{border-radius:0}.btn-group>.btn-group:first-child>.btn:last-child,.btn-group>.btn-group:first-child>.dropdown-toggle{border-top-right-radius:0;border-bottom-right-radius:0}.btn-group>.btn-group:last-child>.btn:first-child{border-bottom-left-radius:0;border-top-left-radius:0}.btn-group .dropdown-toggle:active,.btn-group.open .dropdown-toggle{outline:0}.btn-group>.btn+.dropdown-toggle{padding-right:8px;padding-left:8px}.btn-group>.btn-large+.dropdown-toggle{padding-right:12px;padding-left:12px}.btn-group.open .dropdown-toggle{-webkit-box-shadow:inset 0 3px 5px rgba(0,0,0,0.125);box-shadow:inset 0 3px 5px rgba(0,0,0,0.125)}.btn .caret{margin-left:0}.btn-large .caret{border-width:5px}.dropup .btn-large .caret{border-bottom-width:5px}.btn-group-vertical>.btn{display:block;float:none;width:100%;max-width:100%}.btn-group-vertical>.btn+.btn{margin-top:-1px}.btn-group-vertical .btn:not(:first-child):not(:last-child){border-radius:0}.btn-group-vertical .btn:first-child{border-bottom-right-radius:0;border-bottom-left-radius:0}.btn-group-vertical .btn:last-child{border-top-right-radius:0;border-top-left-radius:0}.btn-group-justified{display:table;width:100%}.btn-group-justified .btn{display:table-cell;float:none;width:1%}.btn-group[data-toggle="buttons"]>.btn>input[type="radio"],.btn-group[data-toggle="buttons"]>.btn>input[type="checkbox"]{display:none}.breadcrumb{padding:8px 15px;margin-bottom:20px;list-style:none;background-color:#f5f5f5;border-radius:4px}.breadcrumb>li{display:inline-block}.breadcrumb>li+li:before{padding:0 5px;color:#ccc;content:"/\00a0"}.breadcrumb>.active{color:#999}.pagination{display:inline-block;padding-left:0;margin:20px 0;border-radius:4px}.pagination>li{display:inline}.pagination>li>a,.pagination>li>span{float:left;padding:4px 12px;line-height:1.428571429;text-decoration:none;background-color:#fff;border:1px solid #ddd;border-left-width:0}.pagination>li:first-child>a,.pagination>li:first-child>span{border-left-width:1px;border-bottom-left-radius:4px;border-top-left-radius:4px}.pagination>li:last-child>a,.pagination>li:last-child>span{border-top-right-radius:4px;border-bottom-right-radius:4px}.pagination>li>a:hover,.pagination>li>a:focus,.pagination>.active>a,.pagination>.active>span{background-color:#f5f5f5}.pagination>.active>a,.pagination>.active>span{color:#999;cursor:default}.pagination>.disabled>span,.pagination>.disabled>a,.pagination>.disabled>a:hover,.pagination>.disabled>a:focus{color:#999;cursor:not-allowed;background-color:#fff}.pagination-large>li>a,.pagination-large>li>span{padding:14px 16px;font-size:18px}.pagination-large>li:first-child>a,.pagination-large>li:first-child>span{border-bottom-left-radius:6px;border-top-left-radius:6px}.pagination-large>li:last-child>a,.pagination-large>li:last-child>span{border-top-right-radius:6px;border-bottom-right-radius:6px}.pagination-small>li>a,.pagination-small>li>span{padding:5px 10px;font-size:12px}.pagination-small>li:first-child>a,.pagination-small>li:first-child>span{border-bottom-left-radius:3px;border-top-left-radius:3px}.pagination-small>li:last-child>a,.pagination-small>li:last-child>span{border-top-right-radius:3px;border-bottom-right-radius:3px}.pager{padding-left:0;margin:20px 0;text-align:center;list-style:none}.pager:before,.pager:after{display:table;content:" "}.pager:after{clear:both}.pager:before,.pager:after{display:table;content:" "}.pager:after{clear:both}.pager li{display:inline}.pager li>a,.pager li>span{display:inline-block;padding:5px 14px;background-color:#fff;border:1px solid #ddd;border-radius:15px}.pager li>a:hover,.pager li>a:focus{text-decoration:none;background-color:#f5f5f5}.pager .next>a,.pager .next>span{float:right}.pager .previous>a,.pager .previous>span{float:left}.pager .disabled>a,.pager .disabled>a:hover,.pager .disabled>a:focus,.pager .disabled>span{color:#999;cursor:not-allowed;background-color:#fff}.modal-open{overflow:hidden}.modal{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1040;display:none;overflow:auto;overflow-y:scroll}.modal.fade .modal-dialog{-webkit-transform:translate(0,-25%);-ms-transform:translate(0,-25%);transform:translate(0,-25%);-webkit-transition:-webkit-transform .3s ease-out;-moz-transition:-moz-transform .3s ease-out;-o-transition:-o-transform .3s ease-out;transition:transform .3s ease-out}.modal.fade.in .modal-dialog{-webkit-transform:translate(0,0);-ms-transform:translate(0,0);transform:translate(0,0)}.modal-dialog{position:relative;top:0;right:0;left:0;z-index:1050;width:auto;padding:10px}.modal-content{position:relative;background-color:#fff;border:1px solid #999;border:1px solid rgba(0,0,0,0.2);border-radius:6px;outline:0;-webkit-box-shadow:0 3px 9px rgba(0,0,0,0.5);box-shadow:0 3px 9px rgba(0,0,0,0.5);background-clip:padding-box}.modal-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1030;background-color:#000}.modal-backdrop.fade{opacity:0;filter:alpha(opacity=0)}.modal-backdrop.fade.in{opacity:.5;filter:alpha(opacity=50)}.modal-header{min-height:16.428571429px;padding:15px;border-bottom:1px solid #e5e5e5}.modal-header .close{margin-top:-2px}.modal-title{margin:0;line-height:1.428571429}.modal-body{position:relative;padding:20px}.modal-footer{padding:19px 20px 20px;margin-top:15px;text-align:right;border-top:1px solid #e5e5e5}.modal-footer:before,.modal-footer:after{display:table;content:" "}.modal-footer:after{clear:both}.modal-footer:before,.modal-footer:after{display:table;content:" "}.modal-footer:after{clear:both}.modal-footer .btn+.btn{margin-bottom:0;margin-left:5px}.modal-footer .btn-group .btn+.btn{margin-left:-1px}.modal-footer .btn-block+.btn-block{margin-left:0}@media screen and (min-width:768px){.modal-dialog{right:auto;left:50%;width:560px;padding-top:30px;padding-bottom:30px;margin-left:-280px}.modal-content{-webkit-box-shadow:0 5px 15px rgba(0,0,0,0.5);box-shadow:0 5px 15px rgba(0,0,0,0.5)}}.tooltip{position:absolute;z-index:1030;display:block;font-size:12px;line-height:1.4;opacity:0;filter:alpha(opacity=0);visibility:visible}.tooltip.in{opacity:1;filter:alpha(opacity=100)}.tooltip.top{padding:5px 0;margin-top:-3px}.tooltip.right{padding:0 5px;margin-left:3px}.tooltip.bottom{padding:5px 0;margin-top:3px}.tooltip.left{padding:0 5px;margin-left:-3px}.tooltip-inner{max-width:200px;padding:3px 8px;color:#fff;text-align:center;text-decoration:none;background-color:rgba(0,0,0,0.9);border-radius:4px}.tooltip-arrow{position:absolute;width:0;height:0;border-color:transparent;border-style:solid}.tooltip.top .tooltip-arrow{bottom:0;left:50%;margin-left:-5px;border-top-color:rgba(0,0,0,0.9);border-width:5px 5px 0}.tooltip.top-left .tooltip-arrow{bottom:0;left:5px;border-top-color:rgba(0,0,0,0.9);border-width:5px 5px 0}.tooltip.top-right .tooltip-arrow{right:5px;bottom:0;border-top-color:rgba(0,0,0,0.9);border-width:5px 5px 0}.tooltip.right .tooltip-arrow{top:50%;left:0;margin-top:-5px;border-right-color:rgba(0,0,0,0.9);border-width:5px 5px 5px 0}.tooltip.left .tooltip-arrow{top:50%;right:0;margin-top:-5px;border-left-color:rgba(0,0,0,0.9);border-width:5px 0 5px 5px}.tooltip.bottom .tooltip-arrow{top:0;left:50%;margin-left:-5px;border-bottom-color:rgba(0,0,0,0.9);border-width:0 5px 5px}.tooltip.bottom-left .tooltip-arrow{top:0;left:5px;border-bottom-color:rgba(0,0,0,0.9);border-width:0 5px 5px}.tooltip.bottom-right .tooltip-arrow{top:0;right:5px;border-bottom-color:rgba(0,0,0,0.9);border-width:0 5px 5px}.popover{position:absolute;top:0;left:0;z-index:1010;display:none;max-width:276px;padding:1px;text-align:left;white-space:normal;background-color:#fff;border:1px solid #ccc;border:1px solid rgba(0,0,0,0.2);border-radius:6px;-webkit-box-shadow:0 5px 10px rgba(0,0,0,0.2);box-shadow:0 5px 10px rgba(0,0,0,0.2);background-clip:padding-box;-webkit-bg-clip:padding-box;-moz-bg-clip:padding}.popover.top{margin-top:-10px}.popover.right{margin-left:10px}.popover.bottom{margin-top:10px}.popover.left{margin-left:-10px}.popover-title{padding:8px 14px;margin:0;font-size:14px;font-weight:normal;line-height:18px;background-color:#f7f7f7;border-bottom:1px solid #ebebeb;border-radius:5px 5px 0 0}.popover-content{padding:9px 14px}.popover .arrow,.popover .arrow:after{position:absolute;display:block;width:0;height:0;border-color:transparent;border-style:solid}.popover .arrow{border-width:11px}.popover .arrow:after{border-width:10px;content:""}.popover.top .arrow{bottom:-11px;left:50%;margin-left:-11px;border-top-color:#999;border-top-color:rgba(0,0,0,0.25);border-bottom-width:0}.popover.top .arrow:after{bottom:1px;margin-left:-10px;border-top-color:#fff;border-bottom-width:0;content:" "}.popover.right .arrow{top:50%;left:-11px;margin-top:-11px;border-right-color:#999;border-right-color:rgba(0,0,0,0.25);border-left-width:0}.popover.right .arrow:after{bottom:-10px;left:1px;border-right-color:#fff;border-left-width:0;content:" "}.popover.bottom .arrow{top:-11px;left:50%;margin-left:-11px;border-bottom-color:#999;border-bottom-color:rgba(0,0,0,0.25);border-top-width:0}.popover.bottom .arrow:after{top:1px;margin-left:-10px;border-bottom-color:#fff;border-top-width:0;content:" "}.popover.left .arrow{top:50%;right:-11px;margin-top:-11px;border-left-color:#999;border-left-color:rgba(0,0,0,0.25);border-right-width:0}.popover.left .arrow:after{right:1px;bottom:-10px;border-left-color:#fff;border-right-width:0;content:" "}.alert{padding:10px 35px 10px 15px;margin-bottom:20px;color:#c09853;background-color:#fcf8e3;border:1px solid #fbeed5;border-radius:4px}.alert h4{margin-top:0;color:inherit}.alert hr{border-top-color:#f8e5be}.alert .alert-link{font-weight:500;color:#a47e3c}.alert .close{position:relative;top:-2px;right:-21px;color:inherit}.alert-success{color:#468847;background-color:#dff0d8;border-color:#d6e9c6}.alert-success hr{border-top-color:#c9e2b3}.alert-success .alert-link{color:#356635}.alert-danger{color:#b94a48;background-color:#f2dede;border-color:#eed3d7}.alert-danger hr{border-top-color:#e6c1c7}.alert-danger .alert-link{color:#953b39}.alert-info{color:#3a87ad;background-color:#d9edf7;border-color:#bce8f1}.alert-info hr{border-top-color:#a6e1ec}.alert-info .alert-link{color:#2d6987}.alert-block{padding-top:15px;padding-bottom:15px}.alert-block>p,.alert-block>ul{margin-bottom:0}.alert-block p+p{margin-top:5px}.thumbnail,.img-thumbnail{padding:4px;line-height:1.428571429;background-color:#fff;border:1px solid #ddd;border-radius:4px;-webkit-transition:all .2s ease-in-out;transition:all .2s ease-in-out}.thumbnail{display:block}.thumbnail>img,.img-thumbnail{display:inline-block;height:auto;max-width:100%}a.thumbnail:hover,a.thumbnail:focus{border-color:#428bca}.thumbnail>img{margin-right:auto;margin-left:auto}.thumbnail .caption{padding:9px;color:#333}.media,.media-body{overflow:hidden;zoom:1}.media,.media .media{margin-top:15px}.media:first-child{margin-top:0}.media-object{display:block}.media-heading{margin:0 0 5px}.media>.pull-left{margin-right:10px}.media>.pull-right{margin-left:10px}.media-list{padding-left:0;list-style:none}.label{display:inline;padding:.25em .6em;font-size:75%;font-weight:500;line-height:1;color:#fff;text-align:center;white-space:nowrap;vertical-align:middle;background-color:#999;border-radius:.25em}.label[href]:hover,.label[href]:focus{color:#fff;text-decoration:none;cursor:pointer;background-color:#808080}.label-danger{background-color:#d9534f}.label-danger[href]:hover,.label-danger[href]:focus{background-color:#c9302c}.label-success{background-color:#5cb85c}.label-success[href]:hover,.label-success[href]:focus{background-color:#449d44}.label-warning{background-color:#f0ad4e}.label-warning[href]:hover,.label-warning[href]:focus{background-color:#ec971f}.label-info{background-color:#5bc0de}.label-info[href]:hover,.label-info[href]:focus{background-color:#31b0d5}.badge{display:inline-block;min-width:10px;padding:3px 7px;font-size:12px;font-weight:bold;line-height:1;color:#fff;text-align:center;white-space:nowrap;vertical-align:middle;background-color:#999;border-radius:10px}.badge:empty{display:none}a.badge:hover,a.badge:focus{color:#fff;text-decoration:none;cursor:pointer}.btn .badge{position:relative;top:-1px}a.list-group-item.active>.badge,.nav-pills>.active>a>.badge{color:#428bca;background-color:#fff}.nav-pills>li>a>.badge{margin-left:3px}@-webkit-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@-moz-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@-ms-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@-o-keyframes progress-bar-stripes{from{background-position:0 0}to{background-position:40px 0}}@keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}.progress{height:20px;margin-bottom:20px;overflow:hidden;background-color:#f5f5f5;border-radius:4px;-webkit-box-shadow:inset 0 1px 2px rgba(0,0,0,0.1);box-shadow:inset 0 1px 2px rgba(0,0,0,0.1)}.progress-bar{float:left;width:0;height:100%;font-size:12px;color:#fff;text-align:center;background-color:#428bca;-webkit-box-shadow:inset 0 -1px 0 rgba(0,0,0,0.15);box-shadow:inset 0 -1px 0 rgba(0,0,0,0.15);-webkit-transition:width .6s ease;transition:width .6s ease}.progress-striped .progress-bar{background-color:#428bca;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-size:40px 40px}.progress.active .progress-bar{-webkit-animation:progress-bar-stripes 2s linear infinite;-moz-animation:progress-bar-stripes 2s linear infinite;-ms-animation:progress-bar-stripes 2s linear infinite;-o-animation:progress-bar-stripes 2s linear infinite;animation:progress-bar-stripes 2s linear infinite}.progress-bar-danger{background-color:#d9534f}.progress-striped .progress-bar-danger{background-color:#d9534f;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.progress-bar-success{background-color:#5cb85c}.progress-striped .progress-bar-success{background-color:#5cb85c;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.progress-bar-warning{background-color:#f0ad4e}.progress-striped .progress-bar-warning{background-color:#f0ad4e;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.progress-bar-info{background-color:#5bc0de}.progress-striped .progress-bar-info{background-color:#5bc0de;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.accordion{margin-bottom:20px}.accordion-group{margin-bottom:2px;border:1px solid #e5e5e5;border-radius:4px}.accordion-heading{border-bottom:0}.accordion-heading .accordion-toggle{display:block;padding:8px 15px;cursor:pointer}.accordion-inner{padding:9px 15px;border-top:1px solid #e5e5e5}.carousel{position:relative}.carousel-inner{position:relative;width:100%;overflow:hidden}.carousel-inner>.item{position:relative;display:none;-webkit-transition:.6s ease-in-out left;transition:.6s ease-in-out left}.carousel-inner>.item>img,.carousel-inner>.item>a>img{display:inline-block;height:auto;max-width:100%;line-height:1}.carousel-inner>.active,.carousel-inner>.next,.carousel-inner>.prev{display:block}.carousel-inner>.active{left:0}.carousel-inner>.next,.carousel-inner>.prev{position:absolute;top:0;width:100%}.carousel-inner>.next{left:100%}.carousel-inner>.prev{left:-100%}.carousel-inner>.next.left,.carousel-inner>.prev.right{left:0}.carousel-inner>.active.left{left:-100%}.carousel-inner>.active.right{left:100%}.carousel-control{position:absolute;top:0;bottom:0;left:0;width:15%;font-size:20px;color:#fff;text-align:center;text-shadow:0 1px 2px rgba(0,0,0,0.6);opacity:.5;filter:alpha(opacity=50)}.carousel-control.left{background-color:rgba(0,0,0,0.0001);background-color:transparent;background-image:-webkit-gradient(linear,0 top,100% top,from(rgba(0,0,0,0.5)),to(rgba(0,0,0,0.0001)));background-image:-webkit-linear-gradient(left,color-stop(rgba(0,0,0,0.5) 0),color-stop(rgba(0,0,0,0.0001) 100%));background-image:-moz-linear-gradient(left,rgba(0,0,0,0.5) 0,rgba(0,0,0,0.0001) 100%);background-image:linear-gradient(to right,rgba(0,0,0,0.5) 0,rgba(0,0,0,0.0001) 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#80000000',endColorstr='#00000000',GradientType=1)}.carousel-control.right{right:0;left:auto;background-color:rgba(0,0,0,0.5);background-color:transparent;background-image:-webkit-gradient(linear,0 top,100% top,from(rgba(0,0,0,0.0001)),to(rgba(0,0,0,0.5)));background-image:-webkit-linear-gradient(left,color-stop(rgba(0,0,0,0.0001) 0),color-stop(rgba(0,0,0,0.5) 100%));background-image:-moz-linear-gradient(left,rgba(0,0,0,0.0001) 0,rgba(0,0,0,0.5) 100%);background-image:linear-gradient(to right,rgba(0,0,0,0.0001) 0,rgba(0,0,0,0.5) 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#00000000',endColorstr='#80000000',GradientType=1)}.carousel-control:hover,.carousel-control:focus{color:#fff;text-decoration:none;opacity:.9;filter:alpha(opacity=90)}.carousel-control .glyphicon,.carousel-control .icon-prev,.carousel-control .icon-next{position:absolute;top:50%;left:50%;z-index:5;display:inline-block;width:20px;height:20px;margin-top:-10px;margin-left:-10px;font-family:serif}.carousel-control .icon-prev:before{content:'\2039'}.carousel-control .icon-next:before{content:'\203a'}.carousel-indicators{position:absolute;bottom:10px;left:50%;z-index:15;width:120px;padding-left:0;margin-left:-60px;text-align:center;list-style:none}.carousel-indicators li{display:inline-block;width:10px;height:10px;margin:1px;text-indent:-999px;cursor:pointer;border:1px solid #fff;border-radius:10px}.carousel-indicators .active{width:12px;height:12px;margin:0;background-color:#fff}.carousel-caption{position:absolute;right:15%;bottom:20px;left:15%;z-index:10;padding-top:20px;padding-bottom:20px;color:#fff;text-align:center;text-shadow:0 1px 2px rgba(0,0,0,0.6)}.carousel-caption .btn{text-shadow:none}@media screen and (min-width:768px){.carousel-control .glyphicon,.carousel-control .icon-prev,.carousel-control .icon-next{width:30px;height:30px;margin-top:-15px;margin-left:-15px;font-size:30px}.carousel-caption{right:20%;left:20%;padding-bottom:30px}.carousel-indicators{bottom:20px}}.jumbotron{padding:30px;margin-bottom:30px;font-size:21px;font-weight:200;line-height:2.1428571435;color:inherit;background-color:#eee}.jumbotron h1{line-height:1;color:inherit}.jumbotron p{line-height:1.4}@media screen and (min-width:768px){.jumbotron{padding:50px 60px;border-radius:6px}.jumbotron h1{font-size:63px}}.clearfix:before,.clearfix:after{display:table;content:" "}.clearfix:after{clear:both}.pull-right{float:right}.pull-left{float:left}.hide{display:none!important}.show{display:block!important}.invisible{visibility:hidden}.text-hide{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0}.affix{position:fixed}@-ms-viewport{width:device-width}@media screen and (max-width:400px){@-ms-viewport{width:320px}}.hidden{display:none!important;visibility:hidden!important}.visible-sm{display:block!important}tr.visible-sm{display:table-row!important}th.visible-sm,td.visible-sm{display:table-cell!important}.visible-md{display:none!important}tr.visible-md{display:none!important}th.visible-md,td.visible-md{display:none!important}.visible-lg{display:none!important}tr.visible-lg{display:none!important}th.visible-lg,td.visible-lg{display:none!important}.hidden-sm{display:none!important}tr.hidden-sm{display:none!important}th.hidden-sm,td.hidden-sm{display:none!important}.hidden-md{display:block!important}tr.hidden-md{display:table-row!important}th.hidden-md,td.hidden-md{display:table-cell!important}.hidden-lg{display:block!important}tr.hidden-lg{display:table-row!important}th.hidden-lg,td.hidden-lg{display:table-cell!important}@media(min-width:768px) and (max-width:991px){.visible-sm{display:none!important}tr.visible-sm{display:none!important}th.visible-sm,td.visible-sm{display:none!important}.visible-md{display:block!important}tr.visible-md{display:table-row!important}th.visible-md,td.visible-md{display:table-cell!important}.visible-lg{display:none!important}tr.visible-lg{display:none!important}th.visible-lg,td.visible-lg{display:none!important}.hidden-sm{display:block!important}tr.hidden-sm{display:table-row!important}th.hidden-sm,td.hidden-sm{display:table-cell!important}.hidden-md{display:none!important}tr.hidden-md{display:none!important}th.hidden-md,td.hidden-md{display:none!important}.hidden-lg{display:block!important}tr.hidden-lg{display:table-row!important}th.hidden-lg,td.hidden-lg{display:table-cell!important}}@media(min-width:992px){.visible-sm{display:none!important}tr.visible-sm{display:none!important}th.visible-sm,td.visible-sm{display:none!important}.visible-md{display:none!important}tr.visible-md{display:none!important}th.visible-md,td.visible-md{display:none!important}.visible-lg{display:block!important}tr.visible-lg{display:table-row!important}th.visible-lg,td.visible-lg{display:table-cell!important}.hidden-sm{display:block!important}tr.hidden-sm{display:table-row!important}th.hidden-sm,td.hidden-sm{display:table-cell!important}.hidden-md{display:block!important}tr.hidden-md{display:table-row!important}th.hidden-md,td.hidden-md{display:table-cell!important}.hidden-lg{display:none!important}tr.hidden-lg{display:none!important}th.hidden-lg,td.hidden-lg{display:none!important}}.visible-print{display:none!important}tr.visible-print{display:none!important}th.visible-print,td.visible-print{display:none!important}@media print{.visible-print{display:block!important}tr.visible-print{display:table-row!important}th.visible-print,td.visible-print{display:table-cell!important}.hidden-print{display:none!important}tr.hidden-print{display:none!important}th.hidden-print,td.hidden-print{display:none!important}} </style> <!-- zepto --> <script type="text/javascript"> /* Zepto v1.1.2 - zepto event ajax form ie - zeptojs.com/license */ var Zepto=function(){function G(a){return a==null?String(a):z[A.call(a)]||"object"}function H(a){return G(a)=="function"}function I(a){return a!=null&&a==a.window}function J(a){return a!=null&&a.nodeType==a.DOCUMENT_NODE}function K(a){return G(a)=="object"}function L(a){return K(a)&&!I(a)&&Object.getPrototypeOf(a)==Object.prototype}function M(a){return a instanceof Array}function N(a){return typeof a.length=="number"}function O(a){return g.call(a,function(a){return a!=null})}function P(a){return a.length>0?c.fn.concat.apply([],a):a}function Q(a){return a.replace(/::/g,"/").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/_/g,"-").toLowerCase()}function R(a){return a in j?j[a]:j[a]=new RegExp("(^|\\s)"+a+"(\\s|$)")}function S(a,b){return typeof b=="number"&&!k[Q(a)]?b+"px":b}function T(a){var b,c;return i[a]||(b=h.createElement(a),h.body.appendChild(b),c=getComputedStyle(b,"").getPropertyValue("display"),b.parentNode.removeChild(b),c=="none"&&(c="block"),i[a]=c),i[a]}function U(a){return"children"in a?f.call(a.children):c.map(a.childNodes,function(a){if(a.nodeType==1)return a})}function V(c,d,e){for(b in d)e&&(L(d[b])||M(d[b]))?(L(d[b])&&!L(c[b])&&(c[b]={}),M(d[b])&&!M(c[b])&&(c[b]=[]),V(c[b],d[b],e)):d[b]!==a&&(c[b]=d[b])}function W(a,b){return b==null?c(a):c(a).filter(b)}function X(a,b,c,d){return H(b)?b.call(a,c,d):b}function Y(a,b,c){c==null?a.removeAttribute(b):a.setAttribute(b,c)}function Z(b,c){var d=b.className,e=d&&d.baseVal!==a;if(c===a)return e?d.baseVal:d;e?d.baseVal=c:b.className=c}function $(a){var b;try{return a?a=="true"||(a=="false"?!1:a=="null"?null:!/^0/.test(a)&&!isNaN(b=Number(a))?b:/^[\[\{]/.test(a)?c.parseJSON(a):a):a}catch(d){return a}}function _(a,b){b(a);for(var c in a.childNodes)_(a.childNodes[c],b)}var a,b,c,d,e=[],f=e.slice,g=e.filter,h=window.document,i={},j={},k={"column-count":1,columns:1,"font-weight":1,"line-height":1,opacity:1,"z-index":1,zoom:1},l=/^\s*<(\w+|!)[^>]*>/,m=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,n=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,o=/^(?:body|html)$/i,p=/([A-Z])/g,q=["val","css","html","text","data","width","height","offset"],r=["after","prepend","before","append"],s=h.createElement("table"),t=h.createElement("tr"),u={tr:h.createElement("tbody"),tbody:s,thead:s,tfoot:s,td:t,th:t,"*":h.createElement("div")},v=/complete|loaded|interactive/,w=/^\.([\w-]+)$/,x=/^#([\w-]*)$/,y=/^[\w-]*$/,z={},A=z.toString,B={},C,D,E=h.createElement("div"),F={tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"};return B.matches=function(a,b){if(!b||!a||a.nodeType!==1)return!1;var c=a.webkitMatchesSelector||a.mozMatchesSelector||a.oMatchesSelector||a.matchesSelector;if(c)return c.call(a,b);var d,e=a.parentNode,f=!e;return f&&(e=E).appendChild(a),d=~B.qsa(e,b).indexOf(a),f&&E.removeChild(a),d},C=function(a){return a.replace(/-+(.)?/g,function(a,b){return b?b.toUpperCase():""})},D=function(a){return g.call(a,function(b,c){return a.indexOf(b)==c})},B.fragment=function(b,d,e){var g,i,j;return m.test(b)&&(g=c(h.createElement(RegExp.$1))),g||(b.replace&&(b=b.replace(n,"<$1></$2>")),d===a&&(d=l.test(b)&&RegExp.$1),d in u||(d="*"),j=u[d],j.innerHTML=""+b,g=c.each(f.call(j.childNodes),function(){j.removeChild(this)})),L(e)&&(i=c(g),c.each(e,function(a,b){q.indexOf(a)>-1?i[a](b):i.attr(a,b)})),g},B.Z=function(a,b){return a=a||[],a.__proto__=c.fn,a.selector=b||"",a},B.isZ=function(a){return a instanceof B.Z},B.init=function(b,d){var e;if(!b)return B.Z();if(typeof b=="string"){b=b.trim();if(b[0]=="<"&&l.test(b))e=B.fragment(b,RegExp.$1,d),b=null;else{if(d!==a)return c(d).find(b);e=B.qsa(h,b)}}else{if(H(b))return c(h).ready(b);if(B.isZ(b))return b;if(M(b))e=O(b);else if(K(b))e=[b],b=null;else if(l.test(b))e=B.fragment(b.trim(),RegExp.$1,d),b=null;else{if(d!==a)return c(d).find(b);e=B.qsa(h,b)}}return B.Z(e,b)},c=function(a,b){return B.init(a,b)},c.extend=function(a){var b,c=f.call(arguments,1);return typeof a=="boolean"&&(b=a,a=c.shift()),c.forEach(function(c){V(a,c,b)}),a},B.qsa=function(a,b){var c,d=b[0]=="#",e=!d&&b[0]==".",g=d||e?b.slice(1):b,h=y.test(g);return J(a)&&h&&d?(c=a.getElementById(g))?[c]:[]:a.nodeType!==1&&a.nodeType!==9?[]:f.call(h&&!d?e?a.getElementsByClassName(g):a.getElementsByTagName(b):a.querySelectorAll(b))},c.contains=function(a,b){return a!==b&&a.contains(b)},c.type=G,c.isFunction=H,c.isWindow=I,c.isArray=M,c.isPlainObject=L,c.isEmptyObject=function(a){var b;for(b in a)return!1;return!0},c.inArray=function(a,b,c){return e.indexOf.call(b,a,c)},c.camelCase=C,c.trim=function(a){return a==null?"":String.prototype.trim.call(a)},c.uuid=0,c.support={},c.expr={},c.map=function(a,b){var c,d=[],e,f;if(N(a))for(e=0;e<a.length;e++)c=b(a[e],e),c!=null&&d.push(c);else for(f in a)c=b(a[f],f),c!=null&&d.push(c);return P(d)},c.each=function(a,b){var c,d;if(N(a)){for(c=0;c<a.length;c++)if(b.call(a[c],c,a[c])===!1)return a}else for(d in a)if(b.call(a[d],d,a[d])===!1)return a;return a},c.grep=function(a,b){return g.call(a,b)},window.JSON&&(c.parseJSON=JSON.parse),c.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){z["[object "+b+"]"]=b.toLowerCase()}),c.fn={forEach:e.forEach,reduce:e.reduce,push:e.push,sort:e.sort,indexOf:e.indexOf,concat:e.concat,map:function(a){return c(c.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return c(f.apply(this,arguments))},ready:function(a){return v.test(h.readyState)&&h.body?a(c):h.addEventListener("DOMContentLoaded",function(){a(c)},!1),this},get:function(b){return b===a?f.call(this):this[b>=0?b:b+this.length]},toArray:function(){return this.get()},size:function(){return this.length},remove:function(){return this.each(function(){this.parentNode!=null&&this.parentNode.removeChild(this)})},each:function(a){return e.every.call(this,function(b,c){return a.call(b,c,b)!==!1}),this},filter:function(a){return H(a)?this.not(this.not(a)):c(g.call(this,function(b){return B.matches(b,a)}))},add:function(a,b){return c(D(this.concat(c(a,b))))},is:function(a){return this.length>0&&B.matches(this[0],a)},not:function(b){var d=[];if(H(b)&&b.call!==a)this.each(function(a){b.call(this,a)||d.push(this)});else{var e=typeof b=="string"?this.filter(b):N(b)&&H(b.item)?f.call(b):c(b);this.forEach(function(a){e.indexOf(a)<0&&d.push(a)})}return c(d)},has:function(a){return this.filter(function(){return K(a)?c.contains(this,a):c(this).find(a).size()})},eq:function(a){return a===-1?this.slice(a):this.slice(a,+a+1)},first:function(){var a=this[0];return a&&!K(a)?a:c(a)},last:function(){var a=this[this.length-1];return a&&!K(a)?a:c(a)},find:function(a){var b,d=this;return typeof a=="object"?b=c(a).filter(function(){var a=this;return e.some.call(d,function(b){return c.contains(b,a)})}):this.length==1?b=c(B.qsa(this[0],a)):b=this.map(function(){return B.qsa(this,a)}),b},closest:function(a,b){var d=this[0],e=!1;typeof a=="object"&&(e=c(a));while(d&&!(e?e.indexOf(d)>=0:B.matches(d,a)))d=d!==b&&!J(d)&&d.parentNode;return c(d)},parents:function(a){var b=[],d=this;while(d.length>0)d=c.map(d,function(a){if((a=a.parentNode)&&!J(a)&&b.indexOf(a)<0)return b.push(a),a});return W(b,a)},parent:function(a){return W(D(this.pluck("parentNode")),a)},children:function(a){return W(this.map(function(){return U(this)}),a)},contents:function(){return this.map(function(){return f.call(this.childNodes)})},siblings:function(a){return W(this.map(function(a,b){return g.call(U(b.parentNode),function(a){return a!==b})}),a)},empty:function(){return this.each(function(){this.innerHTML=""})},pluck:function(a){return c.map(this,function(b){return b[a]})},show:function(){return this.each(function(){this.style.display=="none"&&(this.style.display=""),getComputedStyle(this,"").getPropertyValue("display")=="none"&&(this.style.display=T(this.nodeName))})},replaceWith:function(a){return this.before(a).remove()},wrap:function(a){var b=H(a);if(this[0]&&!b)var d=c(a).get(0),e=d.parentNode||this.length>1;return this.each(function(f){c(this).wrapAll(b?a.call(this,f):e?d.cloneNode(!0):d)})},wrapAll:function(a){if(this[0]){c(this[0]).before(a=c(a));var b;while((b=a.children()).length)a=b.first();c(a).append(this)}return this},wrapInner:function(a){var b=H(a);return this.each(function(d){var e=c(this),f=e.contents(),g=b?a.call(this,d):a;f.length?f.wrapAll(g):e.append(g)})},unwrap:function(){return this.parent().each(function(){c(this).replaceWith(c(this).children())}),this},clone:function(){return this.map(function(){return this.cloneNode(!0)})},hide:function(){return this.css("display","none")},toggle:function(b){return this.each(function(){var d=c(this);(b===a?d.css("display")=="none":b)?d.show():d.hide()})},prev:function(a){return c(this.pluck("previousElementSibling")).filter(a||"*")},next:function(a){return c(this.pluck("nextElementSibling")).filter(a||"*")},html:function(a){return arguments.length===0?this.length>0?this[0].innerHTML:null:this.each(function(b){var d=this.innerHTML;c(this).empty().append(X(this,a,b,d))})},text:function(b){return arguments.length===0?this.length>0?this[0].textContent:null:this.each(function(){this.textContent=b===a?"":""+b})},attr:function(c,d){var e;return typeof c=="string"&&d===a?this.length==0||this[0].nodeType!==1?a:c=="value"&&this[0].nodeName=="INPUT"?this.val():!(e=this[0].getAttribute(c))&&c in this[0]?this[0][c]:e:this.each(function(a){if(this.nodeType!==1)return;if(K(c))for(b in c)Y(this,b,c[b]);else Y(this,c,X(this,d,a,this.getAttribute(c)))})},removeAttr:function(a){return this.each(function(){this.nodeType===1&&Y(this,a)})},prop:function(b,c){return b=F[b]||b,c===a?this[0]&&this[0][b]:this.each(function(a){this[b]=X(this,c,a,this[b])})},data:function(b,c){var d=this.attr("data-"+b.replace(p,"-$1").toLowerCase(),c);return d!==null?$(d):a},val:function(a){return arguments.length===0?this[0]&&(this[0].multiple?c(this[0]).find("option").filter(function(){return this.selected}).pluck("value"):this[0].value):this.each(function(b){this.value=X(this,a,b,this.value)})},offset:function(a){if(a)return this.each(function(b){var d=c(this),e=X(this,a,b,d.offset()),f=d.offsetParent().offset(),g={top:e.top-f.top,left:e.left-f.left};d.css("position")=="static"&&(g.position="relative"),d.css(g)});if(this.length==0)return null;var b=this[0].getBoundingClientRect();return{left:b.left+window.pageXOffset,top:b.top+window.pageYOffset,width:Math.round(b.width),height:Math.round(b.height)}},css:function(a,d){if(arguments.length<2){var e=this[0],f=getComputedStyle(e,"");if(!e)return;if(typeof a=="string")return e.style[C(a)]||f.getPropertyValue(a);if(M(a)){var g={};return c.each(M(a)?a:[a],function(a,b){g[b]=e.style[C(b)]||f.getPropertyValue(b)}),g}}var h="";if(G(a)=="string")!d&&d!==0?this.each(function(){this.style.removeProperty(Q(a))}):h=Q(a)+":"+S(a,d);else for(b in a)!a[b]&&a[b]!==0?this.each(function(){this.style.removeProperty(Q(b))}):h+=Q(b)+":"+S(b,a[b])+";";return this.each(function(){this.style.cssText+=";"+h})},index:function(a){return a?this.indexOf(c(a)[0]):this.parent().children().indexOf(this[0])},hasClass:function(a){return a?e.some.call(this,function(a){return this.test(Z(a))},R(a)):!1},addClass:function(a){return a?this.each(function(b){d=[];var e=Z(this),f=X(this,a,b,e);f.split(/\s+/g).forEach(function(a){c(this).hasClass(a)||d.push(a)},this),d.length&&Z(this,e+(e?" ":"")+d.join(" "))}):this},removeClass:function(b){return this.each(function(c){if(b===a)return Z(this,"");d=Z(this),X(this,b,c,d).split(/\s+/g).forEach(function(a){d=d.replace(R(a)," ")}),Z(this,d.trim())})},toggleClass:function(b,d){return b?this.each(function(e){var f=c(this),g=X(this,b,e,Z(this));g.split(/\s+/g).forEach(function(b){(d===a?!f.hasClass(b):d)?f.addClass(b):f.removeClass(b)})}):this},scrollTop:function(b){if(!this.length)return;var c="scrollTop"in this[0];return b===a?c?this[0].scrollTop:this[0].pageYOffset:this.each(c?function(){this.scrollTop=b}:function(){this.scrollTo(this.scrollX,b)})},scrollLeft:function(b){if(!this.length)return;var c="scrollLeft"in this[0];return b===a?c?this[0].scrollLeft:this[0].pageXOffset:this.each(c?function(){this.scrollLeft=b}:function(){this.scrollTo(b,this.scrollY)})},position:function(){if(!this.length)return;var a=this[0],b=this.offsetParent(),d=this.offset(),e=o.test(b[0].nodeName)?{top:0,left:0}:b.offset();return d.top-=parseFloat(c(a).css("margin-top"))||0,d.left-=parseFloat(c(a).css("margin-left"))||0,e.top+=parseFloat(c(b[0]).css("border-top-width"))||0,e.left+=parseFloat(c(b[0]).css("border-left-width"))||0,{top:d.top-e.top,left:d.left-e.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||h.body;while(a&&!o.test(a.nodeName)&&c(a).css("position")=="static")a=a.offsetParent;return a})}},c.fn.detach=c.fn.remove,["width","height"].forEach(function(b){var d=b.replace(/./,function(a){return a[0].toUpperCase()});c.fn[b]=function(e){var f,g=this[0];return e===a?I(g)?g["inner"+d]:J(g)?g.documentElement["scroll"+d]:(f=this.offset())&&f[b]:this.each(function(a){g=c(this),g.css(b,X(this,e,a,g[b]()))})}}),r.forEach(function(a,b){var d=b%2;c.fn[a]=function(){var a,e=c.map(arguments,function(b){return a=G(b),a=="object"||a=="array"||b==null?b:B.fragment(b)}),f,g=this.length>1;return e.length<1?this:this.each(function(a,h){f=d?h:h.parentNode,h=b==0?h.nextSibling:b==1?h.firstChild:b==2?h:null,e.forEach(function(a){if(g)a=a.cloneNode(!0);else if(!f)return c(a).remove();_(f.insertBefore(a,h),function(a){a.nodeName!=null&&a.nodeName.toUpperCase()==="SCRIPT"&&(!a.type||a.type==="text/javascript")&&!a.src&&window.eval.call(window,a.innerHTML)})})})},c.fn[d?a+"To":"insert"+(b?"Before":"After")]=function(b){return c(b)[a](this),this}}),B.Z.prototype=c.fn,B.uniq=D,B.deserializeValue=$,c.zepto=B,c}();window.Zepto=Zepto,window.$===undefined&&(window.$=Zepto),function(a){function m(a){return a._zid||(a._zid=c++)}function n(a,b,c,d){b=o(b);if(b.ns)var e=p(b.ns);return(h[m(a)]||[]).filter(function(a){return a&&(!b.e||a.e==b.e)&&(!b.ns||e.test(a.ns))&&(!c||m(a.fn)===m(c))&&(!d||a.sel==d)})}function o(a){var b=(""+a).split(".");return{e:b[0],ns:b.slice(1).sort().join(" ")}}function p(a){return new RegExp("(?:^| )"+a.replace(" "," .* ?")+"(?: |$)")}function q(a,b){return a.del&&!j&&a.e in k||!!b}function r(a){return l[a]||j&&k[a]||a}function s(b,c,e,f,g,i,j){var k=m(b),n=h[k]||(h[k]=[]);c.split(/\s/).forEach(function(c){if(c=="ready")return a(document).ready(e);var h=o(c);h.fn=e,h.sel=g,h.e in l&&(e=function(b){var c=b.relatedTarget;if(!c||c!==this&&!a.contains(this,c))return h.fn.apply(this,arguments)}),h.del=i;var k=i||e;h.proxy=function(a){a=y(a);if(a.isImmediatePropagationStopped())return;a.data=f;var c=k.apply(b,a._args==d?[a]:[a].concat(a._args));return c===!1&&(a.preventDefault(),a.stopPropagation()),c},h.i=n.length,n.push(h),"addEventListener"in b&&b.addEventListener(r(h.e),h.proxy,q(h,j))})}function t(a,b,c,d,e){var f=m(a);(b||"").split(/\s/).forEach(function(b){n(a,b,c,d).forEach(function(b){delete h[f][b.i],"removeEventListener"in a&&a.removeEventListener(r(b.e),b.proxy,q(b,e))})})}function y(b,c){if(c||!b.isDefaultPrevented){c||(c=b),a.each(x,function(a,d){var e=c[a];b[a]=function(){return this[d]=u,e&&e.apply(c,arguments)},b[d]=v});if(c.defaultPrevented!==d?c.defaultPrevented:"returnValue"in c?c.returnValue===!1:c.getPreventDefault&&c.getPreventDefault())b.isDefaultPrevented=u}return b}function z(a){var b,c={originalEvent:a};for(b in a)!w.test(b)&&a[b]!==d&&(c[b]=a[b]);return y(c,a)}var b=a.zepto.qsa,c=1,d,e=Array.prototype.slice,f=a.isFunction,g=function(a){return typeof a=="string"},h={},i={},j="onfocusin"in window,k={focus:"focusin",blur:"focusout"},l={mouseenter:"mouseover",mouseleave:"mouseout"};i.click=i.mousedown=i.mouseup=i.mousemove="MouseEvents",a.event={add:s,remove:t},a.proxy=function(b,c){if(f(b)){var d=function(){return b.apply(c,arguments)};return d._zid=m(b),d}if(g(c))return a.proxy(b[c],b);throw new TypeError("expected function")},a.fn.bind=function(a,b,c){return this.on(a,b,c)},a.fn.unbind=function(a,b){return this.off(a,b)},a.fn.one=function(a,b,c,d){return this.on(a,b,c,d,1)};var u=function(){return!0},v=function(){return!1},w=/^([A-Z]|returnValue$|layer[XY]$)/,x={preventDefault:"isDefaultPrevented",stopImmediatePropagation:"isImmediatePropagationStopped",stopPropagation:"isPropagationStopped"};a.fn.delegate=function(a,b,c){return this.on(b,a,c)},a.fn.undelegate=function(a,b,c){return this.off(b,a,c)},a.fn.live=function(b,c){return a(document.body).delegate(this.selector,b,c),this},a.fn.die=function(b,c){return a(document.body).undelegate(this.selector,b,c),this},a.fn.on=function(b,c,h,i,j){var k,l,m=this;if(b&&!g(b))return a.each(b,function(a,b){m.on(a,c,h,b,j)}),m;!g(c)&&!f(i)&&i!==!1&&(i=h,h=c,c=d);if(f(h)||h===!1)i=h,h=d;return i===!1&&(i=v),m.each(function(d,f){j&&(k=function(a){return t(f,a.type,i),i.apply(this,arguments)}),c&&(l=function(b){var d,g=a(b.target).closest(c,f).get(0);if(g&&g!==f)return d=a.extend(z(b),{currentTarget:g,liveFired:f}),(k||i).apply(g,[d].concat(e.call(arguments,1)))}),s(f,b,i,h,c,l||k)})},a.fn.off=function(b,c,e){var h=this;return b&&!g(b)?(a.each(b,function(a,b){h.off(a,c,b)}),h):(!g(c)&&!f(e)&&e!==!1&&(e=c,c=d),e===!1&&(e=v),h.each(function(){t(this,b,e,c)}))},a.fn.trigger=function(b,c){return b=g(b)||a.isPlainObject(b)?a.Event(b):y(b),b._args=c,this.each(function(){"dispatchEvent"in this?this.dispatchEvent(b):a(this).triggerHandler(b,c)})},a.fn.triggerHandler=function(b,c){var d,e;return this.each(function(f,h){d=z(g(b)?a.Event(b):b),d._args=c,d.target=h,a.each(n(h,b.type||b),function(a,b){e=b.proxy(d);if(d.isImmediatePropagationStopped())return!1})}),e},"focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select keydown keypress keyup error".split(" ").forEach(function(b){a.fn[b]=function(a){return a?this.bind(b,a):this.trigger(b)}}),["focus","blur"].forEach(function(b){a.fn[b]=function(a){return a?this.bind(b,a):this.each(function(){try{this[b]()}catch(a){}}),this}}),a.Event=function(a,b){g(a)||(b=a,a=b.type);var c=document.createEvent(i[a]||"Events"),d=!0;if(b)for(var e in b)e=="bubbles"?d=!!b[e]:c[e]=b[e];return c.initEvent(a,d,!0),y(c)}}(Zepto),function($){function triggerAndReturn(a,b,c){var d=$.Event(b);return $(a).trigger(d,c),!d.isDefaultPrevented()}function triggerGlobal(a,b,c,d){if(a.global)return triggerAndReturn(b||document,c,d)}function ajaxStart(a){a.global&&$.active++===0&&triggerGlobal(a,null,"ajaxStart")}function ajaxStop(a){a.global&&!--$.active&&triggerGlobal(a,null,"ajaxStop")}function ajaxBeforeSend(a,b){var c=b.context;if(b.beforeSend.call(c,a,b)===!1||triggerGlobal(b,c,"ajaxBeforeSend",[a,b])===!1)return!1;triggerGlobal(b,c,"ajaxSend",[a,b])}function ajaxSuccess(a,b,c,d){var e=c.context,f="success";c.success.call(e,a,f,b),d&&d.resolveWith(e,[a,f,b]),triggerGlobal(c,e,"ajaxSuccess",[b,c,a]),ajaxComplete(f,b,c)}function ajaxError(a,b,c,d,e){var f=d.context;d.error.call(f,c,b,a),e&&e.rejectWith(f,[c,b,a]),triggerGlobal(d,f,"ajaxError",[c,d,a||b]),ajaxComplete(b,c,d)}function ajaxComplete(a,b,c){var d=c.context;c.complete.call(d,b,a),triggerGlobal(c,d,"ajaxComplete",[b,c]),ajaxStop(c)}function empty(){}function mimeToDataType(a){return a&&(a=a.split(";",2)[0]),a&&(a==htmlType?"html":a==jsonType?"json":scriptTypeRE.test(a)?"script":xmlTypeRE.test(a)&&"xml")||"text"}function appendQuery(a,b){return b==""?a:(a+"&"+b).replace(/[&?]{1,2}/,"?")}function serializeData(a){a.processData&&a.data&&$.type(a.data)!="string"&&(a.data=$.param(a.data,a.traditional)),a.data&&(!a.type||a.type.toUpperCase()=="GET")&&(a.url=appendQuery(a.url,a.data),a.data=undefined)}function parseArguments(a,b,c,d){var e=!$.isFunction(b);return{url:a,data:e?b:undefined,success:e?$.isFunction(c)?c:undefined:b,dataType:e?d||c:c}}function serialize(a,b,c,d){var e,f=$.isArray(b),g=$.isPlainObject(b);$.each(b,function(b,h){e=$.type(h),d&&(b=c?d:d+"["+(g||e=="object"||e=="array"?b:"")+"]"),!d&&f?a.add(h.name,h.value):e=="array"||!c&&e=="object"?serialize(a,h,c,b):a.add(b,h)})}var jsonpID=0,document=window.document,key,name,rscript=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,scriptTypeRE=/^(?:text|application)\/javascript/i,xmlTypeRE=/^(?:text|application)\/xml/i,jsonType="application/json",htmlType="text/html",blankRE=/^\s*$/;$.active=0,$.ajaxJSONP=function(a,b){if("type"in a){var c=a.jsonpCallback,d=($.isFunction(c)?c():c)||"jsonp"+ ++jsonpID,e=document.createElement("script"),f=window[d],g,h=function(a){$(e).triggerHandler("error",a||"abort")},i={abort:h},j;return b&&b.promise(i),$(e).on("load error",function(c,h){clearTimeout(j),$(e).off().remove(),c.type=="error"||!g?ajaxError(null,h||"error",i,a,b):ajaxSuccess(g[0],i,a,b),window[d]=f,g&&$.isFunction(f)&&f(g[0]),f=g=undefined}),ajaxBeforeSend(i,a)===!1?(h("abort"),i):(window[d]=function(){g=arguments},e.src=a.url.replace(/=\?/,"="+d),document.head.appendChild(e),a.timeout>0&&(j=setTimeout(function(){h("timeout")},a.timeout)),i)}return $.ajax(a)},$.ajaxSettings={type:"GET",beforeSend:empty,success:empty,error:empty,complete:empty,context:null,global:!0,xhr:function(){return new window.XMLHttpRequest},accepts:{script:"text/javascript, application/javascript, application/x-javascript",json:jsonType,xml:"application/xml, text/xml",html:htmlType,text:"text/plain"},crossDomain:!1,timeout:0,processData:!0,cache:!0},$.ajax=function(options){var settings=$.extend({},options||{}),deferred=$.Deferred&&$.Deferred();for(key in $.ajaxSettings)settings[key]===undefined&&(settings[key]=$.ajaxSettings[key]);ajaxStart(settings),settings.crossDomain||(settings.crossDomain=/^([\w-]+:)?\/\/([^\/]+)/.test(settings.url)&&RegExp.$2!=window.location.host),settings.url||(settings.url=window.location.toString()),serializeData(settings),settings.cache===!1&&(settings.url=appendQuery(settings.url,"_="+Date.now()));var dataType=settings.dataType,hasPlaceholder=/=\?/.test(settings.url);if(dataType=="jsonp"||hasPlaceholder)return hasPlaceholder||(settings.url=appendQuery(settings.url,settings.jsonp?settings.jsonp+"=?":settings.jsonp===!1?"":"callback=?")),$.ajaxJSONP(settings,deferred);var mime=settings.accepts[dataType],headers={},setHeader=function(a,b){headers[a.toLowerCase()]=[a,b]},protocol=/^([\w-]+:)\/\//.test(settings.url)?RegExp.$1:window.location.protocol,xhr=settings.xhr(),nativeSetHeader=xhr.setRequestHeader,abortTimeout;deferred&&deferred.promise(xhr),settings.crossDomain||setHeader("X-Requested-With","XMLHttpRequest"),setHeader("Accept",mime||"*/*");if(mime=settings.mimeType||mime)mime.indexOf(",")>-1&&(mime=mime.split(",",2)[0]),xhr.overrideMimeType&&xhr.overrideMimeType(mime);(settings.contentType||settings.contentType!==!1&&settings.data&&settings.type.toUpperCase()!="GET")&&setHeader("Content-Type",settings.contentType||"application/x-www-form-urlencoded");if(settings.headers)for(name in settings.headers)setHeader(name,settings.headers[name]);xhr.setRequestHeader=setHeader,xhr.onreadystatechange=function(){if(xhr.readyState==4){xhr.onreadystatechange=empty,clearTimeout(abortTimeout);var result,error=!1;if(xhr.status>=200&&xhr.status<300||xhr.status==304||xhr.status==0&&protocol=="file:"){dataType=dataType||mimeToDataType(settings.mimeType||xhr.getResponseHeader("content-type")),result=xhr.responseText;try{dataType=="script"?(1,eval)(result):dataType=="xml"?result=xhr.responseXML:dataType=="json"&&(result=blankRE.test(result)?null:$.parseJSON(result))}catch(e){error=e}error?ajaxError(error,"parsererror",xhr,settings,deferred):ajaxSuccess(result,xhr,settings,deferred)}else ajaxError(xhr.statusText||null,xhr.status?"error":"abort",xhr,settings,deferred)}};if(ajaxBeforeSend(xhr,settings)===!1)return xhr.abort(),ajaxError(null,"abort",xhr,settings,deferred),xhr;if(settings.xhrFields)for(name in settings.xhrFields)xhr[name]=settings.xhrFields[name];var async="async"in settings?settings.async:!0;xhr.open(settings.type,settings.url,async,settings.username,settings.password);for(name in headers)nativeSetHeader.apply(xhr,headers[name]);return settings.timeout>0&&(abortTimeout=setTimeout(function(){xhr.onreadystatechange=empty,xhr.abort(),ajaxError(null,"timeout",xhr,settings,deferred)},settings.timeout)),xhr.send(settings.data?settings.data:null),xhr},$.get=function(a,b,c,d){return $.ajax(parseArguments.apply(null,arguments))},$.post=function(a,b,c,d){var e=parseArguments.apply(null,arguments);return e.type="POST",$.ajax(e)},$.getJSON=function(a,b,c){var d=parseArguments.apply(null,arguments);return d.dataType="json",$.ajax(d)},$.fn.load=function(a,b,c){if(!this.length)return this;var d=this,e=a.split(/\s/),f,g=parseArguments(a,b,c),h=g.success;return e.length>1&&(g.url=e[0],f=e[1]),g.success=function(a){d.html(f?$("<div>").html(a.replace(rscript,"")).find(f):a),h&&h.apply(d,arguments)},$.ajax(g),this};var escape=encodeURIComponent;$.param=function(a,b){var c=[];return c.add=function(a,b){this.push(escape(a)+"="+escape(b))},serialize(c,a,b),c.join("&").replace(/%20/g,"+")}}(Zepto),function(a){a.fn.serializeArray=function(){var b=[],c;return a([].slice.call(this.get(0).elements)).each(function(){c=a(this);var d=c.attr("type");this.nodeName.toLowerCase()!="fieldset"&&!this.disabled&&d!="submit"&&d!="reset"&&d!="button"&&(d!="radio"&&d!="checkbox"||this.checked)&&b.push({name:c.attr("name"),value:c.val()})}),b},a.fn.serialize=function(){var a=[];return this.serializeArray().forEach(function(b){a.push(encodeURIComponent(b.name)+"="+encodeURIComponent(b.value))}),a.join("&")},a.fn.submit=function(b){if(b)this.bind("submit",b);else if(this.length){var c=a.Event("submit");this.eq(0).trigger(c),c.isDefaultPrevented()||this.get(0).submit()}return this}}(Zepto),function(a){"__proto__"in{}||a.extend(a.zepto,{Z:function(b,c){return b=b||[],a.extend(b,a.fn),b.selector=c||"",b.__Z=!0,b},isZ:function(b){return a.type(b)==="array"&&"__Z"in b}});try{getComputedStyle(undefined)}catch(b){var c=getComputedStyle;window.getComputedStyle=function(a){try{return c(a)}catch(b){return null}}}}(Zepto) </script> <style type="text/css"> body { background: #F9F9F9; font-size: 14px; line-height: 22px; font-family: Helvetica Neue, Helvetica, Arial; } a { color: #000; text-decoration: underline; } li ul, li ol{ margin: 0; } .anchor { cursor: pointer; } .anchor .anchor_char{ visibility: hidden; padding-left: 0.2em; font-size: 0.9em; opacity: 0.5; } .anchor:hover .anchor_char{ visibility: visible; } .sidebar{ background: #FFF; position: fixed; z-index: 10; top: 0; left: 0; bottom: 0; width: 230px; overflow-y: auto; overflow-x: hidden; padding: 15px 0 30px 30px; border-right: 1px solid #bbb; font-family: "Lucida Grande", "Lucida Sans Unicode", Helvetica, Arial, sans-serif !important; } .sidebar ul{ margin: 0; list-style: none; padding: 0; } .sidebar ul a:hover { text-decoration: underline; color: #333; } .sidebar > ul > li { margin-top: 15px; } .sidebar > ul > li > a { font-weight: bold; } .sidebar ul ul { margin-top: 5px; font-size: 11px; line-height: 14px; } .sidebar ul ul li:before { content: "- "; } .sidebar ul ul li { margin-bottom: 3px; } .sidebar ul ul li a { text-decoration: none; } .toggle_sidebar_button{ display: none; position: fixed; z-index: 11; top: 0; width: 44px; height: 44px; background: #000; background: rgba(0,0,0,0.7); margin-left: 230px; } .toggle_sidebar_button:hover { background: rgba(0,0,0,1); cursor: pointer; } .toggle_sidebar_button .line{ height: 2px; width: 21px; margin-left: 11px; margin-top: 5px; background: #FFF; } .toggle_sidebar_button .line:first-child { margin-top: 15px; } .main_container { width: 100%; padding-left: 260px; margin: 30px; margin-left: 0px; padding-right: 30px; } .main_container p, ul{ margin: 25px 0; } .main_container ul { list-style: circle; font-size: 13px; line-height: 18px; padding-left: 15px; } pre { font-size: 12px; border: 4px solid #bbb; border-top: 0; border-bottom: 0; margin: 0px 0 25px; padding-top: 0px; padding-bottom: 0px; font-family: Monaco, Consolas, "Lucida Console", monospace; line-height: 18px; font-style: normal; background: none; border-radius: 0px; overflow-x: scroll; word-wrap: normal; white-space: pre; } .main_container { width: 840px; } .main_container p, ul, pre { width: 100%; } code { padding: 0px 3px; color: #333; background: #fff; border: 1px solid #ddd; zoom: 1; white-space: nowrap; border-radius: 0; font-family: Monaco, Consolas, "Lucida Console", monospace; font-size: 12px; line-height: 18px; font-style: normal; } em { font-size: 12px; line-height: 18px; } @media (max-width: 820px) { .sidebar { display: none; } .main_container { padding: 0px; width: 100%; } .main_container > *{ padding-left: 10px; padding-right: 10px; } .main_container > ul, .main_container > ol { padding-left: 27px; } .force_show_sidebar .main_container { display: none; } .force_show_sidebar .sidebar { width: 100%; } .force_show_sidebar .sidebar a{ font-size: 1.5em; line-height: 1.5em; } .force_show_sidebar .toggle_sidebar_button { right: 0; } .force_show_sidebar .toggle_sidebar_button .line:first-child, .force_show_sidebar .toggle_sidebar_button .line:last-child { visibility: hidden; } .toggle_sidebar_button { margin-left: 0px; display: block; } pre { font-size: 12px; border: 1px solid #bbb; border-left: 0; border-right: 0; padding: 9px; background: #FFF; } code { word-wrap: break-word; white-space: normal; } } .force_show_sidebar .sidebar { display: block; } .force_show_sidebar .main_container { padding-left: 260px; } .force_show_sidebar .toggle_sidebar_button{ margin-left: 230px; } </style> <script type="text/javascript"> $(function(){ $('.toggle_sidebar_button').on('click', function(){ $('body').toggleClass('force_show_sidebar'); }); // hide sidebar on every click in menu (if small screen) $('.sidebar').find('a').on('click', function(){ $('body').removeClass('force_show_sidebar'); }); // add anchors $.each($('.main_container').find('h1,h2,h3,h4,h5,h6'), function(key, item){ if ($(item).attr('id')) { $(item).addClass('anchor'); $(item).append($('<span class="anchor_char">¶</span>')) $(item).on('click', function(){ window.location = '#' + $(item).attr('id'); }) } }); // remove <code> tag inside of <pre> $.each($('pre > code'), function(key, item){ $(item).parent().html($(item).html()) }) }) </script> </head> <body> <a class="toggle_sidebar_button"> <div class="line"></div> <div class="line"></div> <div class="line"></div> </a> <div class="sidebar"> <!-- toc --> </div> <div class="main_container"> <!-- main_content --> </div> </body> </html>''' def force_text(text): if isinstance(text, unicode): return text else: return text.decode('utf-8') class BackDoc(object): def __init__(self, markdown_converter, template_html, stdin, stdout): self.markdown_converter = markdown_converter self.template_html = force_text(template_html) self.stdin = stdin self.stdout = stdout self.parser = self.get_parser() def run(self, argv): kwargs = self.get_kwargs(argv) self.stdout.write(self.get_result_html(**kwargs)) def get_kwargs(self, argv): parsed = dict(self.parser.parse_args(argv)._get_kwargs()) return self.prepare_kwargs_from_parsed_data(parsed) def prepare_kwargs_from_parsed_data(self, parsed): kwargs = {} kwargs['title'] = force_text(parsed.get('title') or 'Documentation') if parsed.get('source'): kwargs['markdown_src'] = open(parsed['source'], 'r').read() else: kwargs['markdown_src'] = self.stdin.read() kwargs['markdown_src'] = force_text(kwargs['markdown_src'] or '') return kwargs def get_result_html(self, title, markdown_src): response = self.get_converted_to_html_response(markdown_src) return ( self.template_html.replace('<!-- title -->', title) .replace('<!-- toc -->', response.toc_html and force_text(response.toc_html) or '') .replace('<!-- main_content -->', force_text(response)) ) def get_converted_to_html_response(self, markdown_src): return self.markdown_converter.convert(markdown_src) def get_parser(self): parser = argparse.ArgumentParser() parser.add_argument( '-t', '--title', help='Documentation title header', required=False, ) parser.add_argument( '-s', '--source', help='Markdown source file path', required=False, ) return parser if __name__ == '__main__': BackDoc( markdown_converter=Markdown(extras=['toc']), template_html=template_html, stdin=sys.stdin, stdout=sys.stdout ).run(argv=sys.argv[1:])
chibisov/drf-extensions
docs/backdoc.py
_regex_from_encoded_pattern
python
def _regex_from_encoded_pattern(s): """'foo' -> re.compile(re.escape('foo')) '/foo/' -> re.compile('foo') '/foo/i' -> re.compile('foo', re.I) """ if s.startswith('/') and s.rfind('/') != 0: # Parse it: /PATTERN/FLAGS idx = s.rfind('/') pattern, flags_str = s[1:idx], s[idx+1:] flag_from_char = { "i": re.IGNORECASE, "l": re.LOCALE, "s": re.DOTALL, "m": re.MULTILINE, "u": re.UNICODE, } flags = 0 for char in flags_str: try: flags |= flag_from_char[char] except KeyError: raise ValueError("unsupported regex flag: '%s' in '%s' " "(must be one of '%s')" % (char, s, ''.join(list(flag_from_char.keys())))) return re.compile(s[1:idx], flags) else: # not an encoded regex return re.compile(re.escape(s))
foo' -> re.compile(re.escape('foo')) '/foo/' -> re.compile('foo') '/foo/i' -> re.compile('foo', re.I)
train
https://github.com/chibisov/drf-extensions/blob/1d28a4b28890eab5cd19e93e042f8590c8c2fb8b/docs/backdoc.py#L1983-L2009
null
# -*- coding: utf-8 -*- #!/usr/bin/env python """ Backdoc is a tool for backbone-like documentation generation. Backdoc main goal is to help to generate one page documentation from one markdown source file. https://github.com/chibisov/backdoc """ import sys import argparse # -*- coding: utf-8 -*- #!/usr/bin/env python # Copyright (c) 2012 Trent Mick. # Copyright (c) 2007-2008 ActiveState Corp. # License: MIT (http://www.opensource.org/licenses/mit-license.php) r"""A fast and complete Python implementation of Markdown. [from http://daringfireball.net/projects/markdown/] > Markdown is a text-to-HTML filter; it translates an easy-to-read / > easy-to-write structured text format into HTML. Markdown's text > format is most similar to that of plain text email, and supports > features such as headers, *emphasis*, code blocks, blockquotes, and > links. > > Markdown's syntax is designed not as a generic markup language, but > specifically to serve as a front-end to (X)HTML. You can use span-level > HTML tags anywhere in a Markdown document, and you can use block level > HTML tags (like <div> and <table> as well). Module usage: >>> import markdown2 >>> markdown2.markdown("*boo!*") # or use `html = markdown_path(PATH)` u'<p><em>boo!</em></p>\n' >>> markdowner = Markdown() >>> markdowner.convert("*boo!*") u'<p><em>boo!</em></p>\n' >>> markdowner.convert("**boom!**") u'<p><strong>boom!</strong></p>\n' This implementation of Markdown implements the full "core" syntax plus a number of extras (e.g., code syntax coloring, footnotes) as described on <https://github.com/trentm/python-markdown2/wiki/Extras>. """ cmdln_desc = """A fast and complete Python implementation of Markdown, a text-to-HTML conversion tool for web writers. Supported extra syntax options (see -x|--extras option below and see <https://github.com/trentm/python-markdown2/wiki/Extras> for details): * code-friendly: Disable _ and __ for em and strong. * cuddled-lists: Allow lists to be cuddled to the preceding paragraph. * fenced-code-blocks: Allows a code block to not have to be indented by fencing it with '```' on a line before and after. Based on <http://github.github.com/github-flavored-markdown/> with support for syntax highlighting. * footnotes: Support footnotes as in use on daringfireball.net and implemented in other Markdown processors (tho not in Markdown.pl v1.0.1). * header-ids: Adds "id" attributes to headers. The id value is a slug of the header text. * html-classes: Takes a dict mapping html tag names (lowercase) to a string to use for a "class" tag attribute. Currently only supports "pre" and "code" tags. Add an issue if you require this for other tags. * markdown-in-html: Allow the use of `markdown="1"` in a block HTML tag to have markdown processing be done on its contents. Similar to <http://michelf.com/projects/php-markdown/extra/#markdown-attr> but with some limitations. * metadata: Extract metadata from a leading '---'-fenced block. See <https://github.com/trentm/python-markdown2/issues/77> for details. * nofollow: Add `rel="nofollow"` to add `<a>` tags with an href. See <http://en.wikipedia.org/wiki/Nofollow>. * pyshell: Treats unindented Python interactive shell sessions as <code> blocks. * link-patterns: Auto-link given regex patterns in text (e.g. bug number references, revision number references). * smarty-pants: Replaces ' and " with curly quotation marks or curly apostrophes. Replaces --, ---, ..., and . . . with en dashes, em dashes, and ellipses. * toc: The returned HTML string gets a new "toc_html" attribute which is a Table of Contents for the document. (experimental) * xml: Passes one-liner processing instructions and namespaced XML tags. * wiki-tables: Google Code Wiki-style tables. See <http://code.google.com/p/support/wiki/WikiSyntax#Tables>. """ # Dev Notes: # - Python's regex syntax doesn't have '\z', so I'm using '\Z'. I'm # not yet sure if there implications with this. Compare 'pydoc sre' # and 'perldoc perlre'. __version_info__ = (2, 1, 1) __version__ = '.'.join(map(str, __version_info__)) __author__ = "Trent Mick" import os import sys from pprint import pprint import re import logging try: from hashlib import md5 except ImportError: from md5 import md5 import optparse from random import random, randint import codecs #---- Python version compat try: from urllib.parse import quote # python3 except ImportError: from urllib import quote # python2 if sys.version_info[:2] < (2,4): from sets import Set as set def reversed(sequence): for i in sequence[::-1]: yield i # Use `bytes` for byte strings and `unicode` for unicode strings (str in Py3). if sys.version_info[0] <= 2: py3 = False try: bytes except NameError: bytes = str base_string_type = basestring elif sys.version_info[0] >= 3: py3 = True unicode = str base_string_type = str #---- globals DEBUG = False log = logging.getLogger("markdown") DEFAULT_TAB_WIDTH = 4 SECRET_SALT = bytes(randint(0, 1000000)) def _hash_text(s): return 'md5-' + md5(SECRET_SALT + s.encode("utf-8")).hexdigest() # Table of hash values for escaped characters: g_escape_table = dict([(ch, _hash_text(ch)) for ch in '\\`*_{}[]()>#+-.!']) #---- exceptions class MarkdownError(Exception): pass #---- public api def markdown_path(path, encoding="utf-8", html4tags=False, tab_width=DEFAULT_TAB_WIDTH, safe_mode=None, extras=None, link_patterns=None, use_file_vars=False): fp = codecs.open(path, 'r', encoding) text = fp.read() fp.close() return Markdown(html4tags=html4tags, tab_width=tab_width, safe_mode=safe_mode, extras=extras, link_patterns=link_patterns, use_file_vars=use_file_vars).convert(text) def markdown(text, html4tags=False, tab_width=DEFAULT_TAB_WIDTH, safe_mode=None, extras=None, link_patterns=None, use_file_vars=False): return Markdown(html4tags=html4tags, tab_width=tab_width, safe_mode=safe_mode, extras=extras, link_patterns=link_patterns, use_file_vars=use_file_vars).convert(text) class Markdown(object): # The dict of "extras" to enable in processing -- a mapping of # extra name to argument for the extra. Most extras do not have an # argument, in which case the value is None. # # This can be set via (a) subclassing and (b) the constructor # "extras" argument. extras = None urls = None titles = None html_blocks = None html_spans = None html_removed_text = "[HTML_REMOVED]" # for compat with markdown.py # Used to track when we're inside an ordered or unordered list # (see _ProcessListItems() for details): list_level = 0 _ws_only_line_re = re.compile(r"^[ \t]+$", re.M) def __init__(self, html4tags=False, tab_width=4, safe_mode=None, extras=None, link_patterns=None, use_file_vars=False): if html4tags: self.empty_element_suffix = ">" else: self.empty_element_suffix = " />" self.tab_width = tab_width # For compatibility with earlier markdown2.py and with # markdown.py's safe_mode being a boolean, # safe_mode == True -> "replace" if safe_mode is True: self.safe_mode = "replace" else: self.safe_mode = safe_mode # Massaging and building the "extras" info. if self.extras is None: self.extras = {} elif not isinstance(self.extras, dict): self.extras = dict([(e, None) for e in self.extras]) if extras: if not isinstance(extras, dict): extras = dict([(e, None) for e in extras]) self.extras.update(extras) assert isinstance(self.extras, dict) if "toc" in self.extras and not "header-ids" in self.extras: self.extras["header-ids"] = None # "toc" implies "header-ids" self._instance_extras = self.extras.copy() self.link_patterns = link_patterns self.use_file_vars = use_file_vars self._outdent_re = re.compile(r'^(\t|[ ]{1,%d})' % tab_width, re.M) self._escape_table = g_escape_table.copy() if "smarty-pants" in self.extras: self._escape_table['"'] = _hash_text('"') self._escape_table["'"] = _hash_text("'") def reset(self): self.urls = {} self.titles = {} self.html_blocks = {} self.html_spans = {} self.list_level = 0 self.extras = self._instance_extras.copy() if "footnotes" in self.extras: self.footnotes = {} self.footnote_ids = [] if "header-ids" in self.extras: self._count_from_header_id = {} # no `defaultdict` in Python 2.4 if "metadata" in self.extras: self.metadata = {} # Per <https://developer.mozilla.org/en-US/docs/HTML/Element/a> "rel" # should only be used in <a> tags with an "href" attribute. _a_nofollow = re.compile(r"<(a)([^>]*href=)", re.IGNORECASE) def convert(self, text): """Convert the given text.""" # Main function. The order in which other subs are called here is # essential. Link and image substitutions need to happen before # _EscapeSpecialChars(), so that any *'s or _'s in the <a> # and <img> tags get encoded. # Clear the global hashes. If we don't clear these, you get conflicts # from other articles when generating a page which contains more than # one article (e.g. an index page that shows the N most recent # articles): self.reset() if not isinstance(text, unicode): #TODO: perhaps shouldn't presume UTF-8 for string input? text = unicode(text, 'utf-8') if self.use_file_vars: # Look for emacs-style file variable hints. emacs_vars = self._get_emacs_vars(text) if "markdown-extras" in emacs_vars: splitter = re.compile("[ ,]+") for e in splitter.split(emacs_vars["markdown-extras"]): if '=' in e: ename, earg = e.split('=', 1) try: earg = int(earg) except ValueError: pass else: ename, earg = e, None self.extras[ename] = earg # Standardize line endings: text = re.sub("\r\n|\r", "\n", text) # Make sure $text ends with a couple of newlines: text += "\n\n" # Convert all tabs to spaces. text = self._detab(text) # Strip any lines consisting only of spaces and tabs. # This makes subsequent regexen easier to write, because we can # match consecutive blank lines with /\n+/ instead of something # contorted like /[ \t]*\n+/ . text = self._ws_only_line_re.sub("", text) # strip metadata from head and extract if "metadata" in self.extras: text = self._extract_metadata(text) text = self.preprocess(text) if self.safe_mode: text = self._hash_html_spans(text) # Turn block-level HTML blocks into hash entries text = self._hash_html_blocks(text, raw=True) # Strip link definitions, store in hashes. if "footnotes" in self.extras: # Must do footnotes first because an unlucky footnote defn # looks like a link defn: # [^4]: this "looks like a link defn" text = self._strip_footnote_definitions(text) text = self._strip_link_definitions(text) text = self._run_block_gamut(text) if "footnotes" in self.extras: text = self._add_footnotes(text) text = self.postprocess(text) text = self._unescape_special_chars(text) if self.safe_mode: text = self._unhash_html_spans(text) if "nofollow" in self.extras: text = self._a_nofollow.sub(r'<\1 rel="nofollow"\2', text) text += "\n" rv = UnicodeWithAttrs(text) if "toc" in self.extras: rv._toc = self._toc if "metadata" in self.extras: rv.metadata = self.metadata return rv def postprocess(self, text): """A hook for subclasses to do some postprocessing of the html, if desired. This is called before unescaping of special chars and unhashing of raw HTML spans. """ return text def preprocess(self, text): """A hook for subclasses to do some preprocessing of the Markdown, if desired. This is called after basic formatting of the text, but prior to any extras, safe mode, etc. processing. """ return text # Is metadata if the content starts with '---'-fenced `key: value` # pairs. E.g. (indented for presentation): # --- # foo: bar # another-var: blah blah # --- _metadata_pat = re.compile("""^---[ \t]*\n((?:[ \t]*[^ \t:]+[ \t]*:[^\n]*\n)+)---[ \t]*\n""") def _extract_metadata(self, text): # fast test if not text.startswith("---"): return text match = self._metadata_pat.match(text) if not match: return text tail = text[len(match.group(0)):] metadata_str = match.group(1).strip() for line in metadata_str.split('\n'): key, value = line.split(':', 1) self.metadata[key.strip()] = value.strip() return tail _emacs_oneliner_vars_pat = re.compile(r"-\*-\s*([^\r\n]*?)\s*-\*-", re.UNICODE) # This regular expression is intended to match blocks like this: # PREFIX Local Variables: SUFFIX # PREFIX mode: Tcl SUFFIX # PREFIX End: SUFFIX # Some notes: # - "[ \t]" is used instead of "\s" to specifically exclude newlines # - "(\r\n|\n|\r)" is used instead of "$" because the sre engine does # not like anything other than Unix-style line terminators. _emacs_local_vars_pat = re.compile(r"""^ (?P<prefix>(?:[^\r\n|\n|\r])*?) [\ \t]*Local\ Variables:[\ \t]* (?P<suffix>.*?)(?:\r\n|\n|\r) (?P<content>.*?\1End:) """, re.IGNORECASE | re.MULTILINE | re.DOTALL | re.VERBOSE) def _get_emacs_vars(self, text): """Return a dictionary of emacs-style local variables. Parsing is done loosely according to this spec (and according to some in-practice deviations from this): http://www.gnu.org/software/emacs/manual/html_node/emacs/Specifying-File-Variables.html#Specifying-File-Variables """ emacs_vars = {} SIZE = pow(2, 13) # 8kB # Search near the start for a '-*-'-style one-liner of variables. head = text[:SIZE] if "-*-" in head: match = self._emacs_oneliner_vars_pat.search(head) if match: emacs_vars_str = match.group(1) assert '\n' not in emacs_vars_str emacs_var_strs = [s.strip() for s in emacs_vars_str.split(';') if s.strip()] if len(emacs_var_strs) == 1 and ':' not in emacs_var_strs[0]: # While not in the spec, this form is allowed by emacs: # -*- Tcl -*- # where the implied "variable" is "mode". This form # is only allowed if there are no other variables. emacs_vars["mode"] = emacs_var_strs[0].strip() else: for emacs_var_str in emacs_var_strs: try: variable, value = emacs_var_str.strip().split(':', 1) except ValueError: log.debug("emacs variables error: malformed -*- " "line: %r", emacs_var_str) continue # Lowercase the variable name because Emacs allows "Mode" # or "mode" or "MoDe", etc. emacs_vars[variable.lower()] = value.strip() tail = text[-SIZE:] if "Local Variables" in tail: match = self._emacs_local_vars_pat.search(tail) if match: prefix = match.group("prefix") suffix = match.group("suffix") lines = match.group("content").splitlines(0) #print "prefix=%r, suffix=%r, content=%r, lines: %s"\ # % (prefix, suffix, match.group("content"), lines) # Validate the Local Variables block: proper prefix and suffix # usage. for i, line in enumerate(lines): if not line.startswith(prefix): log.debug("emacs variables error: line '%s' " "does not use proper prefix '%s'" % (line, prefix)) return {} # Don't validate suffix on last line. Emacs doesn't care, # neither should we. if i != len(lines)-1 and not line.endswith(suffix): log.debug("emacs variables error: line '%s' " "does not use proper suffix '%s'" % (line, suffix)) return {} # Parse out one emacs var per line. continued_for = None for line in lines[:-1]: # no var on the last line ("PREFIX End:") if prefix: line = line[len(prefix):] # strip prefix if suffix: line = line[:-len(suffix)] # strip suffix line = line.strip() if continued_for: variable = continued_for if line.endswith('\\'): line = line[:-1].rstrip() else: continued_for = None emacs_vars[variable] += ' ' + line else: try: variable, value = line.split(':', 1) except ValueError: log.debug("local variables error: missing colon " "in local variables entry: '%s'" % line) continue # Do NOT lowercase the variable name, because Emacs only # allows "mode" (and not "Mode", "MoDe", etc.) in this block. value = value.strip() if value.endswith('\\'): value = value[:-1].rstrip() continued_for = variable else: continued_for = None emacs_vars[variable] = value # Unquote values. for var, val in list(emacs_vars.items()): if len(val) > 1 and (val.startswith('"') and val.endswith('"') or val.startswith('"') and val.endswith('"')): emacs_vars[var] = val[1:-1] return emacs_vars # Cribbed from a post by Bart Lateur: # <http://www.nntp.perl.org/group/perl.macperl.anyperl/154> _detab_re = re.compile(r'(.*?)\t', re.M) def _detab_sub(self, match): g1 = match.group(1) return g1 + (' ' * (self.tab_width - len(g1) % self.tab_width)) def _detab(self, text): r"""Remove (leading?) tabs from a file. >>> m = Markdown() >>> m._detab("\tfoo") ' foo' >>> m._detab(" \tfoo") ' foo' >>> m._detab("\t foo") ' foo' >>> m._detab(" foo") ' foo' >>> m._detab(" foo\n\tbar\tblam") ' foo\n bar blam' """ if '\t' not in text: return text return self._detab_re.subn(self._detab_sub, text)[0] # I broke out the html5 tags here and add them to _block_tags_a and # _block_tags_b. This way html5 tags are easy to keep track of. _html5tags = '|article|aside|header|hgroup|footer|nav|section|figure|figcaption' _block_tags_a = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del' _block_tags_a += _html5tags _strict_tag_block_re = re.compile(r""" ( # save in \1 ^ # start of line (with re.M) <(%s) # start tag = \2 \b # word break (.*\n)*? # any number of lines, minimally matching </\2> # the matching end tag [ \t]* # trailing spaces/tabs (?=\n+|\Z) # followed by a newline or end of document ) """ % _block_tags_a, re.X | re.M) _block_tags_b = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math' _block_tags_b += _html5tags _liberal_tag_block_re = re.compile(r""" ( # save in \1 ^ # start of line (with re.M) <(%s) # start tag = \2 \b # word break (.*\n)*? # any number of lines, minimally matching .*</\2> # the matching end tag [ \t]* # trailing spaces/tabs (?=\n+|\Z) # followed by a newline or end of document ) """ % _block_tags_b, re.X | re.M) _html_markdown_attr_re = re.compile( r'''\s+markdown=("1"|'1')''') def _hash_html_block_sub(self, match, raw=False): html = match.group(1) if raw and self.safe_mode: html = self._sanitize_html(html) elif 'markdown-in-html' in self.extras and 'markdown=' in html: first_line = html.split('\n', 1)[0] m = self._html_markdown_attr_re.search(first_line) if m: lines = html.split('\n') middle = '\n'.join(lines[1:-1]) last_line = lines[-1] first_line = first_line[:m.start()] + first_line[m.end():] f_key = _hash_text(first_line) self.html_blocks[f_key] = first_line l_key = _hash_text(last_line) self.html_blocks[l_key] = last_line return ''.join(["\n\n", f_key, "\n\n", middle, "\n\n", l_key, "\n\n"]) key = _hash_text(html) self.html_blocks[key] = html return "\n\n" + key + "\n\n" def _hash_html_blocks(self, text, raw=False): """Hashify HTML blocks We only want to do this for block-level HTML tags, such as headers, lists, and tables. That's because we still want to wrap <p>s around "paragraphs" that are wrapped in non-block-level tags, such as anchors, phrase emphasis, and spans. The list of tags we're looking for is hard-coded. @param raw {boolean} indicates if these are raw HTML blocks in the original source. It makes a difference in "safe" mode. """ if '<' not in text: return text # Pass `raw` value into our calls to self._hash_html_block_sub. hash_html_block_sub = _curry(self._hash_html_block_sub, raw=raw) # First, look for nested blocks, e.g.: # <div> # <div> # tags for inner block must be indented. # </div> # </div> # # The outermost tags must start at the left margin for this to match, and # the inner nested divs must be indented. # We need to do this before the next, more liberal match, because the next # match will start at the first `<div>` and stop at the first `</div>`. text = self._strict_tag_block_re.sub(hash_html_block_sub, text) # Now match more liberally, simply from `\n<tag>` to `</tag>\n` text = self._liberal_tag_block_re.sub(hash_html_block_sub, text) # Special case just for <hr />. It was easier to make a special # case than to make the other regex more complicated. if "<hr" in text: _hr_tag_re = _hr_tag_re_from_tab_width(self.tab_width) text = _hr_tag_re.sub(hash_html_block_sub, text) # Special case for standalone HTML comments: if "<!--" in text: start = 0 while True: # Delimiters for next comment block. try: start_idx = text.index("<!--", start) except ValueError: break try: end_idx = text.index("-->", start_idx) + 3 except ValueError: break # Start position for next comment block search. start = end_idx # Validate whitespace before comment. if start_idx: # - Up to `tab_width - 1` spaces before start_idx. for i in range(self.tab_width - 1): if text[start_idx - 1] != ' ': break start_idx -= 1 if start_idx == 0: break # - Must be preceded by 2 newlines or hit the start of # the document. if start_idx == 0: pass elif start_idx == 1 and text[0] == '\n': start_idx = 0 # to match minute detail of Markdown.pl regex elif text[start_idx-2:start_idx] == '\n\n': pass else: break # Validate whitespace after comment. # - Any number of spaces and tabs. while end_idx < len(text): if text[end_idx] not in ' \t': break end_idx += 1 # - Must be following by 2 newlines or hit end of text. if text[end_idx:end_idx+2] not in ('', '\n', '\n\n'): continue # Escape and hash (must match `_hash_html_block_sub`). html = text[start_idx:end_idx] if raw and self.safe_mode: html = self._sanitize_html(html) key = _hash_text(html) self.html_blocks[key] = html text = text[:start_idx] + "\n\n" + key + "\n\n" + text[end_idx:] if "xml" in self.extras: # Treat XML processing instructions and namespaced one-liner # tags as if they were block HTML tags. E.g., if standalone # (i.e. are their own paragraph), the following do not get # wrapped in a <p> tag: # <?foo bar?> # # <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="chapter_1.md"/> _xml_oneliner_re = _xml_oneliner_re_from_tab_width(self.tab_width) text = _xml_oneliner_re.sub(hash_html_block_sub, text) return text def _strip_link_definitions(self, text): # Strips link definitions from text, stores the URLs and titles in # hash references. less_than_tab = self.tab_width - 1 # Link defs are in the form: # [id]: url "optional title" _link_def_re = re.compile(r""" ^[ ]{0,%d}\[(.+)\]: # id = \1 [ \t]* \n? # maybe *one* newline [ \t]* <?(.+?)>? # url = \2 [ \t]* (?: \n? # maybe one newline [ \t]* (?<=\s) # lookbehind for whitespace ['"(] ([^\n]*) # title = \3 ['")] [ \t]* )? # title is optional (?:\n+|\Z) """ % less_than_tab, re.X | re.M | re.U) return _link_def_re.sub(self._extract_link_def_sub, text) def _extract_link_def_sub(self, match): id, url, title = match.groups() key = id.lower() # Link IDs are case-insensitive self.urls[key] = self._encode_amps_and_angles(url) if title: self.titles[key] = title return "" def _extract_footnote_def_sub(self, match): id, text = match.groups() text = _dedent(text, skip_first_line=not text.startswith('\n')).strip() normed_id = re.sub(r'\W', '-', id) # Ensure footnote text ends with a couple newlines (for some # block gamut matches). self.footnotes[normed_id] = text + "\n\n" return "" def _strip_footnote_definitions(self, text): """A footnote definition looks like this: [^note-id]: Text of the note. May include one or more indented paragraphs. Where, - The 'note-id' can be pretty much anything, though typically it is the number of the footnote. - The first paragraph may start on the next line, like so: [^note-id]: Text of the note. """ less_than_tab = self.tab_width - 1 footnote_def_re = re.compile(r''' ^[ ]{0,%d}\[\^(.+)\]: # id = \1 [ \t]* ( # footnote text = \2 # First line need not start with the spaces. (?:\s*.*\n+) (?: (?:[ ]{%d} | \t) # Subsequent lines must be indented. .*\n+ )* ) # Lookahead for non-space at line-start, or end of doc. (?:(?=^[ ]{0,%d}\S)|\Z) ''' % (less_than_tab, self.tab_width, self.tab_width), re.X | re.M) return footnote_def_re.sub(self._extract_footnote_def_sub, text) _hr_data = [ ('*', re.compile(r"^[ ]{0,3}\*(.*?)$", re.M)), ('-', re.compile(r"^[ ]{0,3}\-(.*?)$", re.M)), ('_', re.compile(r"^[ ]{0,3}\_(.*?)$", re.M)), ] def _run_block_gamut(self, text): # These are all the transformations that form block-level # tags like paragraphs, headers, and list items. if "fenced-code-blocks" in self.extras: text = self._do_fenced_code_blocks(text) text = self._do_headers(text) # Do Horizontal Rules: # On the number of spaces in horizontal rules: The spec is fuzzy: "If # you wish, you may use spaces between the hyphens or asterisks." # Markdown.pl 1.0.1's hr regexes limit the number of spaces between the # hr chars to one or two. We'll reproduce that limit here. hr = "\n<hr"+self.empty_element_suffix+"\n" for ch, regex in self._hr_data: if ch in text: for m in reversed(list(regex.finditer(text))): tail = m.group(1).rstrip() if not tail.strip(ch + ' ') and tail.count(" ") == 0: start, end = m.span() text = text[:start] + hr + text[end:] text = self._do_lists(text) if "pyshell" in self.extras: text = self._prepare_pyshell_blocks(text) if "wiki-tables" in self.extras: text = self._do_wiki_tables(text) text = self._do_code_blocks(text) text = self._do_block_quotes(text) # We already ran _HashHTMLBlocks() before, in Markdown(), but that # was to escape raw HTML in the original Markdown source. This time, # we're escaping the markup we've just created, so that we don't wrap # <p> tags around block-level tags. text = self._hash_html_blocks(text) text = self._form_paragraphs(text) return text def _pyshell_block_sub(self, match): lines = match.group(0).splitlines(0) _dedentlines(lines) indent = ' ' * self.tab_width s = ('\n' # separate from possible cuddled paragraph + indent + ('\n'+indent).join(lines) + '\n\n') return s def _prepare_pyshell_blocks(self, text): """Ensure that Python interactive shell sessions are put in code blocks -- even if not properly indented. """ if ">>>" not in text: return text less_than_tab = self.tab_width - 1 _pyshell_block_re = re.compile(r""" ^([ ]{0,%d})>>>[ ].*\n # first line ^(\1.*\S+.*\n)* # any number of subsequent lines ^\n # ends with a blank line """ % less_than_tab, re.M | re.X) return _pyshell_block_re.sub(self._pyshell_block_sub, text) def _wiki_table_sub(self, match): ttext = match.group(0).strip() #print 'wiki table: %r' % match.group(0) rows = [] for line in ttext.splitlines(0): line = line.strip()[2:-2].strip() row = [c.strip() for c in re.split(r'(?<!\\)\|\|', line)] rows.append(row) #pprint(rows) hlines = ['<table>', '<tbody>'] for row in rows: hrow = ['<tr>'] for cell in row: hrow.append('<td>') hrow.append(self._run_span_gamut(cell)) hrow.append('</td>') hrow.append('</tr>') hlines.append(''.join(hrow)) hlines += ['</tbody>', '</table>'] return '\n'.join(hlines) + '\n' def _do_wiki_tables(self, text): # Optimization. if "||" not in text: return text less_than_tab = self.tab_width - 1 wiki_table_re = re.compile(r''' (?:(?<=\n\n)|\A\n?) # leading blank line ^([ ]{0,%d})\|\|.+?\|\|[ ]*\n # first line (^\1\|\|.+?\|\|\n)* # any number of subsequent lines ''' % less_than_tab, re.M | re.X) return wiki_table_re.sub(self._wiki_table_sub, text) def _run_span_gamut(self, text): # These are all the transformations that occur *within* block-level # tags like paragraphs, headers, and list items. text = self._do_code_spans(text) text = self._escape_special_chars(text) # Process anchor and image tags. text = self._do_links(text) # Make links out of things like `<http://example.com/>` # Must come after _do_links(), because you can use < and > # delimiters in inline links like [this](<url>). text = self._do_auto_links(text) if "link-patterns" in self.extras: text = self._do_link_patterns(text) text = self._encode_amps_and_angles(text) text = self._do_italics_and_bold(text) if "smarty-pants" in self.extras: text = self._do_smart_punctuation(text) # Do hard breaks: text = re.sub(r" {2,}\n", " <br%s\n" % self.empty_element_suffix, text) return text # "Sorta" because auto-links are identified as "tag" tokens. _sorta_html_tokenize_re = re.compile(r""" ( # tag </? (?:\w+) # tag name (?:\s+(?:[\w-]+:)?[\w-]+=(?:".*?"|'.*?'))* # attributes \s*/?> | # auto-link (e.g., <http://www.activestate.com/>) <\w+[^>]*> | <!--.*?--> # comment | <\?.*?\?> # processing instruction ) """, re.X) def _escape_special_chars(self, text): # Python markdown note: the HTML tokenization here differs from # that in Markdown.pl, hence the behaviour for subtle cases can # differ (I believe the tokenizer here does a better job because # it isn't susceptible to unmatched '<' and '>' in HTML tags). # Note, however, that '>' is not allowed in an auto-link URL # here. escaped = [] is_html_markup = False for token in self._sorta_html_tokenize_re.split(text): if is_html_markup: # Within tags/HTML-comments/auto-links, encode * and _ # so they don't conflict with their use in Markdown for # italics and strong. We're replacing each such # character with its corresponding MD5 checksum value; # this is likely overkill, but it should prevent us from # colliding with the escape values by accident. escaped.append(token.replace('*', self._escape_table['*']) .replace('_', self._escape_table['_'])) else: escaped.append(self._encode_backslash_escapes(token)) is_html_markup = not is_html_markup return ''.join(escaped) def _hash_html_spans(self, text): # Used for safe_mode. def _is_auto_link(s): if ':' in s and self._auto_link_re.match(s): return True elif '@' in s and self._auto_email_link_re.match(s): return True return False tokens = [] is_html_markup = False for token in self._sorta_html_tokenize_re.split(text): if is_html_markup and not _is_auto_link(token): sanitized = self._sanitize_html(token) key = _hash_text(sanitized) self.html_spans[key] = sanitized tokens.append(key) else: tokens.append(token) is_html_markup = not is_html_markup return ''.join(tokens) def _unhash_html_spans(self, text): for key, sanitized in list(self.html_spans.items()): text = text.replace(key, sanitized) return text def _sanitize_html(self, s): if self.safe_mode == "replace": return self.html_removed_text elif self.safe_mode == "escape": replacements = [ ('&', '&amp;'), ('<', '&lt;'), ('>', '&gt;'), ] for before, after in replacements: s = s.replace(before, after) return s else: raise MarkdownError("invalid value for 'safe_mode': %r (must be " "'escape' or 'replace')" % self.safe_mode) _tail_of_inline_link_re = re.compile(r''' # Match tail of: [text](/url/) or [text](/url/ "title") \( # literal paren [ \t]* (?P<url> # \1 <.*?> | .*? ) [ \t]* ( # \2 (['"]) # quote char = \3 (?P<title>.*?) \3 # matching quote )? # title is optional \) ''', re.X | re.S) _tail_of_reference_link_re = re.compile(r''' # Match tail of: [text][id] [ ]? # one optional space (?:\n[ ]*)? # one optional newline followed by spaces \[ (?P<id>.*?) \] ''', re.X | re.S) def _do_links(self, text): """Turn Markdown link shortcuts into XHTML <a> and <img> tags. This is a combination of Markdown.pl's _DoAnchors() and _DoImages(). They are done together because that simplified the approach. It was necessary to use a different approach than Markdown.pl because of the lack of atomic matching support in Python's regex engine used in $g_nested_brackets. """ MAX_LINK_TEXT_SENTINEL = 3000 # markdown2 issue 24 # `anchor_allowed_pos` is used to support img links inside # anchors, but not anchors inside anchors. An anchor's start # pos must be `>= anchor_allowed_pos`. anchor_allowed_pos = 0 curr_pos = 0 while True: # Handle the next link. # The next '[' is the start of: # - an inline anchor: [text](url "title") # - a reference anchor: [text][id] # - an inline img: ![text](url "title") # - a reference img: ![text][id] # - a footnote ref: [^id] # (Only if 'footnotes' extra enabled) # - a footnote defn: [^id]: ... # (Only if 'footnotes' extra enabled) These have already # been stripped in _strip_footnote_definitions() so no # need to watch for them. # - a link definition: [id]: url "title" # These have already been stripped in # _strip_link_definitions() so no need to watch for them. # - not markup: [...anything else... try: start_idx = text.index('[', curr_pos) except ValueError: break text_length = len(text) # Find the matching closing ']'. # Markdown.pl allows *matching* brackets in link text so we # will here too. Markdown.pl *doesn't* currently allow # matching brackets in img alt text -- we'll differ in that # regard. bracket_depth = 0 for p in range(start_idx+1, min(start_idx+MAX_LINK_TEXT_SENTINEL, text_length)): ch = text[p] if ch == ']': bracket_depth -= 1 if bracket_depth < 0: break elif ch == '[': bracket_depth += 1 else: # Closing bracket not found within sentinel length. # This isn't markup. curr_pos = start_idx + 1 continue link_text = text[start_idx+1:p] # Possibly a footnote ref? if "footnotes" in self.extras and link_text.startswith("^"): normed_id = re.sub(r'\W', '-', link_text[1:]) if normed_id in self.footnotes: self.footnote_ids.append(normed_id) result = '<sup class="footnote-ref" id="fnref-%s">' \ '<a href="#fn-%s">%s</a></sup>' \ % (normed_id, normed_id, len(self.footnote_ids)) text = text[:start_idx] + result + text[p+1:] else: # This id isn't defined, leave the markup alone. curr_pos = p+1 continue # Now determine what this is by the remainder. p += 1 if p == text_length: return text # Inline anchor or img? if text[p] == '(': # attempt at perf improvement match = self._tail_of_inline_link_re.match(text, p) if match: # Handle an inline anchor or img. is_img = start_idx > 0 and text[start_idx-1] == "!" if is_img: start_idx -= 1 url, title = match.group("url"), match.group("title") if url and url[0] == '<': url = url[1:-1] # '<url>' -> 'url' # We've got to encode these to avoid conflicting # with italics/bold. url = url.replace('*', self._escape_table['*']) \ .replace('_', self._escape_table['_']) if title: title_str = ' title="%s"' % ( _xml_escape_attr(title) .replace('*', self._escape_table['*']) .replace('_', self._escape_table['_'])) else: title_str = '' if is_img: result = '<img src="%s" alt="%s"%s%s' \ % (url.replace('"', '&quot;'), _xml_escape_attr(link_text), title_str, self.empty_element_suffix) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) curr_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] elif start_idx >= anchor_allowed_pos: result_head = '<a href="%s"%s>' % (url, title_str) result = '%s%s</a>' % (result_head, link_text) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) # <img> allowed from curr_pos on, <a> from # anchor_allowed_pos on. curr_pos = start_idx + len(result_head) anchor_allowed_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] else: # Anchor not allowed here. curr_pos = start_idx + 1 continue # Reference anchor or img? else: match = self._tail_of_reference_link_re.match(text, p) if match: # Handle a reference-style anchor or img. is_img = start_idx > 0 and text[start_idx-1] == "!" if is_img: start_idx -= 1 link_id = match.group("id").lower() if not link_id: link_id = link_text.lower() # for links like [this][] if link_id in self.urls: url = self.urls[link_id] # We've got to encode these to avoid conflicting # with italics/bold. url = url.replace('*', self._escape_table['*']) \ .replace('_', self._escape_table['_']) title = self.titles.get(link_id) if title: before = title title = _xml_escape_attr(title) \ .replace('*', self._escape_table['*']) \ .replace('_', self._escape_table['_']) title_str = ' title="%s"' % title else: title_str = '' if is_img: result = '<img src="%s" alt="%s"%s%s' \ % (url.replace('"', '&quot;'), link_text.replace('"', '&quot;'), title_str, self.empty_element_suffix) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) curr_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] elif start_idx >= anchor_allowed_pos: result = '<a href="%s"%s>%s</a>' \ % (url, title_str, link_text) result_head = '<a href="%s"%s>' % (url, title_str) result = '%s%s</a>' % (result_head, link_text) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) # <img> allowed from curr_pos on, <a> from # anchor_allowed_pos on. curr_pos = start_idx + len(result_head) anchor_allowed_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] else: # Anchor not allowed here. curr_pos = start_idx + 1 else: # This id isn't defined, leave the markup alone. curr_pos = match.end() continue # Otherwise, it isn't markup. curr_pos = start_idx + 1 return text def header_id_from_text(self, text, prefix, n): """Generate a header id attribute value from the given header HTML content. This is only called if the "header-ids" extra is enabled. Subclasses may override this for different header ids. @param text {str} The text of the header tag @param prefix {str} The requested prefix for header ids. This is the value of the "header-ids" extra key, if any. Otherwise, None. @param n {int} The <hN> tag number, i.e. `1` for an <h1> tag. @returns {str} The value for the header tag's "id" attribute. Return None to not have an id attribute and to exclude this header from the TOC (if the "toc" extra is specified). """ header_id = _slugify(text) if prefix and isinstance(prefix, base_string_type): header_id = prefix + '-' + header_id if header_id in self._count_from_header_id: self._count_from_header_id[header_id] += 1 header_id += '-%s' % self._count_from_header_id[header_id] else: self._count_from_header_id[header_id] = 1 return header_id _toc = None def _toc_add_entry(self, level, id, name): if self._toc is None: self._toc = [] self._toc.append((level, id, self._unescape_special_chars(name))) _setext_h_re = re.compile(r'^(.+)[ \t]*\n(=+|-+)[ \t]*\n+', re.M) def _setext_h_sub(self, match): n = {"=": 1, "-": 2}[match.group(2)[0]] demote_headers = self.extras.get("demote-headers") if demote_headers: n = min(n + demote_headers, 6) header_id_attr = "" if "header-ids" in self.extras: header_id = self.header_id_from_text(match.group(1), self.extras["header-ids"], n) if header_id: header_id_attr = ' id="%s"' % header_id html = self._run_span_gamut(match.group(1)) if "toc" in self.extras and header_id: self._toc_add_entry(n, header_id, html) return "<h%d%s>%s</h%d>\n\n" % (n, header_id_attr, html, n) _atx_h_re = re.compile(r''' ^(\#{1,6}) # \1 = string of #'s [ \t]+ (.+?) # \2 = Header text [ \t]* (?<!\\) # ensure not an escaped trailing '#' \#* # optional closing #'s (not counted) \n+ ''', re.X | re.M) def _atx_h_sub(self, match): n = len(match.group(1)) demote_headers = self.extras.get("demote-headers") if demote_headers: n = min(n + demote_headers, 6) header_id_attr = "" if "header-ids" in self.extras: header_id = self.header_id_from_text(match.group(2), self.extras["header-ids"], n) if header_id: header_id_attr = ' id="%s"' % header_id html = self._run_span_gamut(match.group(2)) if "toc" in self.extras and header_id: self._toc_add_entry(n, header_id, html) return "<h%d%s>%s</h%d>\n\n" % (n, header_id_attr, html, n) def _do_headers(self, text): # Setext-style headers: # Header 1 # ======== # # Header 2 # -------- text = self._setext_h_re.sub(self._setext_h_sub, text) # atx-style headers: # # Header 1 # ## Header 2 # ## Header 2 with closing hashes ## # ... # ###### Header 6 text = self._atx_h_re.sub(self._atx_h_sub, text) return text _marker_ul_chars = '*+-' _marker_any = r'(?:[%s]|\d+\.)' % _marker_ul_chars _marker_ul = '(?:[%s])' % _marker_ul_chars _marker_ol = r'(?:\d+\.)' def _list_sub(self, match): lst = match.group(1) lst_type = match.group(3) in self._marker_ul_chars and "ul" or "ol" result = self._process_list_items(lst) if self.list_level: return "<%s>\n%s</%s>\n" % (lst_type, result, lst_type) else: return "<%s>\n%s</%s>\n\n" % (lst_type, result, lst_type) def _do_lists(self, text): # Form HTML ordered (numbered) and unordered (bulleted) lists. # Iterate over each *non-overlapping* list match. pos = 0 while True: # Find the *first* hit for either list style (ul or ol). We # match ul and ol separately to avoid adjacent lists of different # types running into each other (see issue #16). hits = [] for marker_pat in (self._marker_ul, self._marker_ol): less_than_tab = self.tab_width - 1 whole_list = r''' ( # \1 = whole list ( # \2 [ ]{0,%d} (%s) # \3 = first list item marker [ \t]+ (?!\ *\3\ ) # '- - - ...' isn't a list. See 'not_quite_a_list' test case. ) (?:.+?) ( # \4 \Z | \n{2,} (?=\S) (?! # Negative lookahead for another list item marker [ \t]* %s[ \t]+ ) ) ) ''' % (less_than_tab, marker_pat, marker_pat) if self.list_level: # sub-list list_re = re.compile("^"+whole_list, re.X | re.M | re.S) else: list_re = re.compile(r"(?:(?<=\n\n)|\A\n?)"+whole_list, re.X | re.M | re.S) match = list_re.search(text, pos) if match: hits.append((match.start(), match)) if not hits: break hits.sort() match = hits[0][1] start, end = match.span() text = text[:start] + self._list_sub(match) + text[end:] pos = end return text _list_item_re = re.compile(r''' (\n)? # leading line = \1 (^[ \t]*) # leading whitespace = \2 (?P<marker>%s) [ \t]+ # list marker = \3 ((?:.+?) # list item text = \4 (\n{1,2})) # eols = \5 (?= \n* (\Z | \2 (?P<next_marker>%s) [ \t]+)) ''' % (_marker_any, _marker_any), re.M | re.X | re.S) _last_li_endswith_two_eols = False def _list_item_sub(self, match): item = match.group(4) leading_line = match.group(1) leading_space = match.group(2) if leading_line or "\n\n" in item or self._last_li_endswith_two_eols: item = self._run_block_gamut(self._outdent(item)) else: # Recursion for sub-lists: item = self._do_lists(self._outdent(item)) if item.endswith('\n'): item = item[:-1] item = self._run_span_gamut(item) self._last_li_endswith_two_eols = (len(match.group(5)) == 2) return "<li>%s</li>\n" % item def _process_list_items(self, list_str): # Process the contents of a single ordered or unordered list, # splitting it into individual list items. # The $g_list_level global keeps track of when we're inside a list. # Each time we enter a list, we increment it; when we leave a list, # we decrement. If it's zero, we're not in a list anymore. # # We do this because when we're not inside a list, we want to treat # something like this: # # I recommend upgrading to version # 8. Oops, now this line is treated # as a sub-list. # # As a single paragraph, despite the fact that the second line starts # with a digit-period-space sequence. # # Whereas when we're inside a list (or sub-list), that line will be # treated as the start of a sub-list. What a kludge, huh? This is # an aspect of Markdown's syntax that's hard to parse perfectly # without resorting to mind-reading. Perhaps the solution is to # change the syntax rules such that sub-lists must start with a # starting cardinal number; e.g. "1." or "a.". self.list_level += 1 self._last_li_endswith_two_eols = False list_str = list_str.rstrip('\n') + '\n' list_str = self._list_item_re.sub(self._list_item_sub, list_str) self.list_level -= 1 return list_str def _get_pygments_lexer(self, lexer_name): try: from pygments import lexers, util except ImportError: return None try: return lexers.get_lexer_by_name(lexer_name) except util.ClassNotFound: return None def _color_with_pygments(self, codeblock, lexer, **formatter_opts): import pygments import pygments.formatters class HtmlCodeFormatter(pygments.formatters.HtmlFormatter): def _wrap_code(self, inner): """A function for use in a Pygments Formatter which wraps in <code> tags. """ yield 0, "<code>" for tup in inner: yield tup yield 0, "</code>" def wrap(self, source, outfile): """Return the source with a code, pre, and div.""" return self._wrap_div(self._wrap_pre(self._wrap_code(source))) formatter_opts.setdefault("cssclass", "codehilite") formatter = HtmlCodeFormatter(**formatter_opts) return pygments.highlight(codeblock, lexer, formatter) def _code_block_sub(self, match, is_fenced_code_block=False): lexer_name = None if is_fenced_code_block: lexer_name = match.group(1) if lexer_name: formatter_opts = self.extras['fenced-code-blocks'] or {} codeblock = match.group(2) codeblock = codeblock[:-1] # drop one trailing newline else: codeblock = match.group(1) codeblock = self._outdent(codeblock) codeblock = self._detab(codeblock) codeblock = codeblock.lstrip('\n') # trim leading newlines codeblock = codeblock.rstrip() # trim trailing whitespace # Note: "code-color" extra is DEPRECATED. if "code-color" in self.extras and codeblock.startswith(":::"): lexer_name, rest = codeblock.split('\n', 1) lexer_name = lexer_name[3:].strip() codeblock = rest.lstrip("\n") # Remove lexer declaration line. formatter_opts = self.extras['code-color'] or {} if lexer_name: lexer = self._get_pygments_lexer(lexer_name) if lexer: colored = self._color_with_pygments(codeblock, lexer, **formatter_opts) return "\n\n%s\n\n" % colored codeblock = self._encode_code(codeblock) pre_class_str = self._html_class_str_from_tag("pre") code_class_str = self._html_class_str_from_tag("code") return "\n\n<pre%s><code%s>%s\n</code></pre>\n\n" % ( pre_class_str, code_class_str, codeblock) def _html_class_str_from_tag(self, tag): """Get the appropriate ' class="..."' string (note the leading space), if any, for the given tag. """ if "html-classes" not in self.extras: return "" try: html_classes_from_tag = self.extras["html-classes"] except TypeError: return "" else: if tag in html_classes_from_tag: return ' class="%s"' % html_classes_from_tag[tag] return "" def _do_code_blocks(self, text): """Process Markdown `<pre><code>` blocks.""" code_block_re = re.compile(r''' (?:\n\n|\A\n?) ( # $1 = the code block -- one or more lines, starting with a space/tab (?: (?:[ ]{%d} | \t) # Lines must start with a tab or a tab-width of spaces .*\n+ )+ ) ((?=^[ ]{0,%d}\S)|\Z) # Lookahead for non-space at line-start, or end of doc ''' % (self.tab_width, self.tab_width), re.M | re.X) return code_block_re.sub(self._code_block_sub, text) _fenced_code_block_re = re.compile(r''' (?:\n\n|\A\n?) ^```([\w+-]+)?[ \t]*\n # opening fence, $1 = optional lang (.*?) # $2 = code block content ^```[ \t]*\n # closing fence ''', re.M | re.X | re.S) def _fenced_code_block_sub(self, match): return self._code_block_sub(match, is_fenced_code_block=True); def _do_fenced_code_blocks(self, text): """Process ```-fenced unindented code blocks ('fenced-code-blocks' extra).""" return self._fenced_code_block_re.sub(self._fenced_code_block_sub, text) # Rules for a code span: # - backslash escapes are not interpreted in a code span # - to include one or or a run of more backticks the delimiters must # be a longer run of backticks # - cannot start or end a code span with a backtick; pad with a # space and that space will be removed in the emitted HTML # See `test/tm-cases/escapes.text` for a number of edge-case # examples. _code_span_re = re.compile(r''' (?<!\\) (`+) # \1 = Opening run of ` (?!`) # See Note A test/tm-cases/escapes.text (.+?) # \2 = The code block (?<!`) \1 # Matching closer (?!`) ''', re.X | re.S) def _code_span_sub(self, match): c = match.group(2).strip(" \t") c = self._encode_code(c) return "<code>%s</code>" % c def _do_code_spans(self, text): # * Backtick quotes are used for <code></code> spans. # # * You can use multiple backticks as the delimiters if you want to # include literal backticks in the code span. So, this input: # # Just type ``foo `bar` baz`` at the prompt. # # Will translate to: # # <p>Just type <code>foo `bar` baz</code> at the prompt.</p> # # There's no arbitrary limit to the number of backticks you # can use as delimters. If you need three consecutive backticks # in your code, use four for delimiters, etc. # # * You can use spaces to get literal backticks at the edges: # # ... type `` `bar` `` ... # # Turns to: # # ... type <code>`bar`</code> ... return self._code_span_re.sub(self._code_span_sub, text) def _encode_code(self, text): """Encode/escape certain characters inside Markdown code runs. The point is that in code, these characters are literals, and lose their special Markdown meanings. """ replacements = [ # Encode all ampersands; HTML entities are not # entities within a Markdown code span. ('&', '&amp;'), # Do the angle bracket song and dance: ('<', '&lt;'), ('>', '&gt;'), ] for before, after in replacements: text = text.replace(before, after) hashed = _hash_text(text) self._escape_table[text] = hashed return hashed _strong_re = re.compile(r"(\*\*|__)(?=\S)(.+?[*_]*)(?<=\S)\1", re.S) _em_re = re.compile(r"(\*|_)(?=\S)(.+?)(?<=\S)\1", re.S) _code_friendly_strong_re = re.compile(r"\*\*(?=\S)(.+?[*_]*)(?<=\S)\*\*", re.S) _code_friendly_em_re = re.compile(r"\*(?=\S)(.+?)(?<=\S)\*", re.S) def _do_italics_and_bold(self, text): # <strong> must go first: if "code-friendly" in self.extras: text = self._code_friendly_strong_re.sub(r"<strong>\1</strong>", text) text = self._code_friendly_em_re.sub(r"<em>\1</em>", text) else: text = self._strong_re.sub(r"<strong>\2</strong>", text) text = self._em_re.sub(r"<em>\2</em>", text) return text # "smarty-pants" extra: Very liberal in interpreting a single prime as an # apostrophe; e.g. ignores the fact that "round", "bout", "twer", and # "twixt" can be written without an initial apostrophe. This is fine because # using scare quotes (single quotation marks) is rare. _apostrophe_year_re = re.compile(r"'(\d\d)(?=(\s|,|;|\.|\?|!|$))") _contractions = ["tis", "twas", "twer", "neath", "o", "n", "round", "bout", "twixt", "nuff", "fraid", "sup"] def _do_smart_contractions(self, text): text = self._apostrophe_year_re.sub(r"&#8217;\1", text) for c in self._contractions: text = text.replace("'%s" % c, "&#8217;%s" % c) text = text.replace("'%s" % c.capitalize(), "&#8217;%s" % c.capitalize()) return text # Substitute double-quotes before single-quotes. _opening_single_quote_re = re.compile(r"(?<!\S)'(?=\S)") _opening_double_quote_re = re.compile(r'(?<!\S)"(?=\S)') _closing_single_quote_re = re.compile(r"(?<=\S)'") _closing_double_quote_re = re.compile(r'(?<=\S)"(?=(\s|,|;|\.|\?|!|$))') def _do_smart_punctuation(self, text): """Fancifies 'single quotes', "double quotes", and apostrophes. Converts --, ---, and ... into en dashes, em dashes, and ellipses. Inspiration is: <http://daringfireball.net/projects/smartypants/> See "test/tm-cases/smarty_pants.text" for a full discussion of the support here and <http://code.google.com/p/python-markdown2/issues/detail?id=42> for a discussion of some diversion from the original SmartyPants. """ if "'" in text: # guard for perf text = self._do_smart_contractions(text) text = self._opening_single_quote_re.sub("&#8216;", text) text = self._closing_single_quote_re.sub("&#8217;", text) if '"' in text: # guard for perf text = self._opening_double_quote_re.sub("&#8220;", text) text = self._closing_double_quote_re.sub("&#8221;", text) text = text.replace("---", "&#8212;") text = text.replace("--", "&#8211;") text = text.replace("...", "&#8230;") text = text.replace(" . . . ", "&#8230;") text = text.replace(". . .", "&#8230;") return text _block_quote_re = re.compile(r''' ( # Wrap whole match in \1 ( ^[ \t]*>[ \t]? # '>' at the start of a line .+\n # rest of the first line (.+\n)* # subsequent consecutive lines \n* # blanks )+ ) ''', re.M | re.X) _bq_one_level_re = re.compile('^[ \t]*>[ \t]?', re.M); _html_pre_block_re = re.compile(r'(\s*<pre>.+?</pre>)', re.S) def _dedent_two_spaces_sub(self, match): return re.sub(r'(?m)^ ', '', match.group(1)) def _block_quote_sub(self, match): bq = match.group(1) bq = self._bq_one_level_re.sub('', bq) # trim one level of quoting bq = self._ws_only_line_re.sub('', bq) # trim whitespace-only lines bq = self._run_block_gamut(bq) # recurse bq = re.sub('(?m)^', ' ', bq) # These leading spaces screw with <pre> content, so we need to fix that: bq = self._html_pre_block_re.sub(self._dedent_two_spaces_sub, bq) return "<blockquote>\n%s\n</blockquote>\n\n" % bq def _do_block_quotes(self, text): if '>' not in text: return text return self._block_quote_re.sub(self._block_quote_sub, text) def _form_paragraphs(self, text): # Strip leading and trailing lines: text = text.strip('\n') # Wrap <p> tags. grafs = [] for i, graf in enumerate(re.split(r"\n{2,}", text)): if graf in self.html_blocks: # Unhashify HTML blocks grafs.append(self.html_blocks[graf]) else: cuddled_list = None if "cuddled-lists" in self.extras: # Need to put back trailing '\n' for `_list_item_re` # match at the end of the paragraph. li = self._list_item_re.search(graf + '\n') # Two of the same list marker in this paragraph: a likely # candidate for a list cuddled to preceding paragraph # text (issue 33). Note the `[-1]` is a quick way to # consider numeric bullets (e.g. "1." and "2.") to be # equal. if (li and len(li.group(2)) <= 3 and li.group("next_marker") and li.group("marker")[-1] == li.group("next_marker")[-1]): start = li.start() cuddled_list = self._do_lists(graf[start:]).rstrip("\n") assert cuddled_list.startswith("<ul>") or cuddled_list.startswith("<ol>") graf = graf[:start] # Wrap <p> tags. graf = self._run_span_gamut(graf) grafs.append("<p>" + graf.lstrip(" \t") + "</p>") if cuddled_list: grafs.append(cuddled_list) return "\n\n".join(grafs) def _add_footnotes(self, text): if self.footnotes: footer = [ '<div class="footnotes">', '<hr' + self.empty_element_suffix, '<ol>', ] for i, id in enumerate(self.footnote_ids): if i != 0: footer.append('') footer.append('<li id="fn-%s">' % id) footer.append(self._run_block_gamut(self.footnotes[id])) backlink = ('<a href="#fnref-%s" ' 'class="footnoteBackLink" ' 'title="Jump back to footnote %d in the text.">' '&#8617;</a>' % (id, i+1)) if footer[-1].endswith("</p>"): footer[-1] = footer[-1][:-len("</p>")] \ + '&nbsp;' + backlink + "</p>" else: footer.append("\n<p>%s</p>" % backlink) footer.append('</li>') footer.append('</ol>') footer.append('</div>') return text + '\n\n' + '\n'.join(footer) else: return text # Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin: # http://bumppo.net/projects/amputator/ _ampersand_re = re.compile(r'&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)') _naked_lt_re = re.compile(r'<(?![a-z/?\$!])', re.I) _naked_gt_re = re.compile(r'''(?<![a-z0-9?!/'"-])>''', re.I) def _encode_amps_and_angles(self, text): # Smart processing for ampersands and angle brackets that need # to be encoded. text = self._ampersand_re.sub('&amp;', text) # Encode naked <'s text = self._naked_lt_re.sub('&lt;', text) # Encode naked >'s # Note: Other markdown implementations (e.g. Markdown.pl, PHP # Markdown) don't do this. text = self._naked_gt_re.sub('&gt;', text) return text def _encode_backslash_escapes(self, text): for ch, escape in list(self._escape_table.items()): text = text.replace("\\"+ch, escape) return text _auto_link_re = re.compile(r'<((https?|ftp):[^\'">\s]+)>', re.I) def _auto_link_sub(self, match): g1 = match.group(1) return '<a href="%s">%s</a>' % (g1, g1) _auto_email_link_re = re.compile(r""" < (?:mailto:)? ( [-.\w]+ \@ [-\w]+(\.[-\w]+)*\.[a-z]+ ) > """, re.I | re.X | re.U) def _auto_email_link_sub(self, match): return self._encode_email_address( self._unescape_special_chars(match.group(1))) def _do_auto_links(self, text): text = self._auto_link_re.sub(self._auto_link_sub, text) text = self._auto_email_link_re.sub(self._auto_email_link_sub, text) return text def _encode_email_address(self, addr): # Input: an email address, e.g. "foo@example.com" # # Output: the email address as a mailto link, with each character # of the address encoded as either a decimal or hex entity, in # the hopes of foiling most address harvesting spam bots. E.g.: # # <a href="&#x6D;&#97;&#105;&#108;&#x74;&#111;:&#102;&#111;&#111;&#64;&#101; # x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;">&#102;&#111;&#111; # &#64;&#101;x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;</a> # # Based on a filter by Matthew Wickline, posted to the BBEdit-Talk # mailing list: <http://tinyurl.com/yu7ue> chars = [_xml_encode_email_char_at_random(ch) for ch in "mailto:" + addr] # Strip the mailto: from the visible part. addr = '<a href="%s">%s</a>' \ % (''.join(chars), ''.join(chars[7:])) return addr def _do_link_patterns(self, text): """Caveat emptor: there isn't much guarding against link patterns being formed inside other standard Markdown links, e.g. inside a [link def][like this]. Dev Notes: *Could* consider prefixing regexes with a negative lookbehind assertion to attempt to guard against this. """ link_from_hash = {} for regex, repl in self.link_patterns: replacements = [] for match in regex.finditer(text): if hasattr(repl, "__call__"): href = repl(match) else: href = match.expand(repl) replacements.append((match.span(), href)) for (start, end), href in reversed(replacements): escaped_href = ( href.replace('"', '&quot;') # b/c of attr quote # To avoid markdown <em> and <strong>: .replace('*', self._escape_table['*']) .replace('_', self._escape_table['_'])) link = '<a href="%s">%s</a>' % (escaped_href, text[start:end]) hash = _hash_text(link) link_from_hash[hash] = link text = text[:start] + hash + text[end:] for hash, link in list(link_from_hash.items()): text = text.replace(hash, link) return text def _unescape_special_chars(self, text): # Swap back in all the special characters we've hidden. for ch, hash in list(self._escape_table.items()): text = text.replace(hash, ch) return text def _outdent(self, text): # Remove one level of line-leading tabs or spaces return self._outdent_re.sub('', text) class MarkdownWithExtras(Markdown): """A markdowner class that enables most extras: - footnotes - code-color (only has effect if 'pygments' Python module on path) These are not included: - pyshell (specific to Python-related documenting) - code-friendly (because it *disables* part of the syntax) - link-patterns (because you need to specify some actual link-patterns anyway) """ extras = ["footnotes", "code-color"] #---- internal support functions class UnicodeWithAttrs(unicode): """A subclass of unicode used for the return value of conversion to possibly attach some attributes. E.g. the "toc_html" attribute when the "toc" extra is used. """ metadata = None _toc = None def toc_html(self): """Return the HTML for the current TOC. This expects the `_toc` attribute to have been set on this instance. """ if self._toc is None: return None def indent(): return ' ' * (len(h_stack) - 1) lines = [] h_stack = [0] # stack of header-level numbers for level, id, name in self._toc: if level > h_stack[-1]: lines.append("%s<ul>" % indent()) h_stack.append(level) elif level == h_stack[-1]: lines[-1] += "</li>" else: while level < h_stack[-1]: h_stack.pop() if not lines[-1].endswith("</li>"): lines[-1] += "</li>" lines.append("%s</ul></li>" % indent()) lines.append('%s<li><a href="#%s">%s</a>' % ( indent(), id, name)) while len(h_stack) > 1: h_stack.pop() if not lines[-1].endswith("</li>"): lines[-1] += "</li>" lines.append("%s</ul>" % indent()) return '\n'.join(lines) + '\n' toc_html = property(toc_html) ## {{{ http://code.activestate.com/recipes/577257/ (r1) import re char_map = {u'À': 'A', u'Á': 'A', u'Â': 'A', u'Ã': 'A', u'Ä': 'Ae', u'Å': 'A', u'Æ': 'A', u'Ā': 'A', u'Ą': 'A', u'Ă': 'A', u'Ç': 'C', u'Ć': 'C', u'Č': 'C', u'Ĉ': 'C', u'Ċ': 'C', u'Ď': 'D', u'Đ': 'D', u'È': 'E', u'É': 'E', u'Ê': 'E', u'Ë': 'E', u'Ē': 'E', u'Ę': 'E', u'Ě': 'E', u'Ĕ': 'E', u'Ė': 'E', u'Ĝ': 'G', u'Ğ': 'G', u'Ġ': 'G', u'Ģ': 'G', u'Ĥ': 'H', u'Ħ': 'H', u'Ì': 'I', u'Í': 'I', u'Î': 'I', u'Ï': 'I', u'Ī': 'I', u'Ĩ': 'I', u'Ĭ': 'I', u'Į': 'I', u'İ': 'I', u'IJ': 'IJ', u'Ĵ': 'J', u'Ķ': 'K', u'Ľ': 'K', u'Ĺ': 'K', u'Ļ': 'K', u'Ŀ': 'K', u'Ł': 'L', u'Ñ': 'N', u'Ń': 'N', u'Ň': 'N', u'Ņ': 'N', u'Ŋ': 'N', u'Ò': 'O', u'Ó': 'O', u'Ô': 'O', u'Õ': 'O', u'Ö': 'Oe', u'Ø': 'O', u'Ō': 'O', u'Ő': 'O', u'Ŏ': 'O', u'Œ': 'OE', u'Ŕ': 'R', u'Ř': 'R', u'Ŗ': 'R', u'Ś': 'S', u'Ş': 'S', u'Ŝ': 'S', u'Ș': 'S', u'Š': 'S', u'Ť': 'T', u'Ţ': 'T', u'Ŧ': 'T', u'Ț': 'T', u'Ù': 'U', u'Ú': 'U', u'Û': 'U', u'Ü': 'Ue', u'Ū': 'U', u'Ů': 'U', u'Ű': 'U', u'Ŭ': 'U', u'Ũ': 'U', u'Ų': 'U', u'Ŵ': 'W', u'Ŷ': 'Y', u'Ÿ': 'Y', u'Ý': 'Y', u'Ź': 'Z', u'Ż': 'Z', u'Ž': 'Z', u'à': 'a', u'á': 'a', u'â': 'a', u'ã': 'a', u'ä': 'ae', u'ā': 'a', u'ą': 'a', u'ă': 'a', u'å': 'a', u'æ': 'ae', u'ç': 'c', u'ć': 'c', u'č': 'c', u'ĉ': 'c', u'ċ': 'c', u'ď': 'd', u'đ': 'd', u'è': 'e', u'é': 'e', u'ê': 'e', u'ë': 'e', u'ē': 'e', u'ę': 'e', u'ě': 'e', u'ĕ': 'e', u'ė': 'e', u'ƒ': 'f', u'ĝ': 'g', u'ğ': 'g', u'ġ': 'g', u'ģ': 'g', u'ĥ': 'h', u'ħ': 'h', u'ì': 'i', u'í': 'i', u'î': 'i', u'ï': 'i', u'ī': 'i', u'ĩ': 'i', u'ĭ': 'i', u'į': 'i', u'ı': 'i', u'ij': 'ij', u'ĵ': 'j', u'ķ': 'k', u'ĸ': 'k', u'ł': 'l', u'ľ': 'l', u'ĺ': 'l', u'ļ': 'l', u'ŀ': 'l', u'ñ': 'n', u'ń': 'n', u'ň': 'n', u'ņ': 'n', u'ʼn': 'n', u'ŋ': 'n', u'ò': 'o', u'ó': 'o', u'ô': 'o', u'õ': 'o', u'ö': 'oe', u'ø': 'o', u'ō': 'o', u'ő': 'o', u'ŏ': 'o', u'œ': 'oe', u'ŕ': 'r', u'ř': 'r', u'ŗ': 'r', u'ś': 's', u'š': 's', u'ť': 't', u'ù': 'u', u'ú': 'u', u'û': 'u', u'ü': 'ue', u'ū': 'u', u'ů': 'u', u'ű': 'u', u'ŭ': 'u', u'ũ': 'u', u'ų': 'u', u'ŵ': 'w', u'ÿ': 'y', u'ý': 'y', u'ŷ': 'y', u'ż': 'z', u'ź': 'z', u'ž': 'z', u'ß': 'ss', u'ſ': 'ss', u'Α': 'A', u'Ά': 'A', u'Ἀ': 'A', u'Ἁ': 'A', u'Ἂ': 'A', u'Ἃ': 'A', u'Ἄ': 'A', u'Ἅ': 'A', u'Ἆ': 'A', u'Ἇ': 'A', u'ᾈ': 'A', u'ᾉ': 'A', u'ᾊ': 'A', u'ᾋ': 'A', u'ᾌ': 'A', u'ᾍ': 'A', u'ᾎ': 'A', u'ᾏ': 'A', u'Ᾰ': 'A', u'Ᾱ': 'A', u'Ὰ': 'A', u'Ά': 'A', u'ᾼ': 'A', u'Β': 'B', u'Γ': 'G', u'Δ': 'D', u'Ε': 'E', u'Έ': 'E', u'Ἐ': 'E', u'Ἑ': 'E', u'Ἒ': 'E', u'Ἓ': 'E', u'Ἔ': 'E', u'Ἕ': 'E', u'Έ': 'E', u'Ὲ': 'E', u'Ζ': 'Z', u'Η': 'I', u'Ή': 'I', u'Ἠ': 'I', u'Ἡ': 'I', u'Ἢ': 'I', u'Ἣ': 'I', u'Ἤ': 'I', u'Ἥ': 'I', u'Ἦ': 'I', u'Ἧ': 'I', u'ᾘ': 'I', u'ᾙ': 'I', u'ᾚ': 'I', u'ᾛ': 'I', u'ᾜ': 'I', u'ᾝ': 'I', u'ᾞ': 'I', u'ᾟ': 'I', u'Ὴ': 'I', u'Ή': 'I', u'ῌ': 'I', u'Θ': 'TH', u'Ι': 'I', u'Ί': 'I', u'Ϊ': 'I', u'Ἰ': 'I', u'Ἱ': 'I', u'Ἲ': 'I', u'Ἳ': 'I', u'Ἴ': 'I', u'Ἵ': 'I', u'Ἶ': 'I', u'Ἷ': 'I', u'Ῐ': 'I', u'Ῑ': 'I', u'Ὶ': 'I', u'Ί': 'I', u'Κ': 'K', u'Λ': 'L', u'Μ': 'M', u'Ν': 'N', u'Ξ': 'KS', u'Ο': 'O', u'Ό': 'O', u'Ὀ': 'O', u'Ὁ': 'O', u'Ὂ': 'O', u'Ὃ': 'O', u'Ὄ': 'O', u'Ὅ': 'O', u'Ὸ': 'O', u'Ό': 'O', u'Π': 'P', u'Ρ': 'R', u'Ῥ': 'R', u'Σ': 'S', u'Τ': 'T', u'Υ': 'Y', u'Ύ': 'Y', u'Ϋ': 'Y', u'Ὑ': 'Y', u'Ὓ': 'Y', u'Ὕ': 'Y', u'Ὗ': 'Y', u'Ῠ': 'Y', u'Ῡ': 'Y', u'Ὺ': 'Y', u'Ύ': 'Y', u'Φ': 'F', u'Χ': 'X', u'Ψ': 'PS', u'Ω': 'O', u'Ώ': 'O', u'Ὠ': 'O', u'Ὡ': 'O', u'Ὢ': 'O', u'Ὣ': 'O', u'Ὤ': 'O', u'Ὥ': 'O', u'Ὦ': 'O', u'Ὧ': 'O', u'ᾨ': 'O', u'ᾩ': 'O', u'ᾪ': 'O', u'ᾫ': 'O', u'ᾬ': 'O', u'ᾭ': 'O', u'ᾮ': 'O', u'ᾯ': 'O', u'Ὼ': 'O', u'Ώ': 'O', u'ῼ': 'O', u'α': 'a', u'ά': 'a', u'ἀ': 'a', u'ἁ': 'a', u'ἂ': 'a', u'ἃ': 'a', u'ἄ': 'a', u'ἅ': 'a', u'ἆ': 'a', u'ἇ': 'a', u'ᾀ': 'a', u'ᾁ': 'a', u'ᾂ': 'a', u'ᾃ': 'a', u'ᾄ': 'a', u'ᾅ': 'a', u'ᾆ': 'a', u'ᾇ': 'a', u'ὰ': 'a', u'ά': 'a', u'ᾰ': 'a', u'ᾱ': 'a', u'ᾲ': 'a', u'ᾳ': 'a', u'ᾴ': 'a', u'ᾶ': 'a', u'ᾷ': 'a', u'β': 'b', u'γ': 'g', u'δ': 'd', u'ε': 'e', u'έ': 'e', u'ἐ': 'e', u'ἑ': 'e', u'ἒ': 'e', u'ἓ': 'e', u'ἔ': 'e', u'ἕ': 'e', u'ὲ': 'e', u'έ': 'e', u'ζ': 'z', u'η': 'i', u'ή': 'i', u'ἠ': 'i', u'ἡ': 'i', u'ἢ': 'i', u'ἣ': 'i', u'ἤ': 'i', u'ἥ': 'i', u'ἦ': 'i', u'ἧ': 'i', u'ᾐ': 'i', u'ᾑ': 'i', u'ᾒ': 'i', u'ᾓ': 'i', u'ᾔ': 'i', u'ᾕ': 'i', u'ᾖ': 'i', u'ᾗ': 'i', u'ὴ': 'i', u'ή': 'i', u'ῂ': 'i', u'ῃ': 'i', u'ῄ': 'i', u'ῆ': 'i', u'ῇ': 'i', u'θ': 'th', u'ι': 'i', u'ί': 'i', u'ϊ': 'i', u'ΐ': 'i', u'ἰ': 'i', u'ἱ': 'i', u'ἲ': 'i', u'ἳ': 'i', u'ἴ': 'i', u'ἵ': 'i', u'ἶ': 'i', u'ἷ': 'i', u'ὶ': 'i', u'ί': 'i', u'ῐ': 'i', u'ῑ': 'i', u'ῒ': 'i', u'ΐ': 'i', u'ῖ': 'i', u'ῗ': 'i', u'κ': 'k', u'λ': 'l', u'μ': 'm', u'ν': 'n', u'ξ': 'ks', u'ο': 'o', u'ό': 'o', u'ὀ': 'o', u'ὁ': 'o', u'ὂ': 'o', u'ὃ': 'o', u'ὄ': 'o', u'ὅ': 'o', u'ὸ': 'o', u'ό': 'o', u'π': 'p', u'ρ': 'r', u'ῤ': 'r', u'ῥ': 'r', u'σ': 's', u'ς': 's', u'τ': 't', u'υ': 'y', u'ύ': 'y', u'ϋ': 'y', u'ΰ': 'y', u'ὐ': 'y', u'ὑ': 'y', u'ὒ': 'y', u'ὓ': 'y', u'ὔ': 'y', u'ὕ': 'y', u'ὖ': 'y', u'ὗ': 'y', u'ὺ': 'y', u'ύ': 'y', u'ῠ': 'y', u'ῡ': 'y', u'ῢ': 'y', u'ΰ': 'y', u'ῦ': 'y', u'ῧ': 'y', u'φ': 'f', u'χ': 'x', u'ψ': 'ps', u'ω': 'o', u'ώ': 'o', u'ὠ': 'o', u'ὡ': 'o', u'ὢ': 'o', u'ὣ': 'o', u'ὤ': 'o', u'ὥ': 'o', u'ὦ': 'o', u'ὧ': 'o', u'ᾠ': 'o', u'ᾡ': 'o', u'ᾢ': 'o', u'ᾣ': 'o', u'ᾤ': 'o', u'ᾥ': 'o', u'ᾦ': 'o', u'ᾧ': 'o', u'ὼ': 'o', u'ώ': 'o', u'ῲ': 'o', u'ῳ': 'o', u'ῴ': 'o', u'ῶ': 'o', u'ῷ': 'o', u'¨': '', u'΅': '', u'᾿': '', u'῾': '', u'῍': '', u'῝': '', u'῎': '', u'῞': '', u'῏': '', u'῟': '', u'῀': '', u'῁': '', u'΄': '', u'΅': '', u'`': '', u'῭': '', u'ͺ': '', u'᾽': '', u'А': 'A', u'Б': 'B', u'В': 'V', u'Г': 'G', u'Д': 'D', u'Е': 'E', u'Ё': 'YO', u'Ж': 'ZH', u'З': 'Z', u'И': 'I', u'Й': 'J', u'К': 'K', u'Л': 'L', u'М': 'M', u'Н': 'N', u'О': 'O', u'П': 'P', u'Р': 'R', u'С': 'S', u'Т': 'T', u'У': 'U', u'Ф': 'F', u'Х': 'H', u'Ц': 'TS', u'Ч': 'CH', u'Ш': 'SH', u'Щ': 'SCH', u'Ы': 'YI', u'Э': 'E', u'Ю': 'YU', u'Я': 'YA', u'а': 'A', u'б': 'B', u'в': 'V', u'г': 'G', u'д': 'D', u'е': 'E', u'ё': 'YO', u'ж': 'ZH', u'з': 'Z', u'и': 'I', u'й': 'J', u'к': 'K', u'л': 'L', u'м': 'M', u'н': 'N', u'о': 'O', u'п': 'P', u'р': 'R', u'с': 'S', u'т': 'T', u'у': 'U', u'ф': 'F', u'х': 'H', u'ц': 'TS', u'ч': 'CH', u'ш': 'SH', u'щ': 'SCH', u'ы': 'YI', u'э': 'E', u'ю': 'YU', u'я': 'YA', u'Ъ': '', u'ъ': '', u'Ь': '', u'ь': '', u'ð': 'd', u'Ð': 'D', u'þ': 'th', u'Þ': 'TH',u'ა': 'a', u'ბ': 'b', u'გ': 'g', u'დ': 'd', u'ე': 'e', u'ვ': 'v', u'ზ': 'z', u'თ': 't', u'ი': 'i', u'კ': 'k', u'ლ': 'l', u'მ': 'm', u'ნ': 'n', u'ო': 'o', u'პ': 'p', u'ჟ': 'zh', u'რ': 'r', u'ს': 's', u'ტ': 't', u'უ': 'u', u'ფ': 'p', u'ქ': 'k', u'ღ': 'gh', u'ყ': 'q', u'შ': 'sh', u'ჩ': 'ch', u'ც': 'ts', u'ძ': 'dz', u'წ': 'ts', u'ჭ': 'ch', u'ხ': 'kh', u'ჯ': 'j', u'ჰ': 'h' } def replace_char(m): char = m.group() if char_map.has_key(char): return char_map[char] else: return char _punct_re = re.compile(r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.]+') def _slugify(text, delim=u'-'): """Generates an ASCII-only slug.""" result = [] for word in _punct_re.split(text.lower()): word = word.encode('utf-8') if word: result.append(word) slugified = delim.join([i.decode('utf-8') for i in result]) return re.sub('[^a-zA-Z0-9\\s\\-]{1}', replace_char, slugified).lower() ## end of http://code.activestate.com/recipes/577257/ }}} # From http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52549 def _curry(*args, **kwargs): function, args = args[0], args[1:] def result(*rest, **kwrest): combined = kwargs.copy() combined.update(kwrest) return function(*args + rest, **combined) return result # Recipe: regex_from_encoded_pattern (1.0) # Recipe: dedent (0.1.2) def _dedentlines(lines, tabsize=8, skip_first_line=False): """_dedentlines(lines, tabsize=8, skip_first_line=False) -> dedented lines "lines" is a list of lines to dedent. "tabsize" is the tab width to use for indent width calculations. "skip_first_line" is a boolean indicating if the first line should be skipped for calculating the indent width and for dedenting. This is sometimes useful for docstrings and similar. Same as dedent() except operates on a sequence of lines. Note: the lines list is modified **in-place**. """ DEBUG = False if DEBUG: print("dedent: dedent(..., tabsize=%d, skip_first_line=%r)"\ % (tabsize, skip_first_line)) indents = [] margin = None for i, line in enumerate(lines): if i == 0 and skip_first_line: continue indent = 0 for ch in line: if ch == ' ': indent += 1 elif ch == '\t': indent += tabsize - (indent % tabsize) elif ch in '\r\n': continue # skip all-whitespace lines else: break else: continue # skip all-whitespace lines if DEBUG: print("dedent: indent=%d: %r" % (indent, line)) if margin is None: margin = indent else: margin = min(margin, indent) if DEBUG: print("dedent: margin=%r" % margin) if margin is not None and margin > 0: for i, line in enumerate(lines): if i == 0 and skip_first_line: continue removed = 0 for j, ch in enumerate(line): if ch == ' ': removed += 1 elif ch == '\t': removed += tabsize - (removed % tabsize) elif ch in '\r\n': if DEBUG: print("dedent: %r: EOL -> strip up to EOL" % line) lines[i] = lines[i][j:] break else: raise ValueError("unexpected non-whitespace char %r in " "line %r while removing %d-space margin" % (ch, line, margin)) if DEBUG: print("dedent: %r: %r -> removed %d/%d"\ % (line, ch, removed, margin)) if removed == margin: lines[i] = lines[i][j+1:] break elif removed > margin: lines[i] = ' '*(removed-margin) + lines[i][j+1:] break else: if removed: lines[i] = lines[i][removed:] return lines def _dedent(text, tabsize=8, skip_first_line=False): """_dedent(text, tabsize=8, skip_first_line=False) -> dedented text "text" is the text to dedent. "tabsize" is the tab width to use for indent width calculations. "skip_first_line" is a boolean indicating if the first line should be skipped for calculating the indent width and for dedenting. This is sometimes useful for docstrings and similar. textwrap.dedent(s), but don't expand tabs to spaces """ lines = text.splitlines(1) _dedentlines(lines, tabsize=tabsize, skip_first_line=skip_first_line) return ''.join(lines) class _memoized(object): """Decorator that caches a function's return value each time it is called. If called later with the same arguments, the cached value is returned, and not re-evaluated. http://wiki.python.org/moin/PythonDecoratorLibrary """ def __init__(self, func): self.func = func self.cache = {} def __call__(self, *args): try: return self.cache[args] except KeyError: self.cache[args] = value = self.func(*args) return value except TypeError: # uncachable -- for instance, passing a list as an argument. # Better to not cache than to blow up entirely. return self.func(*args) def __repr__(self): """Return the function's docstring.""" return self.func.__doc__ def _xml_oneliner_re_from_tab_width(tab_width): """Standalone XML processing instruction regex.""" return re.compile(r""" (?: (?<=\n\n) # Starting after a blank line | # or \A\n? # the beginning of the doc ) ( # save in $1 [ ]{0,%d} (?: <\?\w+\b\s+.*?\?> # XML processing instruction | <\w+:\w+\b\s+.*?/> # namespaced single tag ) [ \t]* (?=\n{2,}|\Z) # followed by a blank line or end of document ) """ % (tab_width - 1), re.X) _xml_oneliner_re_from_tab_width = _memoized(_xml_oneliner_re_from_tab_width) def _hr_tag_re_from_tab_width(tab_width): return re.compile(r""" (?: (?<=\n\n) # Starting after a blank line | # or \A\n? # the beginning of the doc ) ( # save in \1 [ ]{0,%d} <(hr) # start tag = \2 \b # word break ([^<>])*? # /?> # the matching end tag [ \t]* (?=\n{2,}|\Z) # followed by a blank line or end of document ) """ % (tab_width - 1), re.X) _hr_tag_re_from_tab_width = _memoized(_hr_tag_re_from_tab_width) def _xml_escape_attr(attr, skip_single_quote=True): """Escape the given string for use in an HTML/XML tag attribute. By default this doesn't bother with escaping `'` to `&#39;`, presuming that the tag attribute is surrounded by double quotes. """ escaped = (attr .replace('&', '&amp;') .replace('"', '&quot;') .replace('<', '&lt;') .replace('>', '&gt;')) if not skip_single_quote: escaped = escaped.replace("'", "&#39;") return escaped def _xml_encode_email_char_at_random(ch): r = random() # Roughly 10% raw, 45% hex, 45% dec. # '@' *must* be encoded. I [John Gruber] insist. # Issue 26: '_' must be encoded. if r > 0.9 and ch not in "@_": return ch elif r < 0.45: # The [1:] is to drop leading '0': 0x63 -> x63 return '&#%s;' % hex(ord(ch))[1:] else: return '&#%s;' % ord(ch) #---- mainline class _NoReflowFormatter(optparse.IndentedHelpFormatter): """An optparse formatter that does NOT reflow the description.""" def format_description(self, description): return description or "" def _test(): import doctest doctest.testmod() def main(argv=None): if argv is None: argv = sys.argv if not logging.root.handlers: logging.basicConfig() usage = "usage: %prog [PATHS...]" version = "%prog "+__version__ parser = optparse.OptionParser(prog="markdown2", usage=usage, version=version, description=cmdln_desc, formatter=_NoReflowFormatter()) parser.add_option("-v", "--verbose", dest="log_level", action="store_const", const=logging.DEBUG, help="more verbose output") parser.add_option("--encoding", help="specify encoding of text content") parser.add_option("--html4tags", action="store_true", default=False, help="use HTML 4 style for empty element tags") parser.add_option("-s", "--safe", metavar="MODE", dest="safe_mode", help="sanitize literal HTML: 'escape' escapes " "HTML meta chars, 'replace' replaces with an " "[HTML_REMOVED] note") parser.add_option("-x", "--extras", action="append", help="Turn on specific extra features (not part of " "the core Markdown spec). See above.") parser.add_option("--use-file-vars", help="Look for and use Emacs-style 'markdown-extras' " "file var to turn on extras. See " "<https://github.com/trentm/python-markdown2/wiki/Extras>") parser.add_option("--link-patterns-file", help="path to a link pattern file") parser.add_option("--self-test", action="store_true", help="run internal self-tests (some doctests)") parser.add_option("--compare", action="store_true", help="run against Markdown.pl as well (for testing)") parser.set_defaults(log_level=logging.INFO, compare=False, encoding="utf-8", safe_mode=None, use_file_vars=False) opts, paths = parser.parse_args() log.setLevel(opts.log_level) if opts.self_test: return _test() if opts.extras: extras = {} for s in opts.extras: splitter = re.compile("[,;: ]+") for e in splitter.split(s): if '=' in e: ename, earg = e.split('=', 1) try: earg = int(earg) except ValueError: pass else: ename, earg = e, None extras[ename] = earg else: extras = None if opts.link_patterns_file: link_patterns = [] f = open(opts.link_patterns_file) try: for i, line in enumerate(f.readlines()): if not line.strip(): continue if line.lstrip().startswith("#"): continue try: pat, href = line.rstrip().rsplit(None, 1) except ValueError: raise MarkdownError("%s:%d: invalid link pattern line: %r" % (opts.link_patterns_file, i+1, line)) link_patterns.append( (_regex_from_encoded_pattern(pat), href)) finally: f.close() else: link_patterns = None from os.path import join, dirname, abspath, exists markdown_pl = join(dirname(dirname(abspath(__file__))), "test", "Markdown.pl") if not paths: paths = ['-'] for path in paths: if path == '-': text = sys.stdin.read() else: fp = codecs.open(path, 'r', opts.encoding) text = fp.read() fp.close() if opts.compare: from subprocess import Popen, PIPE print("==== Markdown.pl ====") p = Popen('perl %s' % markdown_pl, shell=True, stdin=PIPE, stdout=PIPE, close_fds=True) p.stdin.write(text.encode('utf-8')) p.stdin.close() perl_html = p.stdout.read().decode('utf-8') if py3: sys.stdout.write(perl_html) else: sys.stdout.write(perl_html.encode( sys.stdout.encoding or "utf-8", 'xmlcharrefreplace')) print("==== markdown2.py ====") html = markdown(text, html4tags=opts.html4tags, safe_mode=opts.safe_mode, extras=extras, link_patterns=link_patterns, use_file_vars=opts.use_file_vars) if py3: sys.stdout.write(html) else: sys.stdout.write(html.encode( sys.stdout.encoding or "utf-8", 'xmlcharrefreplace')) if extras and "toc" in extras: log.debug("toc_html: " + html.toc_html.encode(sys.stdout.encoding or "utf-8", 'xmlcharrefreplace')) if opts.compare: test_dir = join(dirname(dirname(abspath(__file__))), "test") if exists(join(test_dir, "test_markdown2.py")): sys.path.insert(0, test_dir) from test_markdown2 import norm_html_from_html norm_html = norm_html_from_html(html) norm_perl_html = norm_html_from_html(perl_html) else: norm_html = html norm_perl_html = perl_html print("==== match? %r ====" % (norm_perl_html == norm_html)) template_html = u'''<!DOCTYPE html> <!-- Backdoc is a tool for backbone-like documentation generation. Backdoc main goal is to help to generate one page documentation from one markdown source file. https://github.com/chibisov/backdoc --> <html lang="ru"> <head> <meta charset="UTF-8"/> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> <meta name="HandheldFriendly" content="true" /> <title><!-- title --></title> <!-- Bootstrap --> <style type="text/css"> /*! * Bootstrap v3.0.0 * * Copyright 2013 Twitter, Inc * Licensed under the Apache License v2.0 * http://www.apache.org/licenses/LICENSE-2.0 * * Designed and built with all the love in the world by @mdo and @fat. *//*! normalize.css v2.1.0 | MIT License | git.io/normalize */ article,aside,details,figcaption,figure,footer,header,hgroup,main,nav,section,summary{display:block}audio,canvas,video{display:inline-block}audio:not([controls]){display:none;height:0}[hidden]{display:none}html{font-family:sans-serif;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%}body{margin:0}a:focus{outline:thin dotted}a:active,a:hover{outline:0}h1{margin:.67em 0;font-size:2em}abbr[title]{border-bottom:1px dotted}b,strong{font-weight:bold}dfn{font-style:italic}hr{height:0;-moz-box-sizing:content-box;box-sizing:content-box}mark{color:#000;background:#ff0}code,kbd,pre,samp{font-family:monospace,serif;font-size:1em}pre{white-space:pre-wrap}q{quotes:"\201C" "\201D" "\2018" "\2019"}small{font-size:80%}sub,sup{position:relative;font-size:75%;line-height:0;vertical-align:baseline}sup{top:-0.5em}sub{bottom:-0.25em}img{border:0}svg:not(:root){overflow:hidden}figure{margin:0}fieldset{padding:.35em .625em .75em;margin:0 2px;border:1px solid #c0c0c0}legend{padding:0;border:0}button,input,select,textarea{margin:0;font-family:inherit;font-size:100%}button,input{line-height:normal}button,select{text-transform:none}button,html input[type="button"],input[type="reset"],input[type="submit"]{cursor:pointer;-webkit-appearance:button}button[disabled],html input[disabled]{cursor:default}input[type="checkbox"],input[type="radio"]{padding:0;box-sizing:border-box}input[type="search"]{-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;-webkit-appearance:textfield}input[type="search"]::-webkit-search-cancel-button,input[type="search"]::-webkit-search-decoration{-webkit-appearance:none}button::-moz-focus-inner,input::-moz-focus-inner{padding:0;border:0}textarea{overflow:auto;vertical-align:top}table{border-collapse:collapse;border-spacing:0}@media print{*{color:#000!important;text-shadow:none!important;background:transparent!important;box-shadow:none!important}a,a:visited{text-decoration:underline}a[href]:after{content:" (" attr(href) ")"}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100%!important}@page{margin:2cm .5cm}p,h2,h3{orphans:3;widows:3}h2,h3{page-break-after:avoid}.navbar{display:none}.table td,.table th{background-color:#fff!important}.btn>.caret,.dropup>.btn>.caret{border-top-color:#000!important}.label{border:1px solid #000}.table{border-collapse:collapse!important}.table-bordered th,.table-bordered td{border:1px solid #ddd!important}}*{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}html{font-size:62.5%;-webkit-tap-highlight-color:rgba(0,0,0,0)}body{font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px;line-height:1.428571429;color:#333;background-color:#fff}input,button,select,textarea{font-family:inherit;font-size:inherit;line-height:inherit}a{color:#428bca;text-decoration:none}a:hover,a:focus{color:#2a6496;text-decoration:underline}a:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}img{vertical-align:middle}.img-responsive{display:inline-block;height:auto;max-width:100%}.img-rounded{border-radius:6px}.img-circle{border-radius:500px}hr{margin-top:20px;margin-bottom:20px;border:0;border-top:1px solid #eee}p{margin:0 0 10px}.lead{margin-bottom:20px;font-size:16.099999999999998px;font-weight:200;line-height:1.4}@media(min-width:768px){.lead{font-size:21px}}small{font-size:85%}cite{font-style:normal}.text-muted{color:#999}.text-primary{color:#428bca}.text-warning{color:#c09853}.text-danger{color:#b94a48}.text-success{color:#468847}.text-info{color:#3a87ad}.text-left{text-align:left}.text-right{text-align:right}.text-center{text-align:center}h1,h2,h3,h4,h5,h6,.h1,.h2,.h3,.h4,.h5,.h6{font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-weight:500;line-height:1.1}h1 small,h2 small,h3 small,h4 small,h5 small,h6 small,.h1 small,.h2 small,.h3 small,.h4 small,.h5 small,.h6 small{font-weight:normal;line-height:1;color:#999}h1,h2,h3{margin-top:20px;margin-bottom:10px}h4,h5,h6{margin-top:10px;margin-bottom:10px}h1,.h1{font-size:38px}h2,.h2{font-size:32px}h3,.h3{font-size:24px}h4,.h4{font-size:18px}h5,.h5{font-size:14px}h6,.h6{font-size:12px}h1 small,.h1 small{font-size:24px}h2 small,.h2 small{font-size:18px}h3 small,.h3 small,h4 small,.h4 small{font-size:14px}.page-header{padding-bottom:9px;margin:40px 0 20px;border-bottom:1px solid #eee}ul,ol{margin-top:0;margin-bottom:10px}ul ul,ol ul,ul ol,ol ol{margin-bottom:0}.list-unstyled{padding-left:0;list-style:none}.list-inline{padding-left:0;list-style:none}.list-inline>li{display:inline-block;padding-right:5px;padding-left:5px}dl{margin-bottom:20px}dt,dd{line-height:1.428571429}dt{font-weight:bold}dd{margin-left:0}.dl-horizontal dt{float:left;width:160px;overflow:hidden;clear:left;text-align:right;text-overflow:ellipsis;white-space:nowrap}.dl-horizontal dd{margin-left:180px}.dl-horizontal dd:before,.dl-horizontal dd:after{display:table;content:" "}.dl-horizontal dd:after{clear:both}.dl-horizontal dd:before,.dl-horizontal dd:after{display:table;content:" "}.dl-horizontal dd:after{clear:both}abbr[title],abbr[data-original-title]{cursor:help;border-bottom:1px dotted #999}abbr.initialism{font-size:90%;text-transform:uppercase}blockquote{padding:10px 20px;margin:0 0 20px;border-left:5px solid #eee}blockquote p{font-size:17.5px;font-weight:300;line-height:1.25}blockquote p:last-child{margin-bottom:0}blockquote small{display:block;line-height:1.428571429;color:#999}blockquote small:before{content:'\2014 \00A0'}blockquote.pull-right{float:right;padding-right:15px;padding-left:0;border-right:5px solid #eee;border-left:0}blockquote.pull-right p,blockquote.pull-right small{text-align:right}blockquote.pull-right small:before{content:''}blockquote.pull-right small:after{content:'\00A0 \2014'}q:before,q:after,blockquote:before,blockquote:after{content:""}address{display:block;margin-bottom:20px;font-style:normal;line-height:1.428571429}code,pre{font-family:Monaco,Menlo,Consolas,"Courier New",monospace}code{padding:2px 4px;font-size:90%;color:#c7254e;white-space:nowrap;background-color:#f9f2f4;border-radius:4px}pre{display:block;padding:9.5px;margin:0 0 10px;font-size:13px;line-height:1.428571429;color:#333;word-break:break-all;word-wrap:break-word;background-color:#f5f5f5;border:1px solid #ccc;border-radius:4px}pre.prettyprint{margin-bottom:20px}pre code{padding:0;color:inherit;white-space:pre-wrap;background-color:transparent;border:0}.pre-scrollable{max-height:340px;overflow-y:scroll}.container{margin-right:auto;margin-left:auto}.container:before,.container:after{display:table;content:" "}.container:after{clear:both}.container:before,.container:after{display:table;content:" "}.container:after{clear:both}.row:before,.row:after{display:table;content:" "}.row:after{clear:both}.row:before,.row:after{display:table;content:" "}.row:after{clear:both}@media(min-width:768px){.row{margin-right:-15px;margin-left:-15px}}.row .row{margin-right:-15px;margin-left:-15px}.col-1,.col-2,.col-3,.col-4,.col-5,.col-6,.col-7,.col-8,.col-9,.col-10,.col-11,.col-12,.col-sm-1,.col-sm-2,.col-sm-3,.col-sm-4,.col-sm-5,.col-sm-6,.col-sm-7,.col-sm-8,.col-sm-9,.col-sm-10,.col-sm-11,.col-sm-12,.col-lg-1,.col-lg-2,.col-lg-3,.col-lg-4,.col-lg-5,.col-lg-6,.col-lg-7,.col-lg-8,.col-lg-9,.col-lg-10,.col-lg-11,.col-lg-12{position:relative;min-height:1px;padding-right:15px;padding-left:15px}.col-1,.col-2,.col-3,.col-4,.col-5,.col-6,.col-7,.col-8,.col-9,.col-10,.col-11,.col-12{float:left}.col-1{width:8.333333333333332%}.col-2{width:16.666666666666664%}.col-3{width:25%}.col-4{width:33.33333333333333%}.col-5{width:41.66666666666667%}.col-6{width:50%}.col-7{width:58.333333333333336%}.col-8{width:66.66666666666666%}.col-9{width:75%}.col-10{width:83.33333333333334%}.col-11{width:91.66666666666666%}.col-12{width:100%}@media(min-width:768px){.container{max-width:728px}.col-sm-1,.col-sm-2,.col-sm-3,.col-sm-4,.col-sm-5,.col-sm-6,.col-sm-7,.col-sm-8,.col-sm-9,.col-sm-10,.col-sm-11,.col-sm-12{float:left}.col-sm-1{width:8.333333333333332%}.col-sm-2{width:16.666666666666664%}.col-sm-3{width:25%}.col-sm-4{width:33.33333333333333%}.col-sm-5{width:41.66666666666667%}.col-sm-6{width:50%}.col-sm-7{width:58.333333333333336%}.col-sm-8{width:66.66666666666666%}.col-sm-9{width:75%}.col-sm-10{width:83.33333333333334%}.col-sm-11{width:91.66666666666666%}.col-sm-12{width:100%}.col-push-1{left:8.333333333333332%}.col-push-2{left:16.666666666666664%}.col-push-3{left:25%}.col-push-4{left:33.33333333333333%}.col-push-5{left:41.66666666666667%}.col-push-6{left:50%}.col-push-7{left:58.333333333333336%}.col-push-8{left:66.66666666666666%}.col-push-9{left:75%}.col-push-10{left:83.33333333333334%}.col-push-11{left:91.66666666666666%}.col-pull-1{right:8.333333333333332%}.col-pull-2{right:16.666666666666664%}.col-pull-3{right:25%}.col-pull-4{right:33.33333333333333%}.col-pull-5{right:41.66666666666667%}.col-pull-6{right:50%}.col-pull-7{right:58.333333333333336%}.col-pull-8{right:66.66666666666666%}.col-pull-9{right:75%}.col-pull-10{right:83.33333333333334%}.col-pull-11{right:91.66666666666666%}}@media(min-width:992px){.container{max-width:940px}.col-lg-1,.col-lg-2,.col-lg-3,.col-lg-4,.col-lg-5,.col-lg-6,.col-lg-7,.col-lg-8,.col-lg-9,.col-lg-10,.col-lg-11,.col-lg-12{float:left}.col-lg-1{width:8.333333333333332%}.col-lg-2{width:16.666666666666664%}.col-lg-3{width:25%}.col-lg-4{width:33.33333333333333%}.col-lg-5{width:41.66666666666667%}.col-lg-6{width:50%}.col-lg-7{width:58.333333333333336%}.col-lg-8{width:66.66666666666666%}.col-lg-9{width:75%}.col-lg-10{width:83.33333333333334%}.col-lg-11{width:91.66666666666666%}.col-lg-12{width:100%}.col-offset-1{margin-left:8.333333333333332%}.col-offset-2{margin-left:16.666666666666664%}.col-offset-3{margin-left:25%}.col-offset-4{margin-left:33.33333333333333%}.col-offset-5{margin-left:41.66666666666667%}.col-offset-6{margin-left:50%}.col-offset-7{margin-left:58.333333333333336%}.col-offset-8{margin-left:66.66666666666666%}.col-offset-9{margin-left:75%}.col-offset-10{margin-left:83.33333333333334%}.col-offset-11{margin-left:91.66666666666666%}}@media(min-width:1200px){.container{max-width:1170px}}table{max-width:100%;background-color:transparent}th{text-align:left}.table{width:100%;margin-bottom:20px}.table thead>tr>th,.table tbody>tr>th,.table tfoot>tr>th,.table thead>tr>td,.table tbody>tr>td,.table tfoot>tr>td{padding:8px;line-height:1.428571429;vertical-align:top;border-top:1px solid #ddd}.table thead>tr>th{vertical-align:bottom}.table caption+thead tr:first-child th,.table colgroup+thead tr:first-child th,.table thead:first-child tr:first-child th,.table caption+thead tr:first-child td,.table colgroup+thead tr:first-child td,.table thead:first-child tr:first-child td{border-top:0}.table tbody+tbody{border-top:2px solid #ddd}.table .table{background-color:#fff}.table-condensed thead>tr>th,.table-condensed tbody>tr>th,.table-condensed tfoot>tr>th,.table-condensed thead>tr>td,.table-condensed tbody>tr>td,.table-condensed tfoot>tr>td{padding:5px}.table-bordered{border:1px solid #ddd}.table-bordered>thead>tr>th,.table-bordered>tbody>tr>th,.table-bordered>tfoot>tr>th,.table-bordered>thead>tr>td,.table-bordered>tbody>tr>td,.table-bordered>tfoot>tr>td{border:1px solid #ddd}.table-striped>tbody>tr:nth-child(odd)>td,.table-striped>tbody>tr:nth-child(odd)>th{background-color:#f9f9f9}.table-hover>tbody>tr:hover>td,.table-hover>tbody>tr:hover>th{background-color:#f5f5f5}table col[class^="col-"]{display:table-column;float:none}table td[class^="col-"],table th[class^="col-"]{display:table-cell;float:none}.table>thead>tr>td.active,.table>tbody>tr>td.active,.table>tfoot>tr>td.active,.table>thead>tr>th.active,.table>tbody>tr>th.active,.table>tfoot>tr>th.active,.table>thead>tr.active>td,.table>tbody>tr.active>td,.table>tfoot>tr.active>td,.table>thead>tr.active>th,.table>tbody>tr.active>th,.table>tfoot>tr.active>th{background-color:#f5f5f5}.table>thead>tr>td.success,.table>tbody>tr>td.success,.table>tfoot>tr>td.success,.table>thead>tr>th.success,.table>tbody>tr>th.success,.table>tfoot>tr>th.success,.table>thead>tr.success>td,.table>tbody>tr.success>td,.table>tfoot>tr.success>td,.table>thead>tr.success>th,.table>tbody>tr.success>th,.table>tfoot>tr.success>th{background-color:#dff0d8;border-color:#d6e9c6}.table>thead>tr>td.danger,.table>tbody>tr>td.danger,.table>tfoot>tr>td.danger,.table>thead>tr>th.danger,.table>tbody>tr>th.danger,.table>tfoot>tr>th.danger,.table>thead>tr.danger>td,.table>tbody>tr.danger>td,.table>tfoot>tr.danger>td,.table>thead>tr.danger>th,.table>tbody>tr.danger>th,.table>tfoot>tr.danger>th{background-color:#f2dede;border-color:#eed3d7}.table>thead>tr>td.warning,.table>tbody>tr>td.warning,.table>tfoot>tr>td.warning,.table>thead>tr>th.warning,.table>tbody>tr>th.warning,.table>tfoot>tr>th.warning,.table>thead>tr.warning>td,.table>tbody>tr.warning>td,.table>tfoot>tr.warning>td,.table>thead>tr.warning>th,.table>tbody>tr.warning>th,.table>tfoot>tr.warning>th{background-color:#fcf8e3;border-color:#fbeed5}.table-hover>tbody>tr>td.success:hover,.table-hover>tbody>tr>th.success:hover,.table-hover>tbody>tr.success:hover>td{background-color:#d0e9c6;border-color:#c9e2b3}.table-hover>tbody>tr>td.danger:hover,.table-hover>tbody>tr>th.danger:hover,.table-hover>tbody>tr.danger:hover>td{background-color:#ebcccc;border-color:#e6c1c7}.table-hover>tbody>tr>td.warning:hover,.table-hover>tbody>tr>th.warning:hover,.table-hover>tbody>tr.warning:hover>td{background-color:#faf2cc;border-color:#f8e5be}fieldset{padding:0;margin:0;border:0}legend{display:block;width:100%;padding:0;margin-bottom:20px;font-size:21px;line-height:inherit;color:#333;border:0;border-bottom:1px solid #e5e5e5}label{display:inline-block;margin-bottom:5px;font-weight:bold}input[type="search"]{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}input[type="radio"],input[type="checkbox"]{margin:4px 0 0;margin-top:1px \9;line-height:normal}input[type="file"]{display:block}select[multiple],select[size]{height:auto}select optgroup{font-family:inherit;font-size:inherit;font-style:inherit}input[type="file"]:focus,input[type="radio"]:focus,input[type="checkbox"]:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}input[type="number"]::-webkit-outer-spin-button,input[type="number"]::-webkit-inner-spin-button{height:auto}.form-control:-moz-placeholder{color:#999}.form-control::-moz-placeholder{color:#999}.form-control:-ms-input-placeholder{color:#999}.form-control::-webkit-input-placeholder{color:#999}.form-control{display:block;width:100%;height:38px;padding:8px 12px;font-size:14px;line-height:1.428571429;color:#555;vertical-align:middle;background-color:#fff;border:1px solid #ccc;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);-webkit-transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s;transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s}.form-control:focus{border-color:rgba(82,168,236,0.8);outline:0;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6)}.form-control[disabled],.form-control[readonly],fieldset[disabled] .form-control{cursor:not-allowed;background-color:#eee}textarea.form-control{height:auto}.form-group{margin-bottom:15px}.radio,.checkbox{display:block;min-height:20px;padding-left:20px;margin-top:10px;margin-bottom:10px;vertical-align:middle}.radio label,.checkbox label{display:inline;margin-bottom:0;font-weight:normal;cursor:pointer}.radio input[type="radio"],.radio-inline input[type="radio"],.checkbox input[type="checkbox"],.checkbox-inline input[type="checkbox"]{float:left;margin-left:-20px}.radio+.radio,.checkbox+.checkbox{margin-top:-5px}.radio-inline,.checkbox-inline{display:inline-block;padding-left:20px;margin-bottom:0;font-weight:normal;vertical-align:middle;cursor:pointer}.radio-inline+.radio-inline,.checkbox-inline+.checkbox-inline{margin-top:0;margin-left:10px}.form-control.input-large{height:56px;padding:14px 16px;font-size:18px;border-radius:6px}.form-control.input-small{height:30px;padding:5px 10px;font-size:12px;border-radius:3px}select.input-large{height:56px;line-height:56px}select.input-small{height:30px;line-height:30px}.has-warning .help-block,.has-warning .control-label{color:#c09853}.has-warning .form-control{padding-right:32px;border-color:#c09853;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075)}.has-warning .form-control:focus{border-color:#a47e3c;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #dbc59e;box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #dbc59e}.has-warning .input-group-addon{color:#c09853;background-color:#fcf8e3;border-color:#c09853}.has-error .help-block,.has-error .control-label{color:#b94a48}.has-error .form-control{padding-right:32px;border-color:#b94a48;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075)}.has-error .form-control:focus{border-color:#953b39;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #d59392;box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #d59392}.has-error .input-group-addon{color:#b94a48;background-color:#f2dede;border-color:#b94a48}.has-success .help-block,.has-success .control-label{color:#468847}.has-success .form-control{padding-right:32px;border-color:#468847;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075)}.has-success .form-control:focus{border-color:#356635;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7aba7b;box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7aba7b}.has-success .input-group-addon{color:#468847;background-color:#dff0d8;border-color:#468847}.help-block{display:block;margin-top:5px;margin-bottom:10px;color:#737373}.input-group{display:table;border-collapse:separate}.input-group.col{float:none;padding-right:0;padding-left:0}.input-group .form-control{width:100%;margin-bottom:0}.input-group-addon,.input-group-btn,.input-group .form-control{display:table-cell}.input-group-addon:not(:first-child):not(:last-child),.input-group-btn:not(:first-child):not(:last-child),.input-group .form-control:not(:first-child):not(:last-child){border-radius:0}.input-group-addon,.input-group-btn{width:1%;white-space:nowrap;vertical-align:middle}.input-group-addon{padding:8px 12px;font-size:14px;font-weight:normal;line-height:1.428571429;text-align:center;background-color:#eee;border:1px solid #ccc;border-radius:4px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.input-group-addon.input-small{padding:5px 10px;font-size:12px;border-radius:3px}.input-group-addon.input-large{padding:14px 16px;font-size:18px;border-radius:6px}.input-group .form-control:first-child,.input-group-addon:first-child,.input-group-btn:first-child>.btn,.input-group-btn:first-child>.dropdown-toggle,.input-group-btn:last-child>.btn:not(:last-child):not(.dropdown-toggle){border-top-right-radius:0;border-bottom-right-radius:0}.input-group-addon:first-child{border-right:0}.input-group .form-control:last-child,.input-group-addon:last-child,.input-group-btn:last-child>.btn,.input-group-btn:last-child>.dropdown-toggle,.input-group-btn:first-child>.btn:not(:first-child){border-bottom-left-radius:0;border-top-left-radius:0}.input-group-addon:last-child{border-left:0}.input-group-btn{position:relative;white-space:nowrap}.input-group-btn>.btn{position:relative}.input-group-btn>.btn+.btn{margin-left:-4px}.input-group-btn>.btn:hover,.input-group-btn>.btn:active{z-index:2}.form-inline .form-control,.form-inline .radio,.form-inline .checkbox{display:inline-block}.form-inline .radio,.form-inline .checkbox{margin-top:0;margin-bottom:0}.form-horizontal .control-label{padding-top:6px}.form-horizontal .form-group:before,.form-horizontal .form-group:after{display:table;content:" "}.form-horizontal .form-group:after{clear:both}.form-horizontal .form-group:before,.form-horizontal .form-group:after{display:table;content:" "}.form-horizontal .form-group:after{clear:both}@media(min-width:768px){.form-horizontal .form-group{margin-right:-15px;margin-left:-15px}}.form-horizontal .form-group .row{margin-right:-15px;margin-left:-15px}@media(min-width:768px){.form-horizontal .control-label{text-align:right}}.btn{display:inline-block;padding:8px 12px;margin-bottom:0;font-size:14px;font-weight:500;line-height:1.428571429;text-align:center;white-space:nowrap;vertical-align:middle;cursor:pointer;border:1px solid transparent;border-radius:4px}.btn:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn:hover,.btn:focus{color:#fff;text-decoration:none}.btn:active,.btn.active{outline:0;-webkit-box-shadow:inset 0 3px 5px rgba(0,0,0,0.125);box-shadow:inset 0 3px 5px rgba(0,0,0,0.125)}.btn.disabled,.btn[disabled],fieldset[disabled] .btn{pointer-events:none;cursor:default;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;box-shadow:none}.btn-default{color:#fff;background-color:#474949;border-color:#474949}.btn-default:hover,.btn-default:focus,.btn-default:active,.btn-default.active{background-color:#3a3c3c;border-color:#2e2f2f}.btn-default.disabled,.btn-default[disabled],fieldset[disabled] .btn-default,.btn-default.disabled:hover,.btn-default[disabled]:hover,fieldset[disabled] .btn-default:hover,.btn-default.disabled:focus,.btn-default[disabled]:focus,fieldset[disabled] .btn-default:focus,.btn-default.disabled:active,.btn-default[disabled]:active,fieldset[disabled] .btn-default:active,.btn-default.disabled.active,.btn-default[disabled].active,fieldset[disabled] .btn-default.active{background-color:#474949;border-color:#474949}.btn-primary{color:#fff;background-color:#428bca;border-color:#428bca}.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active{background-color:#357ebd;border-color:#3071a9}.btn-primary.disabled,.btn-primary[disabled],fieldset[disabled] .btn-primary,.btn-primary.disabled:hover,.btn-primary[disabled]:hover,fieldset[disabled] .btn-primary:hover,.btn-primary.disabled:focus,.btn-primary[disabled]:focus,fieldset[disabled] .btn-primary:focus,.btn-primary.disabled:active,.btn-primary[disabled]:active,fieldset[disabled] .btn-primary:active,.btn-primary.disabled.active,.btn-primary[disabled].active,fieldset[disabled] .btn-primary.active{background-color:#428bca;border-color:#428bca}.btn-warning{color:#fff;background-color:#f0ad4e;border-color:#f0ad4e}.btn-warning:hover,.btn-warning:focus,.btn-warning:active,.btn-warning.active{background-color:#eea236;border-color:#ec971f}.btn-warning.disabled,.btn-warning[disabled],fieldset[disabled] .btn-warning,.btn-warning.disabled:hover,.btn-warning[disabled]:hover,fieldset[disabled] .btn-warning:hover,.btn-warning.disabled:focus,.btn-warning[disabled]:focus,fieldset[disabled] .btn-warning:focus,.btn-warning.disabled:active,.btn-warning[disabled]:active,fieldset[disabled] .btn-warning:active,.btn-warning.disabled.active,.btn-warning[disabled].active,fieldset[disabled] .btn-warning.active{background-color:#f0ad4e;border-color:#f0ad4e}.btn-danger{color:#fff;background-color:#d9534f;border-color:#d9534f}.btn-danger:hover,.btn-danger:focus,.btn-danger:active,.btn-danger.active{background-color:#d43f3a;border-color:#c9302c}.btn-danger.disabled,.btn-danger[disabled],fieldset[disabled] .btn-danger,.btn-danger.disabled:hover,.btn-danger[disabled]:hover,fieldset[disabled] .btn-danger:hover,.btn-danger.disabled:focus,.btn-danger[disabled]:focus,fieldset[disabled] .btn-danger:focus,.btn-danger.disabled:active,.btn-danger[disabled]:active,fieldset[disabled] .btn-danger:active,.btn-danger.disabled.active,.btn-danger[disabled].active,fieldset[disabled] .btn-danger.active{background-color:#d9534f;border-color:#d9534f}.btn-success{color:#fff;background-color:#5cb85c;border-color:#5cb85c}.btn-success:hover,.btn-success:focus,.btn-success:active,.btn-success.active{background-color:#4cae4c;border-color:#449d44}.btn-success.disabled,.btn-success[disabled],fieldset[disabled] .btn-success,.btn-success.disabled:hover,.btn-success[disabled]:hover,fieldset[disabled] .btn-success:hover,.btn-success.disabled:focus,.btn-success[disabled]:focus,fieldset[disabled] .btn-success:focus,.btn-success.disabled:active,.btn-success[disabled]:active,fieldset[disabled] .btn-success:active,.btn-success.disabled.active,.btn-success[disabled].active,fieldset[disabled] .btn-success.active{background-color:#5cb85c;border-color:#5cb85c}.btn-info{color:#fff;background-color:#5bc0de;border-color:#5bc0de}.btn-info:hover,.btn-info:focus,.btn-info:active,.btn-info.active{background-color:#46b8da;border-color:#31b0d5}.btn-info.disabled,.btn-info[disabled],fieldset[disabled] .btn-info,.btn-info.disabled:hover,.btn-info[disabled]:hover,fieldset[disabled] .btn-info:hover,.btn-info.disabled:focus,.btn-info[disabled]:focus,fieldset[disabled] .btn-info:focus,.btn-info.disabled:active,.btn-info[disabled]:active,fieldset[disabled] .btn-info:active,.btn-info.disabled.active,.btn-info[disabled].active,fieldset[disabled] .btn-info.active{background-color:#5bc0de;border-color:#5bc0de}.btn-link{font-weight:normal;color:#428bca;cursor:pointer;border-radius:0}.btn-link,.btn-link:active,.btn-link[disabled],fieldset[disabled] .btn-link{background-color:transparent;-webkit-box-shadow:none;box-shadow:none}.btn-link,.btn-link:hover,.btn-link:focus,.btn-link:active{border-color:transparent}.btn-link:hover,.btn-link:focus{color:#2a6496;text-decoration:underline;background-color:transparent}.btn-link[disabled]:hover,fieldset[disabled] .btn-link:hover,.btn-link[disabled]:focus,fieldset[disabled] .btn-link:focus{color:#333;text-decoration:none}.btn-large{padding:14px 16px;font-size:18px;border-radius:6px}.btn-small{padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}.btn-block{display:block;width:100%;padding-right:0;padding-left:0}.btn-block+.btn-block{margin-top:5px}input[type="submit"].btn-block,input[type="reset"].btn-block,input[type="button"].btn-block{width:100%}.fade{opacity:0;-webkit-transition:opacity .15s linear;transition:opacity .15s linear}.fade.in{opacity:1}.collapse{display:none}.collapse.in{display:block}.collapsing{position:relative;height:0;overflow:hidden;-webkit-transition:height .35s ease;transition:height .35s ease}.caret{display:inline-block;width:0;height:0;margin-left:2px;vertical-align:middle;border-top:4px solid #000;border-right:4px solid transparent;border-left:4px solid transparent;content:""}.dropdown-menu{position:absolute;top:100%;left:0;z-index:1000;display:none;float:left;min-width:160px;padding:5px 0;margin:2px 0 0;list-style:none;background-color:#fff;border:1px solid #ccc;border:1px solid rgba(0,0,0,0.15);border-radius:4px;-webkit-box-shadow:0 6px 12px rgba(0,0,0,0.175);box-shadow:0 6px 12px rgba(0,0,0,0.175);background-clip:padding-box}.dropdown-menu.pull-right{right:0;left:auto}.dropdown-menu .divider{height:1px;margin:9px 0;overflow:hidden;background-color:#e5e5e5}.dropdown-menu>li>a{display:block;padding:3px 20px;clear:both;font-weight:normal;line-height:1.428571429;color:#333;white-space:nowrap}.dropdown-menu>li>a:hover,.dropdown-menu>li>a:focus{color:#fff;text-decoration:none;background-color:#357ebd;background-image:-webkit-gradient(linear,left 0,left 100%,from(#428bca),to(#357ebd));background-image:-webkit-linear-gradient(top,#428bca,0%,#357ebd,100%);background-image:-moz-linear-gradient(top,#428bca 0,#357ebd 100%);background-image:linear-gradient(to bottom,#428bca 0,#357ebd 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff428bca',endColorstr='#ff357ebd',GradientType=0)}.dropdown-menu>.active>a,.dropdown-menu>.active>a:hover,.dropdown-menu>.active>a:focus{color:#fff;text-decoration:none;background-color:#357ebd;background-image:-webkit-gradient(linear,left 0,left 100%,from(#428bca),to(#357ebd));background-image:-webkit-linear-gradient(top,#428bca,0%,#357ebd,100%);background-image:-moz-linear-gradient(top,#428bca 0,#357ebd 100%);background-image:linear-gradient(to bottom,#428bca 0,#357ebd 100%);background-repeat:repeat-x;outline:0;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff428bca',endColorstr='#ff357ebd',GradientType=0)}.dropdown-menu>.disabled>a,.dropdown-menu>.disabled>a:hover,.dropdown-menu>.disabled>a:focus{color:#999}.dropdown-menu>.disabled>a:hover,.dropdown-menu>.disabled>a:focus{text-decoration:none;cursor:not-allowed;background-color:transparent;background-image:none;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.open>.dropdown-menu{display:block}.open>a{outline:0}.dropdown-header{display:block;padding:3px 20px;font-size:12px;line-height:1.428571429;color:#999}.dropdown-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:990}.pull-right>.dropdown-menu{right:0;left:auto}.dropup .caret,.navbar-fixed-bottom .dropdown .caret{border-top:0;border-bottom:4px solid #000;content:""}.dropup .dropdown-menu,.navbar-fixed-bottom .dropdown .dropdown-menu{top:auto;bottom:100%;margin-bottom:1px}.list-group{padding-left:0;margin-bottom:20px;background-color:#fff}.list-group-item{position:relative;display:block;padding:10px 30px 10px 15px;margin-bottom:-1px;border:1px solid #ddd}.list-group-item:first-child{border-top-right-radius:4px;border-top-left-radius:4px}.list-group-item:last-child{margin-bottom:0;border-bottom-right-radius:4px;border-bottom-left-radius:4px}.list-group-item>.badge{float:right;margin-right:-15px}.list-group-item-heading{margin-top:0;margin-bottom:5px}.list-group-item-text{margin-bottom:0;line-height:1.3}a.list-group-item .list-group-item-heading{color:#333}a.list-group-item .list-group-item-text{color:#555}a.list-group-item:hover,a.list-group-item:focus{text-decoration:none;background-color:#f5f5f5}a.list-group-item.active{z-index:2;color:#fff;background-color:#428bca;border-color:#428bca}a.list-group-item.active .list-group-item-heading{color:inherit}a.list-group-item.active .list-group-item-text{color:#e1edf7}.panel{padding:15px;margin-bottom:20px;background-color:#fff;border:1px solid #ddd;border-radius:4px;-webkit-box-shadow:0 1px 1px rgba(0,0,0,0.05);box-shadow:0 1px 1px rgba(0,0,0,0.05)}.panel-heading{padding:10px 15px;margin:-15px -15px 15px;background-color:#f5f5f5;border-bottom:1px solid #ddd;border-top-right-radius:3px;border-top-left-radius:3px}.panel-title{margin-top:0;margin-bottom:0;font-size:17.5px;font-weight:500}.panel-footer{padding:10px 15px;margin:15px -15px -15px;background-color:#f5f5f5;border-top:1px solid #ddd;border-bottom-right-radius:3px;border-bottom-left-radius:3px}.panel-primary{border-color:#428bca}.panel-primary .panel-heading{color:#fff;background-color:#428bca;border-color:#428bca}.panel-success{border-color:#d6e9c6}.panel-success .panel-heading{color:#468847;background-color:#dff0d8;border-color:#d6e9c6}.panel-warning{border-color:#fbeed5}.panel-warning .panel-heading{color:#c09853;background-color:#fcf8e3;border-color:#fbeed5}.panel-danger{border-color:#eed3d7}.panel-danger .panel-heading{color:#b94a48;background-color:#f2dede;border-color:#eed3d7}.panel-info{border-color:#bce8f1}.panel-info .panel-heading{color:#3a87ad;background-color:#d9edf7;border-color:#bce8f1}.list-group-flush{margin:15px -15px -15px}.list-group-flush .list-group-item{border-width:1px 0}.list-group-flush .list-group-item:first-child{border-top-right-radius:0;border-top-left-radius:0}.list-group-flush .list-group-item:last-child{border-bottom:0}.well{min-height:20px;padding:19px;margin-bottom:20px;background-color:#f5f5f5;border:1px solid #e3e3e3;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.05);box-shadow:inset 0 1px 1px rgba(0,0,0,0.05)}.well blockquote{border-color:#ddd;border-color:rgba(0,0,0,0.15)}.well-large{padding:24px;border-radius:6px}.well-small{padding:9px;border-radius:3px}.close{float:right;font-size:21px;font-weight:bold;line-height:1;color:#000;text-shadow:0 1px 0 #fff;opacity:.2;filter:alpha(opacity=20)}.close:hover,.close:focus{color:#000;text-decoration:none;cursor:pointer;opacity:.5;filter:alpha(opacity=50)}button.close{padding:0;cursor:pointer;background:transparent;border:0;-webkit-appearance:none}.nav{padding-left:0;margin-bottom:0;list-style:none}.nav:before,.nav:after{display:table;content:" "}.nav:after{clear:both}.nav:before,.nav:after{display:table;content:" "}.nav:after{clear:both}.nav>li{position:relative;display:block}.nav>li>a{position:relative;display:block;padding:10px 15px}.nav>li>a:hover,.nav>li>a:focus{text-decoration:none;background-color:#eee}.nav>li.disabled>a{color:#999}.nav>li.disabled>a:hover,.nav>li.disabled>a:focus{color:#999;text-decoration:none;cursor:not-allowed;background-color:transparent}.nav>li+.nav-header{margin-top:9px}.nav.open>a,.nav.open>a:hover,.nav.open>a:focus{color:#fff;background-color:#428bca;border-color:#428bca}.nav.open>a .caret,.nav.open>a:hover .caret,.nav.open>a:focus .caret{border-top-color:#fff;border-bottom-color:#fff}.nav>.pull-right{float:right}.nav .nav-divider{height:1px;margin:9px 0;overflow:hidden;background-color:#e5e5e5}.nav-tabs{border-bottom:1px solid #ddd}.nav-tabs>li{float:left;margin-bottom:-1px}.nav-tabs>li>a{margin-right:2px;line-height:1.428571429;border:1px solid transparent;border-radius:4px 4px 0 0}.nav-tabs>li>a:hover{border-color:#eee}.nav-tabs>li.active>a,.nav-tabs>li.active>a:hover,.nav-tabs>li.active>a:focus{color:#555;cursor:default;background-color:#fff;border:1px solid #ddd;border-bottom-color:transparent}.nav-tabs.nav-justified{width:100%;border-bottom:0}.nav-tabs.nav-justified>li{display:table-cell;float:none;width:1%}.nav-tabs.nav-justified>li>a{text-align:center}.nav-tabs.nav-justified>li>a{margin-right:0;border-bottom:1px solid #ddd}.nav-tabs.nav-justified>.active>a{border-bottom-color:#fff}.nav-pills>li{float:left}.nav-pills>li>a{border-radius:5px}.nav-pills>li+li{margin-left:2px}.nav-pills>li.active>a,.nav-pills>li.active>a:hover,.nav-pills>li.active>a:focus{color:#fff;background-color:#428bca}.nav-stacked>li{float:none}.nav-stacked>li+li>a{margin-top:2px;margin-left:0}.nav-justified{width:100%}.nav-justified>li{display:table-cell;float:none;width:1%}.nav-justified>li>a{text-align:center}.nav-tabs-justified{border-bottom:0}.nav-tabs-justified>li>a{margin-right:0;border-bottom:1px solid #ddd}.nav-tabs-justified>.active>a{border-bottom-color:#fff}.tabbable:before,.tabbable:after{display:table;content:" "}.tabbable:after{clear:both}.tabbable:before,.tabbable:after{display:table;content:" "}.tabbable:after{clear:both}.tab-content>.tab-pane,.pill-content>.pill-pane{display:none}.tab-content>.active,.pill-content>.active{display:block}.nav .caret{border-top-color:#428bca;border-bottom-color:#428bca}.nav a:hover .caret{border-top-color:#2a6496;border-bottom-color:#2a6496}.nav-tabs .dropdown-menu{margin-top:-1px;border-top-right-radius:0;border-top-left-radius:0}.navbar{position:relative;min-height:50px;padding-right:15px;padding-left:15px;margin-bottom:20px;background-color:#eee;border-radius:4px}.navbar:before,.navbar:after{display:table;content:" "}.navbar:after{clear:both}.navbar:before,.navbar:after{display:table;content:" "}.navbar:after{clear:both}.navbar-nav{margin-top:10px;margin-bottom:15px}.navbar-nav>li>a{padding-top:15px;padding-bottom:15px;line-height:20px;color:#777;border-radius:4px}.navbar-nav>li>a:hover,.navbar-nav>li>a:focus{color:#333;background-color:transparent}.navbar-nav>.active>a,.navbar-nav>.active>a:hover,.navbar-nav>.active>a:focus{color:#555;background-color:#d5d5d5}.navbar-nav>.disabled>a,.navbar-nav>.disabled>a:hover,.navbar-nav>.disabled>a:focus{color:#ccc;background-color:transparent}.navbar-nav.pull-right{width:100%}.navbar-static-top{border-radius:0}.navbar-fixed-top,.navbar-fixed-bottom{position:fixed;right:0;left:0;z-index:1030;border-radius:0}.navbar-fixed-top{top:0}.navbar-fixed-bottom{bottom:0;margin-bottom:0}.navbar-brand{display:block;max-width:200px;padding:15px 15px;margin-right:auto;margin-left:auto;font-size:18px;font-weight:500;line-height:20px;color:#777;text-align:center}.navbar-brand:hover,.navbar-brand:focus{color:#5e5e5e;text-decoration:none;background-color:transparent}.navbar-toggle{position:absolute;top:9px;right:10px;width:48px;height:32px;padding:8px 12px;background-color:transparent;border:1px solid #ddd;border-radius:4px}.navbar-toggle:hover,.navbar-toggle:focus{background-color:#ddd}.navbar-toggle .icon-bar{display:block;width:22px;height:2px;background-color:#ccc;border-radius:1px}.navbar-toggle .icon-bar+.icon-bar{margin-top:4px}.navbar-form{margin-top:6px;margin-bottom:6px}.navbar-form .form-control,.navbar-form .radio,.navbar-form .checkbox{display:inline-block}.navbar-form .radio,.navbar-form .checkbox{margin-top:0;margin-bottom:0}.navbar-nav>li>.dropdown-menu{margin-top:0;border-top-right-radius:0;border-top-left-radius:0}.navbar-fixed-bottom .navbar-nav>li>.dropdown-menu{border-bottom-right-radius:0;border-bottom-left-radius:0}.navbar-nav>.dropdown>a:hover .caret,.navbar-nav>.dropdown>a:focus .caret{border-top-color:#333;border-bottom-color:#333}.navbar-nav>.open>a,.navbar-nav>.open>a:hover,.navbar-nav>.open>a:focus{color:#555;background-color:#d5d5d5}.navbar-nav>.open>a .caret,.navbar-nav>.open>a:hover .caret,.navbar-nav>.open>a:focus .caret{border-top-color:#555;border-bottom-color:#555}.navbar-nav>.dropdown>a .caret{border-top-color:#777;border-bottom-color:#777}.navbar-nav.pull-right>li>.dropdown-menu,.navbar-nav>li>.dropdown-menu.pull-right{right:0;left:auto}.navbar-inverse{background-color:#222}.navbar-inverse .navbar-brand{color:#999}.navbar-inverse .navbar-brand:hover,.navbar-inverse .navbar-brand:focus{color:#fff;background-color:transparent}.navbar-inverse .navbar-text{color:#999}.navbar-inverse .navbar-nav>li>a{color:#999}.navbar-inverse .navbar-nav>li>a:hover,.navbar-inverse .navbar-nav>li>a:focus{color:#fff;background-color:transparent}.navbar-inverse .navbar-nav>.active>a,.navbar-inverse .navbar-nav>.active>a:hover,.navbar-inverse .navbar-nav>.active>a:focus{color:#fff;background-color:#080808}.navbar-inverse .navbar-nav>.disabled>a,.navbar-inverse .navbar-nav>.disabled>a:hover,.navbar-inverse .navbar-nav>.disabled>a:focus{color:#444;background-color:transparent}.navbar-inverse .navbar-toggle{border-color:#333}.navbar-inverse .navbar-toggle:hover,.navbar-inverse .navbar-toggle:focus{background-color:#333}.navbar-inverse .navbar-toggle .icon-bar{background-color:#fff}.navbar-inverse .navbar-nav>.open>a,.navbar-inverse .navbar-nav>.open>a:hover,.navbar-inverse .navbar-nav>.open>a:focus{color:#fff;background-color:#080808}.navbar-inverse .navbar-nav>.dropdown>a:hover .caret{border-top-color:#fff;border-bottom-color:#fff}.navbar-inverse .navbar-nav>.dropdown>a .caret{border-top-color:#999;border-bottom-color:#999}.navbar-inverse .navbar-nav>.open>a .caret,.navbar-inverse .navbar-nav>.open>a:hover .caret,.navbar-inverse .navbar-nav>.open>a:focus .caret{border-top-color:#fff;border-bottom-color:#fff}@media screen and (min-width:768px){.navbar-brand{float:left;margin-right:5px;margin-left:-15px}.navbar-nav{float:left;margin-top:0;margin-bottom:0}.navbar-nav>li{float:left}.navbar-nav>li>a{border-radius:0}.navbar-nav.pull-right{float:right;width:auto}.navbar-toggle{position:relative;top:auto;left:auto;display:none}.nav-collapse.collapse{display:block!important;height:auto!important;overflow:visible!important}}.navbar-btn{margin-top:6px}.navbar-text{margin-top:15px;margin-bottom:15px}.navbar-link{color:#777}.navbar-link:hover{color:#333}.navbar-inverse .navbar-link{color:#999}.navbar-inverse .navbar-link:hover{color:#fff}.btn .caret{border-top-color:#fff}.dropup .btn .caret{border-bottom-color:#fff}.btn-group,.btn-group-vertical{position:relative;display:inline-block;vertical-align:middle}.btn-group>.btn,.btn-group-vertical>.btn{position:relative;float:left}.btn-group>.btn:hover,.btn-group-vertical>.btn:hover,.btn-group>.btn:active,.btn-group-vertical>.btn:active{z-index:2}.btn-group .btn+.btn{margin-left:-1px}.btn-toolbar:before,.btn-toolbar:after{display:table;content:" "}.btn-toolbar:after{clear:both}.btn-toolbar:before,.btn-toolbar:after{display:table;content:" "}.btn-toolbar:after{clear:both}.btn-toolbar .btn-group{float:left}.btn-toolbar>.btn+.btn,.btn-toolbar>.btn-group+.btn,.btn-toolbar>.btn+.btn-group,.btn-toolbar>.btn-group+.btn-group{margin-left:5px}.btn-group>.btn:not(:first-child):not(:last-child):not(.dropdown-toggle){border-radius:0}.btn-group>.btn:first-child{margin-left:0}.btn-group>.btn:first-child:not(:last-child):not(.dropdown-toggle){border-top-right-radius:0;border-bottom-right-radius:0}.btn-group>.btn:last-child:not(:first-child),.btn-group>.dropdown-toggle:not(:first-child){border-bottom-left-radius:0;border-top-left-radius:0}.btn-group>.btn-group{float:left}.btn-group>.btn-group:not(:first-child):not(:last-child)>.btn{border-radius:0}.btn-group>.btn-group:first-child>.btn:last-child,.btn-group>.btn-group:first-child>.dropdown-toggle{border-top-right-radius:0;border-bottom-right-radius:0}.btn-group>.btn-group:last-child>.btn:first-child{border-bottom-left-radius:0;border-top-left-radius:0}.btn-group .dropdown-toggle:active,.btn-group.open .dropdown-toggle{outline:0}.btn-group>.btn+.dropdown-toggle{padding-right:8px;padding-left:8px}.btn-group>.btn-large+.dropdown-toggle{padding-right:12px;padding-left:12px}.btn-group.open .dropdown-toggle{-webkit-box-shadow:inset 0 3px 5px rgba(0,0,0,0.125);box-shadow:inset 0 3px 5px rgba(0,0,0,0.125)}.btn .caret{margin-left:0}.btn-large .caret{border-width:5px}.dropup .btn-large .caret{border-bottom-width:5px}.btn-group-vertical>.btn{display:block;float:none;width:100%;max-width:100%}.btn-group-vertical>.btn+.btn{margin-top:-1px}.btn-group-vertical .btn:not(:first-child):not(:last-child){border-radius:0}.btn-group-vertical .btn:first-child{border-bottom-right-radius:0;border-bottom-left-radius:0}.btn-group-vertical .btn:last-child{border-top-right-radius:0;border-top-left-radius:0}.btn-group-justified{display:table;width:100%}.btn-group-justified .btn{display:table-cell;float:none;width:1%}.btn-group[data-toggle="buttons"]>.btn>input[type="radio"],.btn-group[data-toggle="buttons"]>.btn>input[type="checkbox"]{display:none}.breadcrumb{padding:8px 15px;margin-bottom:20px;list-style:none;background-color:#f5f5f5;border-radius:4px}.breadcrumb>li{display:inline-block}.breadcrumb>li+li:before{padding:0 5px;color:#ccc;content:"/\00a0"}.breadcrumb>.active{color:#999}.pagination{display:inline-block;padding-left:0;margin:20px 0;border-radius:4px}.pagination>li{display:inline}.pagination>li>a,.pagination>li>span{float:left;padding:4px 12px;line-height:1.428571429;text-decoration:none;background-color:#fff;border:1px solid #ddd;border-left-width:0}.pagination>li:first-child>a,.pagination>li:first-child>span{border-left-width:1px;border-bottom-left-radius:4px;border-top-left-radius:4px}.pagination>li:last-child>a,.pagination>li:last-child>span{border-top-right-radius:4px;border-bottom-right-radius:4px}.pagination>li>a:hover,.pagination>li>a:focus,.pagination>.active>a,.pagination>.active>span{background-color:#f5f5f5}.pagination>.active>a,.pagination>.active>span{color:#999;cursor:default}.pagination>.disabled>span,.pagination>.disabled>a,.pagination>.disabled>a:hover,.pagination>.disabled>a:focus{color:#999;cursor:not-allowed;background-color:#fff}.pagination-large>li>a,.pagination-large>li>span{padding:14px 16px;font-size:18px}.pagination-large>li:first-child>a,.pagination-large>li:first-child>span{border-bottom-left-radius:6px;border-top-left-radius:6px}.pagination-large>li:last-child>a,.pagination-large>li:last-child>span{border-top-right-radius:6px;border-bottom-right-radius:6px}.pagination-small>li>a,.pagination-small>li>span{padding:5px 10px;font-size:12px}.pagination-small>li:first-child>a,.pagination-small>li:first-child>span{border-bottom-left-radius:3px;border-top-left-radius:3px}.pagination-small>li:last-child>a,.pagination-small>li:last-child>span{border-top-right-radius:3px;border-bottom-right-radius:3px}.pager{padding-left:0;margin:20px 0;text-align:center;list-style:none}.pager:before,.pager:after{display:table;content:" "}.pager:after{clear:both}.pager:before,.pager:after{display:table;content:" "}.pager:after{clear:both}.pager li{display:inline}.pager li>a,.pager li>span{display:inline-block;padding:5px 14px;background-color:#fff;border:1px solid #ddd;border-radius:15px}.pager li>a:hover,.pager li>a:focus{text-decoration:none;background-color:#f5f5f5}.pager .next>a,.pager .next>span{float:right}.pager .previous>a,.pager .previous>span{float:left}.pager .disabled>a,.pager .disabled>a:hover,.pager .disabled>a:focus,.pager .disabled>span{color:#999;cursor:not-allowed;background-color:#fff}.modal-open{overflow:hidden}.modal{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1040;display:none;overflow:auto;overflow-y:scroll}.modal.fade .modal-dialog{-webkit-transform:translate(0,-25%);-ms-transform:translate(0,-25%);transform:translate(0,-25%);-webkit-transition:-webkit-transform .3s ease-out;-moz-transition:-moz-transform .3s ease-out;-o-transition:-o-transform .3s ease-out;transition:transform .3s ease-out}.modal.fade.in .modal-dialog{-webkit-transform:translate(0,0);-ms-transform:translate(0,0);transform:translate(0,0)}.modal-dialog{position:relative;top:0;right:0;left:0;z-index:1050;width:auto;padding:10px}.modal-content{position:relative;background-color:#fff;border:1px solid #999;border:1px solid rgba(0,0,0,0.2);border-radius:6px;outline:0;-webkit-box-shadow:0 3px 9px rgba(0,0,0,0.5);box-shadow:0 3px 9px rgba(0,0,0,0.5);background-clip:padding-box}.modal-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1030;background-color:#000}.modal-backdrop.fade{opacity:0;filter:alpha(opacity=0)}.modal-backdrop.fade.in{opacity:.5;filter:alpha(opacity=50)}.modal-header{min-height:16.428571429px;padding:15px;border-bottom:1px solid #e5e5e5}.modal-header .close{margin-top:-2px}.modal-title{margin:0;line-height:1.428571429}.modal-body{position:relative;padding:20px}.modal-footer{padding:19px 20px 20px;margin-top:15px;text-align:right;border-top:1px solid #e5e5e5}.modal-footer:before,.modal-footer:after{display:table;content:" "}.modal-footer:after{clear:both}.modal-footer:before,.modal-footer:after{display:table;content:" "}.modal-footer:after{clear:both}.modal-footer .btn+.btn{margin-bottom:0;margin-left:5px}.modal-footer .btn-group .btn+.btn{margin-left:-1px}.modal-footer .btn-block+.btn-block{margin-left:0}@media screen and (min-width:768px){.modal-dialog{right:auto;left:50%;width:560px;padding-top:30px;padding-bottom:30px;margin-left:-280px}.modal-content{-webkit-box-shadow:0 5px 15px rgba(0,0,0,0.5);box-shadow:0 5px 15px rgba(0,0,0,0.5)}}.tooltip{position:absolute;z-index:1030;display:block;font-size:12px;line-height:1.4;opacity:0;filter:alpha(opacity=0);visibility:visible}.tooltip.in{opacity:1;filter:alpha(opacity=100)}.tooltip.top{padding:5px 0;margin-top:-3px}.tooltip.right{padding:0 5px;margin-left:3px}.tooltip.bottom{padding:5px 0;margin-top:3px}.tooltip.left{padding:0 5px;margin-left:-3px}.tooltip-inner{max-width:200px;padding:3px 8px;color:#fff;text-align:center;text-decoration:none;background-color:rgba(0,0,0,0.9);border-radius:4px}.tooltip-arrow{position:absolute;width:0;height:0;border-color:transparent;border-style:solid}.tooltip.top .tooltip-arrow{bottom:0;left:50%;margin-left:-5px;border-top-color:rgba(0,0,0,0.9);border-width:5px 5px 0}.tooltip.top-left .tooltip-arrow{bottom:0;left:5px;border-top-color:rgba(0,0,0,0.9);border-width:5px 5px 0}.tooltip.top-right .tooltip-arrow{right:5px;bottom:0;border-top-color:rgba(0,0,0,0.9);border-width:5px 5px 0}.tooltip.right .tooltip-arrow{top:50%;left:0;margin-top:-5px;border-right-color:rgba(0,0,0,0.9);border-width:5px 5px 5px 0}.tooltip.left .tooltip-arrow{top:50%;right:0;margin-top:-5px;border-left-color:rgba(0,0,0,0.9);border-width:5px 0 5px 5px}.tooltip.bottom .tooltip-arrow{top:0;left:50%;margin-left:-5px;border-bottom-color:rgba(0,0,0,0.9);border-width:0 5px 5px}.tooltip.bottom-left .tooltip-arrow{top:0;left:5px;border-bottom-color:rgba(0,0,0,0.9);border-width:0 5px 5px}.tooltip.bottom-right .tooltip-arrow{top:0;right:5px;border-bottom-color:rgba(0,0,0,0.9);border-width:0 5px 5px}.popover{position:absolute;top:0;left:0;z-index:1010;display:none;max-width:276px;padding:1px;text-align:left;white-space:normal;background-color:#fff;border:1px solid #ccc;border:1px solid rgba(0,0,0,0.2);border-radius:6px;-webkit-box-shadow:0 5px 10px rgba(0,0,0,0.2);box-shadow:0 5px 10px rgba(0,0,0,0.2);background-clip:padding-box;-webkit-bg-clip:padding-box;-moz-bg-clip:padding}.popover.top{margin-top:-10px}.popover.right{margin-left:10px}.popover.bottom{margin-top:10px}.popover.left{margin-left:-10px}.popover-title{padding:8px 14px;margin:0;font-size:14px;font-weight:normal;line-height:18px;background-color:#f7f7f7;border-bottom:1px solid #ebebeb;border-radius:5px 5px 0 0}.popover-content{padding:9px 14px}.popover .arrow,.popover .arrow:after{position:absolute;display:block;width:0;height:0;border-color:transparent;border-style:solid}.popover .arrow{border-width:11px}.popover .arrow:after{border-width:10px;content:""}.popover.top .arrow{bottom:-11px;left:50%;margin-left:-11px;border-top-color:#999;border-top-color:rgba(0,0,0,0.25);border-bottom-width:0}.popover.top .arrow:after{bottom:1px;margin-left:-10px;border-top-color:#fff;border-bottom-width:0;content:" "}.popover.right .arrow{top:50%;left:-11px;margin-top:-11px;border-right-color:#999;border-right-color:rgba(0,0,0,0.25);border-left-width:0}.popover.right .arrow:after{bottom:-10px;left:1px;border-right-color:#fff;border-left-width:0;content:" "}.popover.bottom .arrow{top:-11px;left:50%;margin-left:-11px;border-bottom-color:#999;border-bottom-color:rgba(0,0,0,0.25);border-top-width:0}.popover.bottom .arrow:after{top:1px;margin-left:-10px;border-bottom-color:#fff;border-top-width:0;content:" "}.popover.left .arrow{top:50%;right:-11px;margin-top:-11px;border-left-color:#999;border-left-color:rgba(0,0,0,0.25);border-right-width:0}.popover.left .arrow:after{right:1px;bottom:-10px;border-left-color:#fff;border-right-width:0;content:" "}.alert{padding:10px 35px 10px 15px;margin-bottom:20px;color:#c09853;background-color:#fcf8e3;border:1px solid #fbeed5;border-radius:4px}.alert h4{margin-top:0;color:inherit}.alert hr{border-top-color:#f8e5be}.alert .alert-link{font-weight:500;color:#a47e3c}.alert .close{position:relative;top:-2px;right:-21px;color:inherit}.alert-success{color:#468847;background-color:#dff0d8;border-color:#d6e9c6}.alert-success hr{border-top-color:#c9e2b3}.alert-success .alert-link{color:#356635}.alert-danger{color:#b94a48;background-color:#f2dede;border-color:#eed3d7}.alert-danger hr{border-top-color:#e6c1c7}.alert-danger .alert-link{color:#953b39}.alert-info{color:#3a87ad;background-color:#d9edf7;border-color:#bce8f1}.alert-info hr{border-top-color:#a6e1ec}.alert-info .alert-link{color:#2d6987}.alert-block{padding-top:15px;padding-bottom:15px}.alert-block>p,.alert-block>ul{margin-bottom:0}.alert-block p+p{margin-top:5px}.thumbnail,.img-thumbnail{padding:4px;line-height:1.428571429;background-color:#fff;border:1px solid #ddd;border-radius:4px;-webkit-transition:all .2s ease-in-out;transition:all .2s ease-in-out}.thumbnail{display:block}.thumbnail>img,.img-thumbnail{display:inline-block;height:auto;max-width:100%}a.thumbnail:hover,a.thumbnail:focus{border-color:#428bca}.thumbnail>img{margin-right:auto;margin-left:auto}.thumbnail .caption{padding:9px;color:#333}.media,.media-body{overflow:hidden;zoom:1}.media,.media .media{margin-top:15px}.media:first-child{margin-top:0}.media-object{display:block}.media-heading{margin:0 0 5px}.media>.pull-left{margin-right:10px}.media>.pull-right{margin-left:10px}.media-list{padding-left:0;list-style:none}.label{display:inline;padding:.25em .6em;font-size:75%;font-weight:500;line-height:1;color:#fff;text-align:center;white-space:nowrap;vertical-align:middle;background-color:#999;border-radius:.25em}.label[href]:hover,.label[href]:focus{color:#fff;text-decoration:none;cursor:pointer;background-color:#808080}.label-danger{background-color:#d9534f}.label-danger[href]:hover,.label-danger[href]:focus{background-color:#c9302c}.label-success{background-color:#5cb85c}.label-success[href]:hover,.label-success[href]:focus{background-color:#449d44}.label-warning{background-color:#f0ad4e}.label-warning[href]:hover,.label-warning[href]:focus{background-color:#ec971f}.label-info{background-color:#5bc0de}.label-info[href]:hover,.label-info[href]:focus{background-color:#31b0d5}.badge{display:inline-block;min-width:10px;padding:3px 7px;font-size:12px;font-weight:bold;line-height:1;color:#fff;text-align:center;white-space:nowrap;vertical-align:middle;background-color:#999;border-radius:10px}.badge:empty{display:none}a.badge:hover,a.badge:focus{color:#fff;text-decoration:none;cursor:pointer}.btn .badge{position:relative;top:-1px}a.list-group-item.active>.badge,.nav-pills>.active>a>.badge{color:#428bca;background-color:#fff}.nav-pills>li>a>.badge{margin-left:3px}@-webkit-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@-moz-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@-ms-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@-o-keyframes progress-bar-stripes{from{background-position:0 0}to{background-position:40px 0}}@keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}.progress{height:20px;margin-bottom:20px;overflow:hidden;background-color:#f5f5f5;border-radius:4px;-webkit-box-shadow:inset 0 1px 2px rgba(0,0,0,0.1);box-shadow:inset 0 1px 2px rgba(0,0,0,0.1)}.progress-bar{float:left;width:0;height:100%;font-size:12px;color:#fff;text-align:center;background-color:#428bca;-webkit-box-shadow:inset 0 -1px 0 rgba(0,0,0,0.15);box-shadow:inset 0 -1px 0 rgba(0,0,0,0.15);-webkit-transition:width .6s ease;transition:width .6s ease}.progress-striped .progress-bar{background-color:#428bca;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-size:40px 40px}.progress.active .progress-bar{-webkit-animation:progress-bar-stripes 2s linear infinite;-moz-animation:progress-bar-stripes 2s linear infinite;-ms-animation:progress-bar-stripes 2s linear infinite;-o-animation:progress-bar-stripes 2s linear infinite;animation:progress-bar-stripes 2s linear infinite}.progress-bar-danger{background-color:#d9534f}.progress-striped .progress-bar-danger{background-color:#d9534f;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.progress-bar-success{background-color:#5cb85c}.progress-striped .progress-bar-success{background-color:#5cb85c;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.progress-bar-warning{background-color:#f0ad4e}.progress-striped .progress-bar-warning{background-color:#f0ad4e;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.progress-bar-info{background-color:#5bc0de}.progress-striped .progress-bar-info{background-color:#5bc0de;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.accordion{margin-bottom:20px}.accordion-group{margin-bottom:2px;border:1px solid #e5e5e5;border-radius:4px}.accordion-heading{border-bottom:0}.accordion-heading .accordion-toggle{display:block;padding:8px 15px;cursor:pointer}.accordion-inner{padding:9px 15px;border-top:1px solid #e5e5e5}.carousel{position:relative}.carousel-inner{position:relative;width:100%;overflow:hidden}.carousel-inner>.item{position:relative;display:none;-webkit-transition:.6s ease-in-out left;transition:.6s ease-in-out left}.carousel-inner>.item>img,.carousel-inner>.item>a>img{display:inline-block;height:auto;max-width:100%;line-height:1}.carousel-inner>.active,.carousel-inner>.next,.carousel-inner>.prev{display:block}.carousel-inner>.active{left:0}.carousel-inner>.next,.carousel-inner>.prev{position:absolute;top:0;width:100%}.carousel-inner>.next{left:100%}.carousel-inner>.prev{left:-100%}.carousel-inner>.next.left,.carousel-inner>.prev.right{left:0}.carousel-inner>.active.left{left:-100%}.carousel-inner>.active.right{left:100%}.carousel-control{position:absolute;top:0;bottom:0;left:0;width:15%;font-size:20px;color:#fff;text-align:center;text-shadow:0 1px 2px rgba(0,0,0,0.6);opacity:.5;filter:alpha(opacity=50)}.carousel-control.left{background-color:rgba(0,0,0,0.0001);background-color:transparent;background-image:-webkit-gradient(linear,0 top,100% top,from(rgba(0,0,0,0.5)),to(rgba(0,0,0,0.0001)));background-image:-webkit-linear-gradient(left,color-stop(rgba(0,0,0,0.5) 0),color-stop(rgba(0,0,0,0.0001) 100%));background-image:-moz-linear-gradient(left,rgba(0,0,0,0.5) 0,rgba(0,0,0,0.0001) 100%);background-image:linear-gradient(to right,rgba(0,0,0,0.5) 0,rgba(0,0,0,0.0001) 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#80000000',endColorstr='#00000000',GradientType=1)}.carousel-control.right{right:0;left:auto;background-color:rgba(0,0,0,0.5);background-color:transparent;background-image:-webkit-gradient(linear,0 top,100% top,from(rgba(0,0,0,0.0001)),to(rgba(0,0,0,0.5)));background-image:-webkit-linear-gradient(left,color-stop(rgba(0,0,0,0.0001) 0),color-stop(rgba(0,0,0,0.5) 100%));background-image:-moz-linear-gradient(left,rgba(0,0,0,0.0001) 0,rgba(0,0,0,0.5) 100%);background-image:linear-gradient(to right,rgba(0,0,0,0.0001) 0,rgba(0,0,0,0.5) 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#00000000',endColorstr='#80000000',GradientType=1)}.carousel-control:hover,.carousel-control:focus{color:#fff;text-decoration:none;opacity:.9;filter:alpha(opacity=90)}.carousel-control .glyphicon,.carousel-control .icon-prev,.carousel-control .icon-next{position:absolute;top:50%;left:50%;z-index:5;display:inline-block;width:20px;height:20px;margin-top:-10px;margin-left:-10px;font-family:serif}.carousel-control .icon-prev:before{content:'\2039'}.carousel-control .icon-next:before{content:'\203a'}.carousel-indicators{position:absolute;bottom:10px;left:50%;z-index:15;width:120px;padding-left:0;margin-left:-60px;text-align:center;list-style:none}.carousel-indicators li{display:inline-block;width:10px;height:10px;margin:1px;text-indent:-999px;cursor:pointer;border:1px solid #fff;border-radius:10px}.carousel-indicators .active{width:12px;height:12px;margin:0;background-color:#fff}.carousel-caption{position:absolute;right:15%;bottom:20px;left:15%;z-index:10;padding-top:20px;padding-bottom:20px;color:#fff;text-align:center;text-shadow:0 1px 2px rgba(0,0,0,0.6)}.carousel-caption .btn{text-shadow:none}@media screen and (min-width:768px){.carousel-control .glyphicon,.carousel-control .icon-prev,.carousel-control .icon-next{width:30px;height:30px;margin-top:-15px;margin-left:-15px;font-size:30px}.carousel-caption{right:20%;left:20%;padding-bottom:30px}.carousel-indicators{bottom:20px}}.jumbotron{padding:30px;margin-bottom:30px;font-size:21px;font-weight:200;line-height:2.1428571435;color:inherit;background-color:#eee}.jumbotron h1{line-height:1;color:inherit}.jumbotron p{line-height:1.4}@media screen and (min-width:768px){.jumbotron{padding:50px 60px;border-radius:6px}.jumbotron h1{font-size:63px}}.clearfix:before,.clearfix:after{display:table;content:" "}.clearfix:after{clear:both}.pull-right{float:right}.pull-left{float:left}.hide{display:none!important}.show{display:block!important}.invisible{visibility:hidden}.text-hide{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0}.affix{position:fixed}@-ms-viewport{width:device-width}@media screen and (max-width:400px){@-ms-viewport{width:320px}}.hidden{display:none!important;visibility:hidden!important}.visible-sm{display:block!important}tr.visible-sm{display:table-row!important}th.visible-sm,td.visible-sm{display:table-cell!important}.visible-md{display:none!important}tr.visible-md{display:none!important}th.visible-md,td.visible-md{display:none!important}.visible-lg{display:none!important}tr.visible-lg{display:none!important}th.visible-lg,td.visible-lg{display:none!important}.hidden-sm{display:none!important}tr.hidden-sm{display:none!important}th.hidden-sm,td.hidden-sm{display:none!important}.hidden-md{display:block!important}tr.hidden-md{display:table-row!important}th.hidden-md,td.hidden-md{display:table-cell!important}.hidden-lg{display:block!important}tr.hidden-lg{display:table-row!important}th.hidden-lg,td.hidden-lg{display:table-cell!important}@media(min-width:768px) and (max-width:991px){.visible-sm{display:none!important}tr.visible-sm{display:none!important}th.visible-sm,td.visible-sm{display:none!important}.visible-md{display:block!important}tr.visible-md{display:table-row!important}th.visible-md,td.visible-md{display:table-cell!important}.visible-lg{display:none!important}tr.visible-lg{display:none!important}th.visible-lg,td.visible-lg{display:none!important}.hidden-sm{display:block!important}tr.hidden-sm{display:table-row!important}th.hidden-sm,td.hidden-sm{display:table-cell!important}.hidden-md{display:none!important}tr.hidden-md{display:none!important}th.hidden-md,td.hidden-md{display:none!important}.hidden-lg{display:block!important}tr.hidden-lg{display:table-row!important}th.hidden-lg,td.hidden-lg{display:table-cell!important}}@media(min-width:992px){.visible-sm{display:none!important}tr.visible-sm{display:none!important}th.visible-sm,td.visible-sm{display:none!important}.visible-md{display:none!important}tr.visible-md{display:none!important}th.visible-md,td.visible-md{display:none!important}.visible-lg{display:block!important}tr.visible-lg{display:table-row!important}th.visible-lg,td.visible-lg{display:table-cell!important}.hidden-sm{display:block!important}tr.hidden-sm{display:table-row!important}th.hidden-sm,td.hidden-sm{display:table-cell!important}.hidden-md{display:block!important}tr.hidden-md{display:table-row!important}th.hidden-md,td.hidden-md{display:table-cell!important}.hidden-lg{display:none!important}tr.hidden-lg{display:none!important}th.hidden-lg,td.hidden-lg{display:none!important}}.visible-print{display:none!important}tr.visible-print{display:none!important}th.visible-print,td.visible-print{display:none!important}@media print{.visible-print{display:block!important}tr.visible-print{display:table-row!important}th.visible-print,td.visible-print{display:table-cell!important}.hidden-print{display:none!important}tr.hidden-print{display:none!important}th.hidden-print,td.hidden-print{display:none!important}} </style> <!-- zepto --> <script type="text/javascript"> /* Zepto v1.1.2 - zepto event ajax form ie - zeptojs.com/license */ var Zepto=function(){function G(a){return a==null?String(a):z[A.call(a)]||"object"}function H(a){return G(a)=="function"}function I(a){return a!=null&&a==a.window}function J(a){return a!=null&&a.nodeType==a.DOCUMENT_NODE}function K(a){return G(a)=="object"}function L(a){return K(a)&&!I(a)&&Object.getPrototypeOf(a)==Object.prototype}function M(a){return a instanceof Array}function N(a){return typeof a.length=="number"}function O(a){return g.call(a,function(a){return a!=null})}function P(a){return a.length>0?c.fn.concat.apply([],a):a}function Q(a){return a.replace(/::/g,"/").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/_/g,"-").toLowerCase()}function R(a){return a in j?j[a]:j[a]=new RegExp("(^|\\s)"+a+"(\\s|$)")}function S(a,b){return typeof b=="number"&&!k[Q(a)]?b+"px":b}function T(a){var b,c;return i[a]||(b=h.createElement(a),h.body.appendChild(b),c=getComputedStyle(b,"").getPropertyValue("display"),b.parentNode.removeChild(b),c=="none"&&(c="block"),i[a]=c),i[a]}function U(a){return"children"in a?f.call(a.children):c.map(a.childNodes,function(a){if(a.nodeType==1)return a})}function V(c,d,e){for(b in d)e&&(L(d[b])||M(d[b]))?(L(d[b])&&!L(c[b])&&(c[b]={}),M(d[b])&&!M(c[b])&&(c[b]=[]),V(c[b],d[b],e)):d[b]!==a&&(c[b]=d[b])}function W(a,b){return b==null?c(a):c(a).filter(b)}function X(a,b,c,d){return H(b)?b.call(a,c,d):b}function Y(a,b,c){c==null?a.removeAttribute(b):a.setAttribute(b,c)}function Z(b,c){var d=b.className,e=d&&d.baseVal!==a;if(c===a)return e?d.baseVal:d;e?d.baseVal=c:b.className=c}function $(a){var b;try{return a?a=="true"||(a=="false"?!1:a=="null"?null:!/^0/.test(a)&&!isNaN(b=Number(a))?b:/^[\[\{]/.test(a)?c.parseJSON(a):a):a}catch(d){return a}}function _(a,b){b(a);for(var c in a.childNodes)_(a.childNodes[c],b)}var a,b,c,d,e=[],f=e.slice,g=e.filter,h=window.document,i={},j={},k={"column-count":1,columns:1,"font-weight":1,"line-height":1,opacity:1,"z-index":1,zoom:1},l=/^\s*<(\w+|!)[^>]*>/,m=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,n=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,o=/^(?:body|html)$/i,p=/([A-Z])/g,q=["val","css","html","text","data","width","height","offset"],r=["after","prepend","before","append"],s=h.createElement("table"),t=h.createElement("tr"),u={tr:h.createElement("tbody"),tbody:s,thead:s,tfoot:s,td:t,th:t,"*":h.createElement("div")},v=/complete|loaded|interactive/,w=/^\.([\w-]+)$/,x=/^#([\w-]*)$/,y=/^[\w-]*$/,z={},A=z.toString,B={},C,D,E=h.createElement("div"),F={tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"};return B.matches=function(a,b){if(!b||!a||a.nodeType!==1)return!1;var c=a.webkitMatchesSelector||a.mozMatchesSelector||a.oMatchesSelector||a.matchesSelector;if(c)return c.call(a,b);var d,e=a.parentNode,f=!e;return f&&(e=E).appendChild(a),d=~B.qsa(e,b).indexOf(a),f&&E.removeChild(a),d},C=function(a){return a.replace(/-+(.)?/g,function(a,b){return b?b.toUpperCase():""})},D=function(a){return g.call(a,function(b,c){return a.indexOf(b)==c})},B.fragment=function(b,d,e){var g,i,j;return m.test(b)&&(g=c(h.createElement(RegExp.$1))),g||(b.replace&&(b=b.replace(n,"<$1></$2>")),d===a&&(d=l.test(b)&&RegExp.$1),d in u||(d="*"),j=u[d],j.innerHTML=""+b,g=c.each(f.call(j.childNodes),function(){j.removeChild(this)})),L(e)&&(i=c(g),c.each(e,function(a,b){q.indexOf(a)>-1?i[a](b):i.attr(a,b)})),g},B.Z=function(a,b){return a=a||[],a.__proto__=c.fn,a.selector=b||"",a},B.isZ=function(a){return a instanceof B.Z},B.init=function(b,d){var e;if(!b)return B.Z();if(typeof b=="string"){b=b.trim();if(b[0]=="<"&&l.test(b))e=B.fragment(b,RegExp.$1,d),b=null;else{if(d!==a)return c(d).find(b);e=B.qsa(h,b)}}else{if(H(b))return c(h).ready(b);if(B.isZ(b))return b;if(M(b))e=O(b);else if(K(b))e=[b],b=null;else if(l.test(b))e=B.fragment(b.trim(),RegExp.$1,d),b=null;else{if(d!==a)return c(d).find(b);e=B.qsa(h,b)}}return B.Z(e,b)},c=function(a,b){return B.init(a,b)},c.extend=function(a){var b,c=f.call(arguments,1);return typeof a=="boolean"&&(b=a,a=c.shift()),c.forEach(function(c){V(a,c,b)}),a},B.qsa=function(a,b){var c,d=b[0]=="#",e=!d&&b[0]==".",g=d||e?b.slice(1):b,h=y.test(g);return J(a)&&h&&d?(c=a.getElementById(g))?[c]:[]:a.nodeType!==1&&a.nodeType!==9?[]:f.call(h&&!d?e?a.getElementsByClassName(g):a.getElementsByTagName(b):a.querySelectorAll(b))},c.contains=function(a,b){return a!==b&&a.contains(b)},c.type=G,c.isFunction=H,c.isWindow=I,c.isArray=M,c.isPlainObject=L,c.isEmptyObject=function(a){var b;for(b in a)return!1;return!0},c.inArray=function(a,b,c){return e.indexOf.call(b,a,c)},c.camelCase=C,c.trim=function(a){return a==null?"":String.prototype.trim.call(a)},c.uuid=0,c.support={},c.expr={},c.map=function(a,b){var c,d=[],e,f;if(N(a))for(e=0;e<a.length;e++)c=b(a[e],e),c!=null&&d.push(c);else for(f in a)c=b(a[f],f),c!=null&&d.push(c);return P(d)},c.each=function(a,b){var c,d;if(N(a)){for(c=0;c<a.length;c++)if(b.call(a[c],c,a[c])===!1)return a}else for(d in a)if(b.call(a[d],d,a[d])===!1)return a;return a},c.grep=function(a,b){return g.call(a,b)},window.JSON&&(c.parseJSON=JSON.parse),c.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){z["[object "+b+"]"]=b.toLowerCase()}),c.fn={forEach:e.forEach,reduce:e.reduce,push:e.push,sort:e.sort,indexOf:e.indexOf,concat:e.concat,map:function(a){return c(c.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return c(f.apply(this,arguments))},ready:function(a){return v.test(h.readyState)&&h.body?a(c):h.addEventListener("DOMContentLoaded",function(){a(c)},!1),this},get:function(b){return b===a?f.call(this):this[b>=0?b:b+this.length]},toArray:function(){return this.get()},size:function(){return this.length},remove:function(){return this.each(function(){this.parentNode!=null&&this.parentNode.removeChild(this)})},each:function(a){return e.every.call(this,function(b,c){return a.call(b,c,b)!==!1}),this},filter:function(a){return H(a)?this.not(this.not(a)):c(g.call(this,function(b){return B.matches(b,a)}))},add:function(a,b){return c(D(this.concat(c(a,b))))},is:function(a){return this.length>0&&B.matches(this[0],a)},not:function(b){var d=[];if(H(b)&&b.call!==a)this.each(function(a){b.call(this,a)||d.push(this)});else{var e=typeof b=="string"?this.filter(b):N(b)&&H(b.item)?f.call(b):c(b);this.forEach(function(a){e.indexOf(a)<0&&d.push(a)})}return c(d)},has:function(a){return this.filter(function(){return K(a)?c.contains(this,a):c(this).find(a).size()})},eq:function(a){return a===-1?this.slice(a):this.slice(a,+a+1)},first:function(){var a=this[0];return a&&!K(a)?a:c(a)},last:function(){var a=this[this.length-1];return a&&!K(a)?a:c(a)},find:function(a){var b,d=this;return typeof a=="object"?b=c(a).filter(function(){var a=this;return e.some.call(d,function(b){return c.contains(b,a)})}):this.length==1?b=c(B.qsa(this[0],a)):b=this.map(function(){return B.qsa(this,a)}),b},closest:function(a,b){var d=this[0],e=!1;typeof a=="object"&&(e=c(a));while(d&&!(e?e.indexOf(d)>=0:B.matches(d,a)))d=d!==b&&!J(d)&&d.parentNode;return c(d)},parents:function(a){var b=[],d=this;while(d.length>0)d=c.map(d,function(a){if((a=a.parentNode)&&!J(a)&&b.indexOf(a)<0)return b.push(a),a});return W(b,a)},parent:function(a){return W(D(this.pluck("parentNode")),a)},children:function(a){return W(this.map(function(){return U(this)}),a)},contents:function(){return this.map(function(){return f.call(this.childNodes)})},siblings:function(a){return W(this.map(function(a,b){return g.call(U(b.parentNode),function(a){return a!==b})}),a)},empty:function(){return this.each(function(){this.innerHTML=""})},pluck:function(a){return c.map(this,function(b){return b[a]})},show:function(){return this.each(function(){this.style.display=="none"&&(this.style.display=""),getComputedStyle(this,"").getPropertyValue("display")=="none"&&(this.style.display=T(this.nodeName))})},replaceWith:function(a){return this.before(a).remove()},wrap:function(a){var b=H(a);if(this[0]&&!b)var d=c(a).get(0),e=d.parentNode||this.length>1;return this.each(function(f){c(this).wrapAll(b?a.call(this,f):e?d.cloneNode(!0):d)})},wrapAll:function(a){if(this[0]){c(this[0]).before(a=c(a));var b;while((b=a.children()).length)a=b.first();c(a).append(this)}return this},wrapInner:function(a){var b=H(a);return this.each(function(d){var e=c(this),f=e.contents(),g=b?a.call(this,d):a;f.length?f.wrapAll(g):e.append(g)})},unwrap:function(){return this.parent().each(function(){c(this).replaceWith(c(this).children())}),this},clone:function(){return this.map(function(){return this.cloneNode(!0)})},hide:function(){return this.css("display","none")},toggle:function(b){return this.each(function(){var d=c(this);(b===a?d.css("display")=="none":b)?d.show():d.hide()})},prev:function(a){return c(this.pluck("previousElementSibling")).filter(a||"*")},next:function(a){return c(this.pluck("nextElementSibling")).filter(a||"*")},html:function(a){return arguments.length===0?this.length>0?this[0].innerHTML:null:this.each(function(b){var d=this.innerHTML;c(this).empty().append(X(this,a,b,d))})},text:function(b){return arguments.length===0?this.length>0?this[0].textContent:null:this.each(function(){this.textContent=b===a?"":""+b})},attr:function(c,d){var e;return typeof c=="string"&&d===a?this.length==0||this[0].nodeType!==1?a:c=="value"&&this[0].nodeName=="INPUT"?this.val():!(e=this[0].getAttribute(c))&&c in this[0]?this[0][c]:e:this.each(function(a){if(this.nodeType!==1)return;if(K(c))for(b in c)Y(this,b,c[b]);else Y(this,c,X(this,d,a,this.getAttribute(c)))})},removeAttr:function(a){return this.each(function(){this.nodeType===1&&Y(this,a)})},prop:function(b,c){return b=F[b]||b,c===a?this[0]&&this[0][b]:this.each(function(a){this[b]=X(this,c,a,this[b])})},data:function(b,c){var d=this.attr("data-"+b.replace(p,"-$1").toLowerCase(),c);return d!==null?$(d):a},val:function(a){return arguments.length===0?this[0]&&(this[0].multiple?c(this[0]).find("option").filter(function(){return this.selected}).pluck("value"):this[0].value):this.each(function(b){this.value=X(this,a,b,this.value)})},offset:function(a){if(a)return this.each(function(b){var d=c(this),e=X(this,a,b,d.offset()),f=d.offsetParent().offset(),g={top:e.top-f.top,left:e.left-f.left};d.css("position")=="static"&&(g.position="relative"),d.css(g)});if(this.length==0)return null;var b=this[0].getBoundingClientRect();return{left:b.left+window.pageXOffset,top:b.top+window.pageYOffset,width:Math.round(b.width),height:Math.round(b.height)}},css:function(a,d){if(arguments.length<2){var e=this[0],f=getComputedStyle(e,"");if(!e)return;if(typeof a=="string")return e.style[C(a)]||f.getPropertyValue(a);if(M(a)){var g={};return c.each(M(a)?a:[a],function(a,b){g[b]=e.style[C(b)]||f.getPropertyValue(b)}),g}}var h="";if(G(a)=="string")!d&&d!==0?this.each(function(){this.style.removeProperty(Q(a))}):h=Q(a)+":"+S(a,d);else for(b in a)!a[b]&&a[b]!==0?this.each(function(){this.style.removeProperty(Q(b))}):h+=Q(b)+":"+S(b,a[b])+";";return this.each(function(){this.style.cssText+=";"+h})},index:function(a){return a?this.indexOf(c(a)[0]):this.parent().children().indexOf(this[0])},hasClass:function(a){return a?e.some.call(this,function(a){return this.test(Z(a))},R(a)):!1},addClass:function(a){return a?this.each(function(b){d=[];var e=Z(this),f=X(this,a,b,e);f.split(/\s+/g).forEach(function(a){c(this).hasClass(a)||d.push(a)},this),d.length&&Z(this,e+(e?" ":"")+d.join(" "))}):this},removeClass:function(b){return this.each(function(c){if(b===a)return Z(this,"");d=Z(this),X(this,b,c,d).split(/\s+/g).forEach(function(a){d=d.replace(R(a)," ")}),Z(this,d.trim())})},toggleClass:function(b,d){return b?this.each(function(e){var f=c(this),g=X(this,b,e,Z(this));g.split(/\s+/g).forEach(function(b){(d===a?!f.hasClass(b):d)?f.addClass(b):f.removeClass(b)})}):this},scrollTop:function(b){if(!this.length)return;var c="scrollTop"in this[0];return b===a?c?this[0].scrollTop:this[0].pageYOffset:this.each(c?function(){this.scrollTop=b}:function(){this.scrollTo(this.scrollX,b)})},scrollLeft:function(b){if(!this.length)return;var c="scrollLeft"in this[0];return b===a?c?this[0].scrollLeft:this[0].pageXOffset:this.each(c?function(){this.scrollLeft=b}:function(){this.scrollTo(b,this.scrollY)})},position:function(){if(!this.length)return;var a=this[0],b=this.offsetParent(),d=this.offset(),e=o.test(b[0].nodeName)?{top:0,left:0}:b.offset();return d.top-=parseFloat(c(a).css("margin-top"))||0,d.left-=parseFloat(c(a).css("margin-left"))||0,e.top+=parseFloat(c(b[0]).css("border-top-width"))||0,e.left+=parseFloat(c(b[0]).css("border-left-width"))||0,{top:d.top-e.top,left:d.left-e.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||h.body;while(a&&!o.test(a.nodeName)&&c(a).css("position")=="static")a=a.offsetParent;return a})}},c.fn.detach=c.fn.remove,["width","height"].forEach(function(b){var d=b.replace(/./,function(a){return a[0].toUpperCase()});c.fn[b]=function(e){var f,g=this[0];return e===a?I(g)?g["inner"+d]:J(g)?g.documentElement["scroll"+d]:(f=this.offset())&&f[b]:this.each(function(a){g=c(this),g.css(b,X(this,e,a,g[b]()))})}}),r.forEach(function(a,b){var d=b%2;c.fn[a]=function(){var a,e=c.map(arguments,function(b){return a=G(b),a=="object"||a=="array"||b==null?b:B.fragment(b)}),f,g=this.length>1;return e.length<1?this:this.each(function(a,h){f=d?h:h.parentNode,h=b==0?h.nextSibling:b==1?h.firstChild:b==2?h:null,e.forEach(function(a){if(g)a=a.cloneNode(!0);else if(!f)return c(a).remove();_(f.insertBefore(a,h),function(a){a.nodeName!=null&&a.nodeName.toUpperCase()==="SCRIPT"&&(!a.type||a.type==="text/javascript")&&!a.src&&window.eval.call(window,a.innerHTML)})})})},c.fn[d?a+"To":"insert"+(b?"Before":"After")]=function(b){return c(b)[a](this),this}}),B.Z.prototype=c.fn,B.uniq=D,B.deserializeValue=$,c.zepto=B,c}();window.Zepto=Zepto,window.$===undefined&&(window.$=Zepto),function(a){function m(a){return a._zid||(a._zid=c++)}function n(a,b,c,d){b=o(b);if(b.ns)var e=p(b.ns);return(h[m(a)]||[]).filter(function(a){return a&&(!b.e||a.e==b.e)&&(!b.ns||e.test(a.ns))&&(!c||m(a.fn)===m(c))&&(!d||a.sel==d)})}function o(a){var b=(""+a).split(".");return{e:b[0],ns:b.slice(1).sort().join(" ")}}function p(a){return new RegExp("(?:^| )"+a.replace(" "," .* ?")+"(?: |$)")}function q(a,b){return a.del&&!j&&a.e in k||!!b}function r(a){return l[a]||j&&k[a]||a}function s(b,c,e,f,g,i,j){var k=m(b),n=h[k]||(h[k]=[]);c.split(/\s/).forEach(function(c){if(c=="ready")return a(document).ready(e);var h=o(c);h.fn=e,h.sel=g,h.e in l&&(e=function(b){var c=b.relatedTarget;if(!c||c!==this&&!a.contains(this,c))return h.fn.apply(this,arguments)}),h.del=i;var k=i||e;h.proxy=function(a){a=y(a);if(a.isImmediatePropagationStopped())return;a.data=f;var c=k.apply(b,a._args==d?[a]:[a].concat(a._args));return c===!1&&(a.preventDefault(),a.stopPropagation()),c},h.i=n.length,n.push(h),"addEventListener"in b&&b.addEventListener(r(h.e),h.proxy,q(h,j))})}function t(a,b,c,d,e){var f=m(a);(b||"").split(/\s/).forEach(function(b){n(a,b,c,d).forEach(function(b){delete h[f][b.i],"removeEventListener"in a&&a.removeEventListener(r(b.e),b.proxy,q(b,e))})})}function y(b,c){if(c||!b.isDefaultPrevented){c||(c=b),a.each(x,function(a,d){var e=c[a];b[a]=function(){return this[d]=u,e&&e.apply(c,arguments)},b[d]=v});if(c.defaultPrevented!==d?c.defaultPrevented:"returnValue"in c?c.returnValue===!1:c.getPreventDefault&&c.getPreventDefault())b.isDefaultPrevented=u}return b}function z(a){var b,c={originalEvent:a};for(b in a)!w.test(b)&&a[b]!==d&&(c[b]=a[b]);return y(c,a)}var b=a.zepto.qsa,c=1,d,e=Array.prototype.slice,f=a.isFunction,g=function(a){return typeof a=="string"},h={},i={},j="onfocusin"in window,k={focus:"focusin",blur:"focusout"},l={mouseenter:"mouseover",mouseleave:"mouseout"};i.click=i.mousedown=i.mouseup=i.mousemove="MouseEvents",a.event={add:s,remove:t},a.proxy=function(b,c){if(f(b)){var d=function(){return b.apply(c,arguments)};return d._zid=m(b),d}if(g(c))return a.proxy(b[c],b);throw new TypeError("expected function")},a.fn.bind=function(a,b,c){return this.on(a,b,c)},a.fn.unbind=function(a,b){return this.off(a,b)},a.fn.one=function(a,b,c,d){return this.on(a,b,c,d,1)};var u=function(){return!0},v=function(){return!1},w=/^([A-Z]|returnValue$|layer[XY]$)/,x={preventDefault:"isDefaultPrevented",stopImmediatePropagation:"isImmediatePropagationStopped",stopPropagation:"isPropagationStopped"};a.fn.delegate=function(a,b,c){return this.on(b,a,c)},a.fn.undelegate=function(a,b,c){return this.off(b,a,c)},a.fn.live=function(b,c){return a(document.body).delegate(this.selector,b,c),this},a.fn.die=function(b,c){return a(document.body).undelegate(this.selector,b,c),this},a.fn.on=function(b,c,h,i,j){var k,l,m=this;if(b&&!g(b))return a.each(b,function(a,b){m.on(a,c,h,b,j)}),m;!g(c)&&!f(i)&&i!==!1&&(i=h,h=c,c=d);if(f(h)||h===!1)i=h,h=d;return i===!1&&(i=v),m.each(function(d,f){j&&(k=function(a){return t(f,a.type,i),i.apply(this,arguments)}),c&&(l=function(b){var d,g=a(b.target).closest(c,f).get(0);if(g&&g!==f)return d=a.extend(z(b),{currentTarget:g,liveFired:f}),(k||i).apply(g,[d].concat(e.call(arguments,1)))}),s(f,b,i,h,c,l||k)})},a.fn.off=function(b,c,e){var h=this;return b&&!g(b)?(a.each(b,function(a,b){h.off(a,c,b)}),h):(!g(c)&&!f(e)&&e!==!1&&(e=c,c=d),e===!1&&(e=v),h.each(function(){t(this,b,e,c)}))},a.fn.trigger=function(b,c){return b=g(b)||a.isPlainObject(b)?a.Event(b):y(b),b._args=c,this.each(function(){"dispatchEvent"in this?this.dispatchEvent(b):a(this).triggerHandler(b,c)})},a.fn.triggerHandler=function(b,c){var d,e;return this.each(function(f,h){d=z(g(b)?a.Event(b):b),d._args=c,d.target=h,a.each(n(h,b.type||b),function(a,b){e=b.proxy(d);if(d.isImmediatePropagationStopped())return!1})}),e},"focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select keydown keypress keyup error".split(" ").forEach(function(b){a.fn[b]=function(a){return a?this.bind(b,a):this.trigger(b)}}),["focus","blur"].forEach(function(b){a.fn[b]=function(a){return a?this.bind(b,a):this.each(function(){try{this[b]()}catch(a){}}),this}}),a.Event=function(a,b){g(a)||(b=a,a=b.type);var c=document.createEvent(i[a]||"Events"),d=!0;if(b)for(var e in b)e=="bubbles"?d=!!b[e]:c[e]=b[e];return c.initEvent(a,d,!0),y(c)}}(Zepto),function($){function triggerAndReturn(a,b,c){var d=$.Event(b);return $(a).trigger(d,c),!d.isDefaultPrevented()}function triggerGlobal(a,b,c,d){if(a.global)return triggerAndReturn(b||document,c,d)}function ajaxStart(a){a.global&&$.active++===0&&triggerGlobal(a,null,"ajaxStart")}function ajaxStop(a){a.global&&!--$.active&&triggerGlobal(a,null,"ajaxStop")}function ajaxBeforeSend(a,b){var c=b.context;if(b.beforeSend.call(c,a,b)===!1||triggerGlobal(b,c,"ajaxBeforeSend",[a,b])===!1)return!1;triggerGlobal(b,c,"ajaxSend",[a,b])}function ajaxSuccess(a,b,c,d){var e=c.context,f="success";c.success.call(e,a,f,b),d&&d.resolveWith(e,[a,f,b]),triggerGlobal(c,e,"ajaxSuccess",[b,c,a]),ajaxComplete(f,b,c)}function ajaxError(a,b,c,d,e){var f=d.context;d.error.call(f,c,b,a),e&&e.rejectWith(f,[c,b,a]),triggerGlobal(d,f,"ajaxError",[c,d,a||b]),ajaxComplete(b,c,d)}function ajaxComplete(a,b,c){var d=c.context;c.complete.call(d,b,a),triggerGlobal(c,d,"ajaxComplete",[b,c]),ajaxStop(c)}function empty(){}function mimeToDataType(a){return a&&(a=a.split(";",2)[0]),a&&(a==htmlType?"html":a==jsonType?"json":scriptTypeRE.test(a)?"script":xmlTypeRE.test(a)&&"xml")||"text"}function appendQuery(a,b){return b==""?a:(a+"&"+b).replace(/[&?]{1,2}/,"?")}function serializeData(a){a.processData&&a.data&&$.type(a.data)!="string"&&(a.data=$.param(a.data,a.traditional)),a.data&&(!a.type||a.type.toUpperCase()=="GET")&&(a.url=appendQuery(a.url,a.data),a.data=undefined)}function parseArguments(a,b,c,d){var e=!$.isFunction(b);return{url:a,data:e?b:undefined,success:e?$.isFunction(c)?c:undefined:b,dataType:e?d||c:c}}function serialize(a,b,c,d){var e,f=$.isArray(b),g=$.isPlainObject(b);$.each(b,function(b,h){e=$.type(h),d&&(b=c?d:d+"["+(g||e=="object"||e=="array"?b:"")+"]"),!d&&f?a.add(h.name,h.value):e=="array"||!c&&e=="object"?serialize(a,h,c,b):a.add(b,h)})}var jsonpID=0,document=window.document,key,name,rscript=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,scriptTypeRE=/^(?:text|application)\/javascript/i,xmlTypeRE=/^(?:text|application)\/xml/i,jsonType="application/json",htmlType="text/html",blankRE=/^\s*$/;$.active=0,$.ajaxJSONP=function(a,b){if("type"in a){var c=a.jsonpCallback,d=($.isFunction(c)?c():c)||"jsonp"+ ++jsonpID,e=document.createElement("script"),f=window[d],g,h=function(a){$(e).triggerHandler("error",a||"abort")},i={abort:h},j;return b&&b.promise(i),$(e).on("load error",function(c,h){clearTimeout(j),$(e).off().remove(),c.type=="error"||!g?ajaxError(null,h||"error",i,a,b):ajaxSuccess(g[0],i,a,b),window[d]=f,g&&$.isFunction(f)&&f(g[0]),f=g=undefined}),ajaxBeforeSend(i,a)===!1?(h("abort"),i):(window[d]=function(){g=arguments},e.src=a.url.replace(/=\?/,"="+d),document.head.appendChild(e),a.timeout>0&&(j=setTimeout(function(){h("timeout")},a.timeout)),i)}return $.ajax(a)},$.ajaxSettings={type:"GET",beforeSend:empty,success:empty,error:empty,complete:empty,context:null,global:!0,xhr:function(){return new window.XMLHttpRequest},accepts:{script:"text/javascript, application/javascript, application/x-javascript",json:jsonType,xml:"application/xml, text/xml",html:htmlType,text:"text/plain"},crossDomain:!1,timeout:0,processData:!0,cache:!0},$.ajax=function(options){var settings=$.extend({},options||{}),deferred=$.Deferred&&$.Deferred();for(key in $.ajaxSettings)settings[key]===undefined&&(settings[key]=$.ajaxSettings[key]);ajaxStart(settings),settings.crossDomain||(settings.crossDomain=/^([\w-]+:)?\/\/([^\/]+)/.test(settings.url)&&RegExp.$2!=window.location.host),settings.url||(settings.url=window.location.toString()),serializeData(settings),settings.cache===!1&&(settings.url=appendQuery(settings.url,"_="+Date.now()));var dataType=settings.dataType,hasPlaceholder=/=\?/.test(settings.url);if(dataType=="jsonp"||hasPlaceholder)return hasPlaceholder||(settings.url=appendQuery(settings.url,settings.jsonp?settings.jsonp+"=?":settings.jsonp===!1?"":"callback=?")),$.ajaxJSONP(settings,deferred);var mime=settings.accepts[dataType],headers={},setHeader=function(a,b){headers[a.toLowerCase()]=[a,b]},protocol=/^([\w-]+:)\/\//.test(settings.url)?RegExp.$1:window.location.protocol,xhr=settings.xhr(),nativeSetHeader=xhr.setRequestHeader,abortTimeout;deferred&&deferred.promise(xhr),settings.crossDomain||setHeader("X-Requested-With","XMLHttpRequest"),setHeader("Accept",mime||"*/*");if(mime=settings.mimeType||mime)mime.indexOf(",")>-1&&(mime=mime.split(",",2)[0]),xhr.overrideMimeType&&xhr.overrideMimeType(mime);(settings.contentType||settings.contentType!==!1&&settings.data&&settings.type.toUpperCase()!="GET")&&setHeader("Content-Type",settings.contentType||"application/x-www-form-urlencoded");if(settings.headers)for(name in settings.headers)setHeader(name,settings.headers[name]);xhr.setRequestHeader=setHeader,xhr.onreadystatechange=function(){if(xhr.readyState==4){xhr.onreadystatechange=empty,clearTimeout(abortTimeout);var result,error=!1;if(xhr.status>=200&&xhr.status<300||xhr.status==304||xhr.status==0&&protocol=="file:"){dataType=dataType||mimeToDataType(settings.mimeType||xhr.getResponseHeader("content-type")),result=xhr.responseText;try{dataType=="script"?(1,eval)(result):dataType=="xml"?result=xhr.responseXML:dataType=="json"&&(result=blankRE.test(result)?null:$.parseJSON(result))}catch(e){error=e}error?ajaxError(error,"parsererror",xhr,settings,deferred):ajaxSuccess(result,xhr,settings,deferred)}else ajaxError(xhr.statusText||null,xhr.status?"error":"abort",xhr,settings,deferred)}};if(ajaxBeforeSend(xhr,settings)===!1)return xhr.abort(),ajaxError(null,"abort",xhr,settings,deferred),xhr;if(settings.xhrFields)for(name in settings.xhrFields)xhr[name]=settings.xhrFields[name];var async="async"in settings?settings.async:!0;xhr.open(settings.type,settings.url,async,settings.username,settings.password);for(name in headers)nativeSetHeader.apply(xhr,headers[name]);return settings.timeout>0&&(abortTimeout=setTimeout(function(){xhr.onreadystatechange=empty,xhr.abort(),ajaxError(null,"timeout",xhr,settings,deferred)},settings.timeout)),xhr.send(settings.data?settings.data:null),xhr},$.get=function(a,b,c,d){return $.ajax(parseArguments.apply(null,arguments))},$.post=function(a,b,c,d){var e=parseArguments.apply(null,arguments);return e.type="POST",$.ajax(e)},$.getJSON=function(a,b,c){var d=parseArguments.apply(null,arguments);return d.dataType="json",$.ajax(d)},$.fn.load=function(a,b,c){if(!this.length)return this;var d=this,e=a.split(/\s/),f,g=parseArguments(a,b,c),h=g.success;return e.length>1&&(g.url=e[0],f=e[1]),g.success=function(a){d.html(f?$("<div>").html(a.replace(rscript,"")).find(f):a),h&&h.apply(d,arguments)},$.ajax(g),this};var escape=encodeURIComponent;$.param=function(a,b){var c=[];return c.add=function(a,b){this.push(escape(a)+"="+escape(b))},serialize(c,a,b),c.join("&").replace(/%20/g,"+")}}(Zepto),function(a){a.fn.serializeArray=function(){var b=[],c;return a([].slice.call(this.get(0).elements)).each(function(){c=a(this);var d=c.attr("type");this.nodeName.toLowerCase()!="fieldset"&&!this.disabled&&d!="submit"&&d!="reset"&&d!="button"&&(d!="radio"&&d!="checkbox"||this.checked)&&b.push({name:c.attr("name"),value:c.val()})}),b},a.fn.serialize=function(){var a=[];return this.serializeArray().forEach(function(b){a.push(encodeURIComponent(b.name)+"="+encodeURIComponent(b.value))}),a.join("&")},a.fn.submit=function(b){if(b)this.bind("submit",b);else if(this.length){var c=a.Event("submit");this.eq(0).trigger(c),c.isDefaultPrevented()||this.get(0).submit()}return this}}(Zepto),function(a){"__proto__"in{}||a.extend(a.zepto,{Z:function(b,c){return b=b||[],a.extend(b,a.fn),b.selector=c||"",b.__Z=!0,b},isZ:function(b){return a.type(b)==="array"&&"__Z"in b}});try{getComputedStyle(undefined)}catch(b){var c=getComputedStyle;window.getComputedStyle=function(a){try{return c(a)}catch(b){return null}}}}(Zepto) </script> <style type="text/css"> body { background: #F9F9F9; font-size: 14px; line-height: 22px; font-family: Helvetica Neue, Helvetica, Arial; } a { color: #000; text-decoration: underline; } li ul, li ol{ margin: 0; } .anchor { cursor: pointer; } .anchor .anchor_char{ visibility: hidden; padding-left: 0.2em; font-size: 0.9em; opacity: 0.5; } .anchor:hover .anchor_char{ visibility: visible; } .sidebar{ background: #FFF; position: fixed; z-index: 10; top: 0; left: 0; bottom: 0; width: 230px; overflow-y: auto; overflow-x: hidden; padding: 15px 0 30px 30px; border-right: 1px solid #bbb; font-family: "Lucida Grande", "Lucida Sans Unicode", Helvetica, Arial, sans-serif !important; } .sidebar ul{ margin: 0; list-style: none; padding: 0; } .sidebar ul a:hover { text-decoration: underline; color: #333; } .sidebar > ul > li { margin-top: 15px; } .sidebar > ul > li > a { font-weight: bold; } .sidebar ul ul { margin-top: 5px; font-size: 11px; line-height: 14px; } .sidebar ul ul li:before { content: "- "; } .sidebar ul ul li { margin-bottom: 3px; } .sidebar ul ul li a { text-decoration: none; } .toggle_sidebar_button{ display: none; position: fixed; z-index: 11; top: 0; width: 44px; height: 44px; background: #000; background: rgba(0,0,0,0.7); margin-left: 230px; } .toggle_sidebar_button:hover { background: rgba(0,0,0,1); cursor: pointer; } .toggle_sidebar_button .line{ height: 2px; width: 21px; margin-left: 11px; margin-top: 5px; background: #FFF; } .toggle_sidebar_button .line:first-child { margin-top: 15px; } .main_container { width: 100%; padding-left: 260px; margin: 30px; margin-left: 0px; padding-right: 30px; } .main_container p, ul{ margin: 25px 0; } .main_container ul { list-style: circle; font-size: 13px; line-height: 18px; padding-left: 15px; } pre { font-size: 12px; border: 4px solid #bbb; border-top: 0; border-bottom: 0; margin: 0px 0 25px; padding-top: 0px; padding-bottom: 0px; font-family: Monaco, Consolas, "Lucida Console", monospace; line-height: 18px; font-style: normal; background: none; border-radius: 0px; overflow-x: scroll; word-wrap: normal; white-space: pre; } .main_container { width: 840px; } .main_container p, ul, pre { width: 100%; } code { padding: 0px 3px; color: #333; background: #fff; border: 1px solid #ddd; zoom: 1; white-space: nowrap; border-radius: 0; font-family: Monaco, Consolas, "Lucida Console", monospace; font-size: 12px; line-height: 18px; font-style: normal; } em { font-size: 12px; line-height: 18px; } @media (max-width: 820px) { .sidebar { display: none; } .main_container { padding: 0px; width: 100%; } .main_container > *{ padding-left: 10px; padding-right: 10px; } .main_container > ul, .main_container > ol { padding-left: 27px; } .force_show_sidebar .main_container { display: none; } .force_show_sidebar .sidebar { width: 100%; } .force_show_sidebar .sidebar a{ font-size: 1.5em; line-height: 1.5em; } .force_show_sidebar .toggle_sidebar_button { right: 0; } .force_show_sidebar .toggle_sidebar_button .line:first-child, .force_show_sidebar .toggle_sidebar_button .line:last-child { visibility: hidden; } .toggle_sidebar_button { margin-left: 0px; display: block; } pre { font-size: 12px; border: 1px solid #bbb; border-left: 0; border-right: 0; padding: 9px; background: #FFF; } code { word-wrap: break-word; white-space: normal; } } .force_show_sidebar .sidebar { display: block; } .force_show_sidebar .main_container { padding-left: 260px; } .force_show_sidebar .toggle_sidebar_button{ margin-left: 230px; } </style> <script type="text/javascript"> $(function(){ $('.toggle_sidebar_button').on('click', function(){ $('body').toggleClass('force_show_sidebar'); }); // hide sidebar on every click in menu (if small screen) $('.sidebar').find('a').on('click', function(){ $('body').removeClass('force_show_sidebar'); }); // add anchors $.each($('.main_container').find('h1,h2,h3,h4,h5,h6'), function(key, item){ if ($(item).attr('id')) { $(item).addClass('anchor'); $(item).append($('<span class="anchor_char">¶</span>')) $(item).on('click', function(){ window.location = '#' + $(item).attr('id'); }) } }); // remove <code> tag inside of <pre> $.each($('pre > code'), function(key, item){ $(item).parent().html($(item).html()) }) }) </script> </head> <body> <a class="toggle_sidebar_button"> <div class="line"></div> <div class="line"></div> <div class="line"></div> </a> <div class="sidebar"> <!-- toc --> </div> <div class="main_container"> <!-- main_content --> </div> </body> </html>''' def force_text(text): if isinstance(text, unicode): return text else: return text.decode('utf-8') class BackDoc(object): def __init__(self, markdown_converter, template_html, stdin, stdout): self.markdown_converter = markdown_converter self.template_html = force_text(template_html) self.stdin = stdin self.stdout = stdout self.parser = self.get_parser() def run(self, argv): kwargs = self.get_kwargs(argv) self.stdout.write(self.get_result_html(**kwargs)) def get_kwargs(self, argv): parsed = dict(self.parser.parse_args(argv)._get_kwargs()) return self.prepare_kwargs_from_parsed_data(parsed) def prepare_kwargs_from_parsed_data(self, parsed): kwargs = {} kwargs['title'] = force_text(parsed.get('title') or 'Documentation') if parsed.get('source'): kwargs['markdown_src'] = open(parsed['source'], 'r').read() else: kwargs['markdown_src'] = self.stdin.read() kwargs['markdown_src'] = force_text(kwargs['markdown_src'] or '') return kwargs def get_result_html(self, title, markdown_src): response = self.get_converted_to_html_response(markdown_src) return ( self.template_html.replace('<!-- title -->', title) .replace('<!-- toc -->', response.toc_html and force_text(response.toc_html) or '') .replace('<!-- main_content -->', force_text(response)) ) def get_converted_to_html_response(self, markdown_src): return self.markdown_converter.convert(markdown_src) def get_parser(self): parser = argparse.ArgumentParser() parser.add_argument( '-t', '--title', help='Documentation title header', required=False, ) parser.add_argument( '-s', '--source', help='Markdown source file path', required=False, ) return parser if __name__ == '__main__': BackDoc( markdown_converter=Markdown(extras=['toc']), template_html=template_html, stdin=sys.stdin, stdout=sys.stdout ).run(argv=sys.argv[1:])
chibisov/drf-extensions
docs/backdoc.py
_dedentlines
python
def _dedentlines(lines, tabsize=8, skip_first_line=False): DEBUG = False if DEBUG: print("dedent: dedent(..., tabsize=%d, skip_first_line=%r)"\ % (tabsize, skip_first_line)) indents = [] margin = None for i, line in enumerate(lines): if i == 0 and skip_first_line: continue indent = 0 for ch in line: if ch == ' ': indent += 1 elif ch == '\t': indent += tabsize - (indent % tabsize) elif ch in '\r\n': continue # skip all-whitespace lines else: break else: continue # skip all-whitespace lines if DEBUG: print("dedent: indent=%d: %r" % (indent, line)) if margin is None: margin = indent else: margin = min(margin, indent) if DEBUG: print("dedent: margin=%r" % margin) if margin is not None and margin > 0: for i, line in enumerate(lines): if i == 0 and skip_first_line: continue removed = 0 for j, ch in enumerate(line): if ch == ' ': removed += 1 elif ch == '\t': removed += tabsize - (removed % tabsize) elif ch in '\r\n': if DEBUG: print("dedent: %r: EOL -> strip up to EOL" % line) lines[i] = lines[i][j:] break else: raise ValueError("unexpected non-whitespace char %r in " "line %r while removing %d-space margin" % (ch, line, margin)) if DEBUG: print("dedent: %r: %r -> removed %d/%d"\ % (line, ch, removed, margin)) if removed == margin: lines[i] = lines[i][j+1:] break elif removed > margin: lines[i] = ' '*(removed-margin) + lines[i][j+1:] break else: if removed: lines[i] = lines[i][removed:] return lines
_dedentlines(lines, tabsize=8, skip_first_line=False) -> dedented lines "lines" is a list of lines to dedent. "tabsize" is the tab width to use for indent width calculations. "skip_first_line" is a boolean indicating if the first line should be skipped for calculating the indent width and for dedenting. This is sometimes useful for docstrings and similar. Same as dedent() except operates on a sequence of lines. Note: the lines list is modified **in-place**.
train
https://github.com/chibisov/drf-extensions/blob/1d28a4b28890eab5cd19e93e042f8590c8c2fb8b/docs/backdoc.py#L2012-L2080
null
# -*- coding: utf-8 -*- #!/usr/bin/env python """ Backdoc is a tool for backbone-like documentation generation. Backdoc main goal is to help to generate one page documentation from one markdown source file. https://github.com/chibisov/backdoc """ import sys import argparse # -*- coding: utf-8 -*- #!/usr/bin/env python # Copyright (c) 2012 Trent Mick. # Copyright (c) 2007-2008 ActiveState Corp. # License: MIT (http://www.opensource.org/licenses/mit-license.php) r"""A fast and complete Python implementation of Markdown. [from http://daringfireball.net/projects/markdown/] > Markdown is a text-to-HTML filter; it translates an easy-to-read / > easy-to-write structured text format into HTML. Markdown's text > format is most similar to that of plain text email, and supports > features such as headers, *emphasis*, code blocks, blockquotes, and > links. > > Markdown's syntax is designed not as a generic markup language, but > specifically to serve as a front-end to (X)HTML. You can use span-level > HTML tags anywhere in a Markdown document, and you can use block level > HTML tags (like <div> and <table> as well). Module usage: >>> import markdown2 >>> markdown2.markdown("*boo!*") # or use `html = markdown_path(PATH)` u'<p><em>boo!</em></p>\n' >>> markdowner = Markdown() >>> markdowner.convert("*boo!*") u'<p><em>boo!</em></p>\n' >>> markdowner.convert("**boom!**") u'<p><strong>boom!</strong></p>\n' This implementation of Markdown implements the full "core" syntax plus a number of extras (e.g., code syntax coloring, footnotes) as described on <https://github.com/trentm/python-markdown2/wiki/Extras>. """ cmdln_desc = """A fast and complete Python implementation of Markdown, a text-to-HTML conversion tool for web writers. Supported extra syntax options (see -x|--extras option below and see <https://github.com/trentm/python-markdown2/wiki/Extras> for details): * code-friendly: Disable _ and __ for em and strong. * cuddled-lists: Allow lists to be cuddled to the preceding paragraph. * fenced-code-blocks: Allows a code block to not have to be indented by fencing it with '```' on a line before and after. Based on <http://github.github.com/github-flavored-markdown/> with support for syntax highlighting. * footnotes: Support footnotes as in use on daringfireball.net and implemented in other Markdown processors (tho not in Markdown.pl v1.0.1). * header-ids: Adds "id" attributes to headers. The id value is a slug of the header text. * html-classes: Takes a dict mapping html tag names (lowercase) to a string to use for a "class" tag attribute. Currently only supports "pre" and "code" tags. Add an issue if you require this for other tags. * markdown-in-html: Allow the use of `markdown="1"` in a block HTML tag to have markdown processing be done on its contents. Similar to <http://michelf.com/projects/php-markdown/extra/#markdown-attr> but with some limitations. * metadata: Extract metadata from a leading '---'-fenced block. See <https://github.com/trentm/python-markdown2/issues/77> for details. * nofollow: Add `rel="nofollow"` to add `<a>` tags with an href. See <http://en.wikipedia.org/wiki/Nofollow>. * pyshell: Treats unindented Python interactive shell sessions as <code> blocks. * link-patterns: Auto-link given regex patterns in text (e.g. bug number references, revision number references). * smarty-pants: Replaces ' and " with curly quotation marks or curly apostrophes. Replaces --, ---, ..., and . . . with en dashes, em dashes, and ellipses. * toc: The returned HTML string gets a new "toc_html" attribute which is a Table of Contents for the document. (experimental) * xml: Passes one-liner processing instructions and namespaced XML tags. * wiki-tables: Google Code Wiki-style tables. See <http://code.google.com/p/support/wiki/WikiSyntax#Tables>. """ # Dev Notes: # - Python's regex syntax doesn't have '\z', so I'm using '\Z'. I'm # not yet sure if there implications with this. Compare 'pydoc sre' # and 'perldoc perlre'. __version_info__ = (2, 1, 1) __version__ = '.'.join(map(str, __version_info__)) __author__ = "Trent Mick" import os import sys from pprint import pprint import re import logging try: from hashlib import md5 except ImportError: from md5 import md5 import optparse from random import random, randint import codecs #---- Python version compat try: from urllib.parse import quote # python3 except ImportError: from urllib import quote # python2 if sys.version_info[:2] < (2,4): from sets import Set as set def reversed(sequence): for i in sequence[::-1]: yield i # Use `bytes` for byte strings and `unicode` for unicode strings (str in Py3). if sys.version_info[0] <= 2: py3 = False try: bytes except NameError: bytes = str base_string_type = basestring elif sys.version_info[0] >= 3: py3 = True unicode = str base_string_type = str #---- globals DEBUG = False log = logging.getLogger("markdown") DEFAULT_TAB_WIDTH = 4 SECRET_SALT = bytes(randint(0, 1000000)) def _hash_text(s): return 'md5-' + md5(SECRET_SALT + s.encode("utf-8")).hexdigest() # Table of hash values for escaped characters: g_escape_table = dict([(ch, _hash_text(ch)) for ch in '\\`*_{}[]()>#+-.!']) #---- exceptions class MarkdownError(Exception): pass #---- public api def markdown_path(path, encoding="utf-8", html4tags=False, tab_width=DEFAULT_TAB_WIDTH, safe_mode=None, extras=None, link_patterns=None, use_file_vars=False): fp = codecs.open(path, 'r', encoding) text = fp.read() fp.close() return Markdown(html4tags=html4tags, tab_width=tab_width, safe_mode=safe_mode, extras=extras, link_patterns=link_patterns, use_file_vars=use_file_vars).convert(text) def markdown(text, html4tags=False, tab_width=DEFAULT_TAB_WIDTH, safe_mode=None, extras=None, link_patterns=None, use_file_vars=False): return Markdown(html4tags=html4tags, tab_width=tab_width, safe_mode=safe_mode, extras=extras, link_patterns=link_patterns, use_file_vars=use_file_vars).convert(text) class Markdown(object): # The dict of "extras" to enable in processing -- a mapping of # extra name to argument for the extra. Most extras do not have an # argument, in which case the value is None. # # This can be set via (a) subclassing and (b) the constructor # "extras" argument. extras = None urls = None titles = None html_blocks = None html_spans = None html_removed_text = "[HTML_REMOVED]" # for compat with markdown.py # Used to track when we're inside an ordered or unordered list # (see _ProcessListItems() for details): list_level = 0 _ws_only_line_re = re.compile(r"^[ \t]+$", re.M) def __init__(self, html4tags=False, tab_width=4, safe_mode=None, extras=None, link_patterns=None, use_file_vars=False): if html4tags: self.empty_element_suffix = ">" else: self.empty_element_suffix = " />" self.tab_width = tab_width # For compatibility with earlier markdown2.py and with # markdown.py's safe_mode being a boolean, # safe_mode == True -> "replace" if safe_mode is True: self.safe_mode = "replace" else: self.safe_mode = safe_mode # Massaging and building the "extras" info. if self.extras is None: self.extras = {} elif not isinstance(self.extras, dict): self.extras = dict([(e, None) for e in self.extras]) if extras: if not isinstance(extras, dict): extras = dict([(e, None) for e in extras]) self.extras.update(extras) assert isinstance(self.extras, dict) if "toc" in self.extras and not "header-ids" in self.extras: self.extras["header-ids"] = None # "toc" implies "header-ids" self._instance_extras = self.extras.copy() self.link_patterns = link_patterns self.use_file_vars = use_file_vars self._outdent_re = re.compile(r'^(\t|[ ]{1,%d})' % tab_width, re.M) self._escape_table = g_escape_table.copy() if "smarty-pants" in self.extras: self._escape_table['"'] = _hash_text('"') self._escape_table["'"] = _hash_text("'") def reset(self): self.urls = {} self.titles = {} self.html_blocks = {} self.html_spans = {} self.list_level = 0 self.extras = self._instance_extras.copy() if "footnotes" in self.extras: self.footnotes = {} self.footnote_ids = [] if "header-ids" in self.extras: self._count_from_header_id = {} # no `defaultdict` in Python 2.4 if "metadata" in self.extras: self.metadata = {} # Per <https://developer.mozilla.org/en-US/docs/HTML/Element/a> "rel" # should only be used in <a> tags with an "href" attribute. _a_nofollow = re.compile(r"<(a)([^>]*href=)", re.IGNORECASE) def convert(self, text): """Convert the given text.""" # Main function. The order in which other subs are called here is # essential. Link and image substitutions need to happen before # _EscapeSpecialChars(), so that any *'s or _'s in the <a> # and <img> tags get encoded. # Clear the global hashes. If we don't clear these, you get conflicts # from other articles when generating a page which contains more than # one article (e.g. an index page that shows the N most recent # articles): self.reset() if not isinstance(text, unicode): #TODO: perhaps shouldn't presume UTF-8 for string input? text = unicode(text, 'utf-8') if self.use_file_vars: # Look for emacs-style file variable hints. emacs_vars = self._get_emacs_vars(text) if "markdown-extras" in emacs_vars: splitter = re.compile("[ ,]+") for e in splitter.split(emacs_vars["markdown-extras"]): if '=' in e: ename, earg = e.split('=', 1) try: earg = int(earg) except ValueError: pass else: ename, earg = e, None self.extras[ename] = earg # Standardize line endings: text = re.sub("\r\n|\r", "\n", text) # Make sure $text ends with a couple of newlines: text += "\n\n" # Convert all tabs to spaces. text = self._detab(text) # Strip any lines consisting only of spaces and tabs. # This makes subsequent regexen easier to write, because we can # match consecutive blank lines with /\n+/ instead of something # contorted like /[ \t]*\n+/ . text = self._ws_only_line_re.sub("", text) # strip metadata from head and extract if "metadata" in self.extras: text = self._extract_metadata(text) text = self.preprocess(text) if self.safe_mode: text = self._hash_html_spans(text) # Turn block-level HTML blocks into hash entries text = self._hash_html_blocks(text, raw=True) # Strip link definitions, store in hashes. if "footnotes" in self.extras: # Must do footnotes first because an unlucky footnote defn # looks like a link defn: # [^4]: this "looks like a link defn" text = self._strip_footnote_definitions(text) text = self._strip_link_definitions(text) text = self._run_block_gamut(text) if "footnotes" in self.extras: text = self._add_footnotes(text) text = self.postprocess(text) text = self._unescape_special_chars(text) if self.safe_mode: text = self._unhash_html_spans(text) if "nofollow" in self.extras: text = self._a_nofollow.sub(r'<\1 rel="nofollow"\2', text) text += "\n" rv = UnicodeWithAttrs(text) if "toc" in self.extras: rv._toc = self._toc if "metadata" in self.extras: rv.metadata = self.metadata return rv def postprocess(self, text): """A hook for subclasses to do some postprocessing of the html, if desired. This is called before unescaping of special chars and unhashing of raw HTML spans. """ return text def preprocess(self, text): """A hook for subclasses to do some preprocessing of the Markdown, if desired. This is called after basic formatting of the text, but prior to any extras, safe mode, etc. processing. """ return text # Is metadata if the content starts with '---'-fenced `key: value` # pairs. E.g. (indented for presentation): # --- # foo: bar # another-var: blah blah # --- _metadata_pat = re.compile("""^---[ \t]*\n((?:[ \t]*[^ \t:]+[ \t]*:[^\n]*\n)+)---[ \t]*\n""") def _extract_metadata(self, text): # fast test if not text.startswith("---"): return text match = self._metadata_pat.match(text) if not match: return text tail = text[len(match.group(0)):] metadata_str = match.group(1).strip() for line in metadata_str.split('\n'): key, value = line.split(':', 1) self.metadata[key.strip()] = value.strip() return tail _emacs_oneliner_vars_pat = re.compile(r"-\*-\s*([^\r\n]*?)\s*-\*-", re.UNICODE) # This regular expression is intended to match blocks like this: # PREFIX Local Variables: SUFFIX # PREFIX mode: Tcl SUFFIX # PREFIX End: SUFFIX # Some notes: # - "[ \t]" is used instead of "\s" to specifically exclude newlines # - "(\r\n|\n|\r)" is used instead of "$" because the sre engine does # not like anything other than Unix-style line terminators. _emacs_local_vars_pat = re.compile(r"""^ (?P<prefix>(?:[^\r\n|\n|\r])*?) [\ \t]*Local\ Variables:[\ \t]* (?P<suffix>.*?)(?:\r\n|\n|\r) (?P<content>.*?\1End:) """, re.IGNORECASE | re.MULTILINE | re.DOTALL | re.VERBOSE) def _get_emacs_vars(self, text): """Return a dictionary of emacs-style local variables. Parsing is done loosely according to this spec (and according to some in-practice deviations from this): http://www.gnu.org/software/emacs/manual/html_node/emacs/Specifying-File-Variables.html#Specifying-File-Variables """ emacs_vars = {} SIZE = pow(2, 13) # 8kB # Search near the start for a '-*-'-style one-liner of variables. head = text[:SIZE] if "-*-" in head: match = self._emacs_oneliner_vars_pat.search(head) if match: emacs_vars_str = match.group(1) assert '\n' not in emacs_vars_str emacs_var_strs = [s.strip() for s in emacs_vars_str.split(';') if s.strip()] if len(emacs_var_strs) == 1 and ':' not in emacs_var_strs[0]: # While not in the spec, this form is allowed by emacs: # -*- Tcl -*- # where the implied "variable" is "mode". This form # is only allowed if there are no other variables. emacs_vars["mode"] = emacs_var_strs[0].strip() else: for emacs_var_str in emacs_var_strs: try: variable, value = emacs_var_str.strip().split(':', 1) except ValueError: log.debug("emacs variables error: malformed -*- " "line: %r", emacs_var_str) continue # Lowercase the variable name because Emacs allows "Mode" # or "mode" or "MoDe", etc. emacs_vars[variable.lower()] = value.strip() tail = text[-SIZE:] if "Local Variables" in tail: match = self._emacs_local_vars_pat.search(tail) if match: prefix = match.group("prefix") suffix = match.group("suffix") lines = match.group("content").splitlines(0) #print "prefix=%r, suffix=%r, content=%r, lines: %s"\ # % (prefix, suffix, match.group("content"), lines) # Validate the Local Variables block: proper prefix and suffix # usage. for i, line in enumerate(lines): if not line.startswith(prefix): log.debug("emacs variables error: line '%s' " "does not use proper prefix '%s'" % (line, prefix)) return {} # Don't validate suffix on last line. Emacs doesn't care, # neither should we. if i != len(lines)-1 and not line.endswith(suffix): log.debug("emacs variables error: line '%s' " "does not use proper suffix '%s'" % (line, suffix)) return {} # Parse out one emacs var per line. continued_for = None for line in lines[:-1]: # no var on the last line ("PREFIX End:") if prefix: line = line[len(prefix):] # strip prefix if suffix: line = line[:-len(suffix)] # strip suffix line = line.strip() if continued_for: variable = continued_for if line.endswith('\\'): line = line[:-1].rstrip() else: continued_for = None emacs_vars[variable] += ' ' + line else: try: variable, value = line.split(':', 1) except ValueError: log.debug("local variables error: missing colon " "in local variables entry: '%s'" % line) continue # Do NOT lowercase the variable name, because Emacs only # allows "mode" (and not "Mode", "MoDe", etc.) in this block. value = value.strip() if value.endswith('\\'): value = value[:-1].rstrip() continued_for = variable else: continued_for = None emacs_vars[variable] = value # Unquote values. for var, val in list(emacs_vars.items()): if len(val) > 1 and (val.startswith('"') and val.endswith('"') or val.startswith('"') and val.endswith('"')): emacs_vars[var] = val[1:-1] return emacs_vars # Cribbed from a post by Bart Lateur: # <http://www.nntp.perl.org/group/perl.macperl.anyperl/154> _detab_re = re.compile(r'(.*?)\t', re.M) def _detab_sub(self, match): g1 = match.group(1) return g1 + (' ' * (self.tab_width - len(g1) % self.tab_width)) def _detab(self, text): r"""Remove (leading?) tabs from a file. >>> m = Markdown() >>> m._detab("\tfoo") ' foo' >>> m._detab(" \tfoo") ' foo' >>> m._detab("\t foo") ' foo' >>> m._detab(" foo") ' foo' >>> m._detab(" foo\n\tbar\tblam") ' foo\n bar blam' """ if '\t' not in text: return text return self._detab_re.subn(self._detab_sub, text)[0] # I broke out the html5 tags here and add them to _block_tags_a and # _block_tags_b. This way html5 tags are easy to keep track of. _html5tags = '|article|aside|header|hgroup|footer|nav|section|figure|figcaption' _block_tags_a = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del' _block_tags_a += _html5tags _strict_tag_block_re = re.compile(r""" ( # save in \1 ^ # start of line (with re.M) <(%s) # start tag = \2 \b # word break (.*\n)*? # any number of lines, minimally matching </\2> # the matching end tag [ \t]* # trailing spaces/tabs (?=\n+|\Z) # followed by a newline or end of document ) """ % _block_tags_a, re.X | re.M) _block_tags_b = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math' _block_tags_b += _html5tags _liberal_tag_block_re = re.compile(r""" ( # save in \1 ^ # start of line (with re.M) <(%s) # start tag = \2 \b # word break (.*\n)*? # any number of lines, minimally matching .*</\2> # the matching end tag [ \t]* # trailing spaces/tabs (?=\n+|\Z) # followed by a newline or end of document ) """ % _block_tags_b, re.X | re.M) _html_markdown_attr_re = re.compile( r'''\s+markdown=("1"|'1')''') def _hash_html_block_sub(self, match, raw=False): html = match.group(1) if raw and self.safe_mode: html = self._sanitize_html(html) elif 'markdown-in-html' in self.extras and 'markdown=' in html: first_line = html.split('\n', 1)[0] m = self._html_markdown_attr_re.search(first_line) if m: lines = html.split('\n') middle = '\n'.join(lines[1:-1]) last_line = lines[-1] first_line = first_line[:m.start()] + first_line[m.end():] f_key = _hash_text(first_line) self.html_blocks[f_key] = first_line l_key = _hash_text(last_line) self.html_blocks[l_key] = last_line return ''.join(["\n\n", f_key, "\n\n", middle, "\n\n", l_key, "\n\n"]) key = _hash_text(html) self.html_blocks[key] = html return "\n\n" + key + "\n\n" def _hash_html_blocks(self, text, raw=False): """Hashify HTML blocks We only want to do this for block-level HTML tags, such as headers, lists, and tables. That's because we still want to wrap <p>s around "paragraphs" that are wrapped in non-block-level tags, such as anchors, phrase emphasis, and spans. The list of tags we're looking for is hard-coded. @param raw {boolean} indicates if these are raw HTML blocks in the original source. It makes a difference in "safe" mode. """ if '<' not in text: return text # Pass `raw` value into our calls to self._hash_html_block_sub. hash_html_block_sub = _curry(self._hash_html_block_sub, raw=raw) # First, look for nested blocks, e.g.: # <div> # <div> # tags for inner block must be indented. # </div> # </div> # # The outermost tags must start at the left margin for this to match, and # the inner nested divs must be indented. # We need to do this before the next, more liberal match, because the next # match will start at the first `<div>` and stop at the first `</div>`. text = self._strict_tag_block_re.sub(hash_html_block_sub, text) # Now match more liberally, simply from `\n<tag>` to `</tag>\n` text = self._liberal_tag_block_re.sub(hash_html_block_sub, text) # Special case just for <hr />. It was easier to make a special # case than to make the other regex more complicated. if "<hr" in text: _hr_tag_re = _hr_tag_re_from_tab_width(self.tab_width) text = _hr_tag_re.sub(hash_html_block_sub, text) # Special case for standalone HTML comments: if "<!--" in text: start = 0 while True: # Delimiters for next comment block. try: start_idx = text.index("<!--", start) except ValueError: break try: end_idx = text.index("-->", start_idx) + 3 except ValueError: break # Start position for next comment block search. start = end_idx # Validate whitespace before comment. if start_idx: # - Up to `tab_width - 1` spaces before start_idx. for i in range(self.tab_width - 1): if text[start_idx - 1] != ' ': break start_idx -= 1 if start_idx == 0: break # - Must be preceded by 2 newlines or hit the start of # the document. if start_idx == 0: pass elif start_idx == 1 and text[0] == '\n': start_idx = 0 # to match minute detail of Markdown.pl regex elif text[start_idx-2:start_idx] == '\n\n': pass else: break # Validate whitespace after comment. # - Any number of spaces and tabs. while end_idx < len(text): if text[end_idx] not in ' \t': break end_idx += 1 # - Must be following by 2 newlines or hit end of text. if text[end_idx:end_idx+2] not in ('', '\n', '\n\n'): continue # Escape and hash (must match `_hash_html_block_sub`). html = text[start_idx:end_idx] if raw and self.safe_mode: html = self._sanitize_html(html) key = _hash_text(html) self.html_blocks[key] = html text = text[:start_idx] + "\n\n" + key + "\n\n" + text[end_idx:] if "xml" in self.extras: # Treat XML processing instructions and namespaced one-liner # tags as if they were block HTML tags. E.g., if standalone # (i.e. are their own paragraph), the following do not get # wrapped in a <p> tag: # <?foo bar?> # # <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="chapter_1.md"/> _xml_oneliner_re = _xml_oneliner_re_from_tab_width(self.tab_width) text = _xml_oneliner_re.sub(hash_html_block_sub, text) return text def _strip_link_definitions(self, text): # Strips link definitions from text, stores the URLs and titles in # hash references. less_than_tab = self.tab_width - 1 # Link defs are in the form: # [id]: url "optional title" _link_def_re = re.compile(r""" ^[ ]{0,%d}\[(.+)\]: # id = \1 [ \t]* \n? # maybe *one* newline [ \t]* <?(.+?)>? # url = \2 [ \t]* (?: \n? # maybe one newline [ \t]* (?<=\s) # lookbehind for whitespace ['"(] ([^\n]*) # title = \3 ['")] [ \t]* )? # title is optional (?:\n+|\Z) """ % less_than_tab, re.X | re.M | re.U) return _link_def_re.sub(self._extract_link_def_sub, text) def _extract_link_def_sub(self, match): id, url, title = match.groups() key = id.lower() # Link IDs are case-insensitive self.urls[key] = self._encode_amps_and_angles(url) if title: self.titles[key] = title return "" def _extract_footnote_def_sub(self, match): id, text = match.groups() text = _dedent(text, skip_first_line=not text.startswith('\n')).strip() normed_id = re.sub(r'\W', '-', id) # Ensure footnote text ends with a couple newlines (for some # block gamut matches). self.footnotes[normed_id] = text + "\n\n" return "" def _strip_footnote_definitions(self, text): """A footnote definition looks like this: [^note-id]: Text of the note. May include one or more indented paragraphs. Where, - The 'note-id' can be pretty much anything, though typically it is the number of the footnote. - The first paragraph may start on the next line, like so: [^note-id]: Text of the note. """ less_than_tab = self.tab_width - 1 footnote_def_re = re.compile(r''' ^[ ]{0,%d}\[\^(.+)\]: # id = \1 [ \t]* ( # footnote text = \2 # First line need not start with the spaces. (?:\s*.*\n+) (?: (?:[ ]{%d} | \t) # Subsequent lines must be indented. .*\n+ )* ) # Lookahead for non-space at line-start, or end of doc. (?:(?=^[ ]{0,%d}\S)|\Z) ''' % (less_than_tab, self.tab_width, self.tab_width), re.X | re.M) return footnote_def_re.sub(self._extract_footnote_def_sub, text) _hr_data = [ ('*', re.compile(r"^[ ]{0,3}\*(.*?)$", re.M)), ('-', re.compile(r"^[ ]{0,3}\-(.*?)$", re.M)), ('_', re.compile(r"^[ ]{0,3}\_(.*?)$", re.M)), ] def _run_block_gamut(self, text): # These are all the transformations that form block-level # tags like paragraphs, headers, and list items. if "fenced-code-blocks" in self.extras: text = self._do_fenced_code_blocks(text) text = self._do_headers(text) # Do Horizontal Rules: # On the number of spaces in horizontal rules: The spec is fuzzy: "If # you wish, you may use spaces between the hyphens or asterisks." # Markdown.pl 1.0.1's hr regexes limit the number of spaces between the # hr chars to one or two. We'll reproduce that limit here. hr = "\n<hr"+self.empty_element_suffix+"\n" for ch, regex in self._hr_data: if ch in text: for m in reversed(list(regex.finditer(text))): tail = m.group(1).rstrip() if not tail.strip(ch + ' ') and tail.count(" ") == 0: start, end = m.span() text = text[:start] + hr + text[end:] text = self._do_lists(text) if "pyshell" in self.extras: text = self._prepare_pyshell_blocks(text) if "wiki-tables" in self.extras: text = self._do_wiki_tables(text) text = self._do_code_blocks(text) text = self._do_block_quotes(text) # We already ran _HashHTMLBlocks() before, in Markdown(), but that # was to escape raw HTML in the original Markdown source. This time, # we're escaping the markup we've just created, so that we don't wrap # <p> tags around block-level tags. text = self._hash_html_blocks(text) text = self._form_paragraphs(text) return text def _pyshell_block_sub(self, match): lines = match.group(0).splitlines(0) _dedentlines(lines) indent = ' ' * self.tab_width s = ('\n' # separate from possible cuddled paragraph + indent + ('\n'+indent).join(lines) + '\n\n') return s def _prepare_pyshell_blocks(self, text): """Ensure that Python interactive shell sessions are put in code blocks -- even if not properly indented. """ if ">>>" not in text: return text less_than_tab = self.tab_width - 1 _pyshell_block_re = re.compile(r""" ^([ ]{0,%d})>>>[ ].*\n # first line ^(\1.*\S+.*\n)* # any number of subsequent lines ^\n # ends with a blank line """ % less_than_tab, re.M | re.X) return _pyshell_block_re.sub(self._pyshell_block_sub, text) def _wiki_table_sub(self, match): ttext = match.group(0).strip() #print 'wiki table: %r' % match.group(0) rows = [] for line in ttext.splitlines(0): line = line.strip()[2:-2].strip() row = [c.strip() for c in re.split(r'(?<!\\)\|\|', line)] rows.append(row) #pprint(rows) hlines = ['<table>', '<tbody>'] for row in rows: hrow = ['<tr>'] for cell in row: hrow.append('<td>') hrow.append(self._run_span_gamut(cell)) hrow.append('</td>') hrow.append('</tr>') hlines.append(''.join(hrow)) hlines += ['</tbody>', '</table>'] return '\n'.join(hlines) + '\n' def _do_wiki_tables(self, text): # Optimization. if "||" not in text: return text less_than_tab = self.tab_width - 1 wiki_table_re = re.compile(r''' (?:(?<=\n\n)|\A\n?) # leading blank line ^([ ]{0,%d})\|\|.+?\|\|[ ]*\n # first line (^\1\|\|.+?\|\|\n)* # any number of subsequent lines ''' % less_than_tab, re.M | re.X) return wiki_table_re.sub(self._wiki_table_sub, text) def _run_span_gamut(self, text): # These are all the transformations that occur *within* block-level # tags like paragraphs, headers, and list items. text = self._do_code_spans(text) text = self._escape_special_chars(text) # Process anchor and image tags. text = self._do_links(text) # Make links out of things like `<http://example.com/>` # Must come after _do_links(), because you can use < and > # delimiters in inline links like [this](<url>). text = self._do_auto_links(text) if "link-patterns" in self.extras: text = self._do_link_patterns(text) text = self._encode_amps_and_angles(text) text = self._do_italics_and_bold(text) if "smarty-pants" in self.extras: text = self._do_smart_punctuation(text) # Do hard breaks: text = re.sub(r" {2,}\n", " <br%s\n" % self.empty_element_suffix, text) return text # "Sorta" because auto-links are identified as "tag" tokens. _sorta_html_tokenize_re = re.compile(r""" ( # tag </? (?:\w+) # tag name (?:\s+(?:[\w-]+:)?[\w-]+=(?:".*?"|'.*?'))* # attributes \s*/?> | # auto-link (e.g., <http://www.activestate.com/>) <\w+[^>]*> | <!--.*?--> # comment | <\?.*?\?> # processing instruction ) """, re.X) def _escape_special_chars(self, text): # Python markdown note: the HTML tokenization here differs from # that in Markdown.pl, hence the behaviour for subtle cases can # differ (I believe the tokenizer here does a better job because # it isn't susceptible to unmatched '<' and '>' in HTML tags). # Note, however, that '>' is not allowed in an auto-link URL # here. escaped = [] is_html_markup = False for token in self._sorta_html_tokenize_re.split(text): if is_html_markup: # Within tags/HTML-comments/auto-links, encode * and _ # so they don't conflict with their use in Markdown for # italics and strong. We're replacing each such # character with its corresponding MD5 checksum value; # this is likely overkill, but it should prevent us from # colliding with the escape values by accident. escaped.append(token.replace('*', self._escape_table['*']) .replace('_', self._escape_table['_'])) else: escaped.append(self._encode_backslash_escapes(token)) is_html_markup = not is_html_markup return ''.join(escaped) def _hash_html_spans(self, text): # Used for safe_mode. def _is_auto_link(s): if ':' in s and self._auto_link_re.match(s): return True elif '@' in s and self._auto_email_link_re.match(s): return True return False tokens = [] is_html_markup = False for token in self._sorta_html_tokenize_re.split(text): if is_html_markup and not _is_auto_link(token): sanitized = self._sanitize_html(token) key = _hash_text(sanitized) self.html_spans[key] = sanitized tokens.append(key) else: tokens.append(token) is_html_markup = not is_html_markup return ''.join(tokens) def _unhash_html_spans(self, text): for key, sanitized in list(self.html_spans.items()): text = text.replace(key, sanitized) return text def _sanitize_html(self, s): if self.safe_mode == "replace": return self.html_removed_text elif self.safe_mode == "escape": replacements = [ ('&', '&amp;'), ('<', '&lt;'), ('>', '&gt;'), ] for before, after in replacements: s = s.replace(before, after) return s else: raise MarkdownError("invalid value for 'safe_mode': %r (must be " "'escape' or 'replace')" % self.safe_mode) _tail_of_inline_link_re = re.compile(r''' # Match tail of: [text](/url/) or [text](/url/ "title") \( # literal paren [ \t]* (?P<url> # \1 <.*?> | .*? ) [ \t]* ( # \2 (['"]) # quote char = \3 (?P<title>.*?) \3 # matching quote )? # title is optional \) ''', re.X | re.S) _tail_of_reference_link_re = re.compile(r''' # Match tail of: [text][id] [ ]? # one optional space (?:\n[ ]*)? # one optional newline followed by spaces \[ (?P<id>.*?) \] ''', re.X | re.S) def _do_links(self, text): """Turn Markdown link shortcuts into XHTML <a> and <img> tags. This is a combination of Markdown.pl's _DoAnchors() and _DoImages(). They are done together because that simplified the approach. It was necessary to use a different approach than Markdown.pl because of the lack of atomic matching support in Python's regex engine used in $g_nested_brackets. """ MAX_LINK_TEXT_SENTINEL = 3000 # markdown2 issue 24 # `anchor_allowed_pos` is used to support img links inside # anchors, but not anchors inside anchors. An anchor's start # pos must be `>= anchor_allowed_pos`. anchor_allowed_pos = 0 curr_pos = 0 while True: # Handle the next link. # The next '[' is the start of: # - an inline anchor: [text](url "title") # - a reference anchor: [text][id] # - an inline img: ![text](url "title") # - a reference img: ![text][id] # - a footnote ref: [^id] # (Only if 'footnotes' extra enabled) # - a footnote defn: [^id]: ... # (Only if 'footnotes' extra enabled) These have already # been stripped in _strip_footnote_definitions() so no # need to watch for them. # - a link definition: [id]: url "title" # These have already been stripped in # _strip_link_definitions() so no need to watch for them. # - not markup: [...anything else... try: start_idx = text.index('[', curr_pos) except ValueError: break text_length = len(text) # Find the matching closing ']'. # Markdown.pl allows *matching* brackets in link text so we # will here too. Markdown.pl *doesn't* currently allow # matching brackets in img alt text -- we'll differ in that # regard. bracket_depth = 0 for p in range(start_idx+1, min(start_idx+MAX_LINK_TEXT_SENTINEL, text_length)): ch = text[p] if ch == ']': bracket_depth -= 1 if bracket_depth < 0: break elif ch == '[': bracket_depth += 1 else: # Closing bracket not found within sentinel length. # This isn't markup. curr_pos = start_idx + 1 continue link_text = text[start_idx+1:p] # Possibly a footnote ref? if "footnotes" in self.extras and link_text.startswith("^"): normed_id = re.sub(r'\W', '-', link_text[1:]) if normed_id in self.footnotes: self.footnote_ids.append(normed_id) result = '<sup class="footnote-ref" id="fnref-%s">' \ '<a href="#fn-%s">%s</a></sup>' \ % (normed_id, normed_id, len(self.footnote_ids)) text = text[:start_idx] + result + text[p+1:] else: # This id isn't defined, leave the markup alone. curr_pos = p+1 continue # Now determine what this is by the remainder. p += 1 if p == text_length: return text # Inline anchor or img? if text[p] == '(': # attempt at perf improvement match = self._tail_of_inline_link_re.match(text, p) if match: # Handle an inline anchor or img. is_img = start_idx > 0 and text[start_idx-1] == "!" if is_img: start_idx -= 1 url, title = match.group("url"), match.group("title") if url and url[0] == '<': url = url[1:-1] # '<url>' -> 'url' # We've got to encode these to avoid conflicting # with italics/bold. url = url.replace('*', self._escape_table['*']) \ .replace('_', self._escape_table['_']) if title: title_str = ' title="%s"' % ( _xml_escape_attr(title) .replace('*', self._escape_table['*']) .replace('_', self._escape_table['_'])) else: title_str = '' if is_img: result = '<img src="%s" alt="%s"%s%s' \ % (url.replace('"', '&quot;'), _xml_escape_attr(link_text), title_str, self.empty_element_suffix) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) curr_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] elif start_idx >= anchor_allowed_pos: result_head = '<a href="%s"%s>' % (url, title_str) result = '%s%s</a>' % (result_head, link_text) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) # <img> allowed from curr_pos on, <a> from # anchor_allowed_pos on. curr_pos = start_idx + len(result_head) anchor_allowed_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] else: # Anchor not allowed here. curr_pos = start_idx + 1 continue # Reference anchor or img? else: match = self._tail_of_reference_link_re.match(text, p) if match: # Handle a reference-style anchor or img. is_img = start_idx > 0 and text[start_idx-1] == "!" if is_img: start_idx -= 1 link_id = match.group("id").lower() if not link_id: link_id = link_text.lower() # for links like [this][] if link_id in self.urls: url = self.urls[link_id] # We've got to encode these to avoid conflicting # with italics/bold. url = url.replace('*', self._escape_table['*']) \ .replace('_', self._escape_table['_']) title = self.titles.get(link_id) if title: before = title title = _xml_escape_attr(title) \ .replace('*', self._escape_table['*']) \ .replace('_', self._escape_table['_']) title_str = ' title="%s"' % title else: title_str = '' if is_img: result = '<img src="%s" alt="%s"%s%s' \ % (url.replace('"', '&quot;'), link_text.replace('"', '&quot;'), title_str, self.empty_element_suffix) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) curr_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] elif start_idx >= anchor_allowed_pos: result = '<a href="%s"%s>%s</a>' \ % (url, title_str, link_text) result_head = '<a href="%s"%s>' % (url, title_str) result = '%s%s</a>' % (result_head, link_text) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) # <img> allowed from curr_pos on, <a> from # anchor_allowed_pos on. curr_pos = start_idx + len(result_head) anchor_allowed_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] else: # Anchor not allowed here. curr_pos = start_idx + 1 else: # This id isn't defined, leave the markup alone. curr_pos = match.end() continue # Otherwise, it isn't markup. curr_pos = start_idx + 1 return text def header_id_from_text(self, text, prefix, n): """Generate a header id attribute value from the given header HTML content. This is only called if the "header-ids" extra is enabled. Subclasses may override this for different header ids. @param text {str} The text of the header tag @param prefix {str} The requested prefix for header ids. This is the value of the "header-ids" extra key, if any. Otherwise, None. @param n {int} The <hN> tag number, i.e. `1` for an <h1> tag. @returns {str} The value for the header tag's "id" attribute. Return None to not have an id attribute and to exclude this header from the TOC (if the "toc" extra is specified). """ header_id = _slugify(text) if prefix and isinstance(prefix, base_string_type): header_id = prefix + '-' + header_id if header_id in self._count_from_header_id: self._count_from_header_id[header_id] += 1 header_id += '-%s' % self._count_from_header_id[header_id] else: self._count_from_header_id[header_id] = 1 return header_id _toc = None def _toc_add_entry(self, level, id, name): if self._toc is None: self._toc = [] self._toc.append((level, id, self._unescape_special_chars(name))) _setext_h_re = re.compile(r'^(.+)[ \t]*\n(=+|-+)[ \t]*\n+', re.M) def _setext_h_sub(self, match): n = {"=": 1, "-": 2}[match.group(2)[0]] demote_headers = self.extras.get("demote-headers") if demote_headers: n = min(n + demote_headers, 6) header_id_attr = "" if "header-ids" in self.extras: header_id = self.header_id_from_text(match.group(1), self.extras["header-ids"], n) if header_id: header_id_attr = ' id="%s"' % header_id html = self._run_span_gamut(match.group(1)) if "toc" in self.extras and header_id: self._toc_add_entry(n, header_id, html) return "<h%d%s>%s</h%d>\n\n" % (n, header_id_attr, html, n) _atx_h_re = re.compile(r''' ^(\#{1,6}) # \1 = string of #'s [ \t]+ (.+?) # \2 = Header text [ \t]* (?<!\\) # ensure not an escaped trailing '#' \#* # optional closing #'s (not counted) \n+ ''', re.X | re.M) def _atx_h_sub(self, match): n = len(match.group(1)) demote_headers = self.extras.get("demote-headers") if demote_headers: n = min(n + demote_headers, 6) header_id_attr = "" if "header-ids" in self.extras: header_id = self.header_id_from_text(match.group(2), self.extras["header-ids"], n) if header_id: header_id_attr = ' id="%s"' % header_id html = self._run_span_gamut(match.group(2)) if "toc" in self.extras and header_id: self._toc_add_entry(n, header_id, html) return "<h%d%s>%s</h%d>\n\n" % (n, header_id_attr, html, n) def _do_headers(self, text): # Setext-style headers: # Header 1 # ======== # # Header 2 # -------- text = self._setext_h_re.sub(self._setext_h_sub, text) # atx-style headers: # # Header 1 # ## Header 2 # ## Header 2 with closing hashes ## # ... # ###### Header 6 text = self._atx_h_re.sub(self._atx_h_sub, text) return text _marker_ul_chars = '*+-' _marker_any = r'(?:[%s]|\d+\.)' % _marker_ul_chars _marker_ul = '(?:[%s])' % _marker_ul_chars _marker_ol = r'(?:\d+\.)' def _list_sub(self, match): lst = match.group(1) lst_type = match.group(3) in self._marker_ul_chars and "ul" or "ol" result = self._process_list_items(lst) if self.list_level: return "<%s>\n%s</%s>\n" % (lst_type, result, lst_type) else: return "<%s>\n%s</%s>\n\n" % (lst_type, result, lst_type) def _do_lists(self, text): # Form HTML ordered (numbered) and unordered (bulleted) lists. # Iterate over each *non-overlapping* list match. pos = 0 while True: # Find the *first* hit for either list style (ul or ol). We # match ul and ol separately to avoid adjacent lists of different # types running into each other (see issue #16). hits = [] for marker_pat in (self._marker_ul, self._marker_ol): less_than_tab = self.tab_width - 1 whole_list = r''' ( # \1 = whole list ( # \2 [ ]{0,%d} (%s) # \3 = first list item marker [ \t]+ (?!\ *\3\ ) # '- - - ...' isn't a list. See 'not_quite_a_list' test case. ) (?:.+?) ( # \4 \Z | \n{2,} (?=\S) (?! # Negative lookahead for another list item marker [ \t]* %s[ \t]+ ) ) ) ''' % (less_than_tab, marker_pat, marker_pat) if self.list_level: # sub-list list_re = re.compile("^"+whole_list, re.X | re.M | re.S) else: list_re = re.compile(r"(?:(?<=\n\n)|\A\n?)"+whole_list, re.X | re.M | re.S) match = list_re.search(text, pos) if match: hits.append((match.start(), match)) if not hits: break hits.sort() match = hits[0][1] start, end = match.span() text = text[:start] + self._list_sub(match) + text[end:] pos = end return text _list_item_re = re.compile(r''' (\n)? # leading line = \1 (^[ \t]*) # leading whitespace = \2 (?P<marker>%s) [ \t]+ # list marker = \3 ((?:.+?) # list item text = \4 (\n{1,2})) # eols = \5 (?= \n* (\Z | \2 (?P<next_marker>%s) [ \t]+)) ''' % (_marker_any, _marker_any), re.M | re.X | re.S) _last_li_endswith_two_eols = False def _list_item_sub(self, match): item = match.group(4) leading_line = match.group(1) leading_space = match.group(2) if leading_line or "\n\n" in item or self._last_li_endswith_two_eols: item = self._run_block_gamut(self._outdent(item)) else: # Recursion for sub-lists: item = self._do_lists(self._outdent(item)) if item.endswith('\n'): item = item[:-1] item = self._run_span_gamut(item) self._last_li_endswith_two_eols = (len(match.group(5)) == 2) return "<li>%s</li>\n" % item def _process_list_items(self, list_str): # Process the contents of a single ordered or unordered list, # splitting it into individual list items. # The $g_list_level global keeps track of when we're inside a list. # Each time we enter a list, we increment it; when we leave a list, # we decrement. If it's zero, we're not in a list anymore. # # We do this because when we're not inside a list, we want to treat # something like this: # # I recommend upgrading to version # 8. Oops, now this line is treated # as a sub-list. # # As a single paragraph, despite the fact that the second line starts # with a digit-period-space sequence. # # Whereas when we're inside a list (or sub-list), that line will be # treated as the start of a sub-list. What a kludge, huh? This is # an aspect of Markdown's syntax that's hard to parse perfectly # without resorting to mind-reading. Perhaps the solution is to # change the syntax rules such that sub-lists must start with a # starting cardinal number; e.g. "1." or "a.". self.list_level += 1 self._last_li_endswith_two_eols = False list_str = list_str.rstrip('\n') + '\n' list_str = self._list_item_re.sub(self._list_item_sub, list_str) self.list_level -= 1 return list_str def _get_pygments_lexer(self, lexer_name): try: from pygments import lexers, util except ImportError: return None try: return lexers.get_lexer_by_name(lexer_name) except util.ClassNotFound: return None def _color_with_pygments(self, codeblock, lexer, **formatter_opts): import pygments import pygments.formatters class HtmlCodeFormatter(pygments.formatters.HtmlFormatter): def _wrap_code(self, inner): """A function for use in a Pygments Formatter which wraps in <code> tags. """ yield 0, "<code>" for tup in inner: yield tup yield 0, "</code>" def wrap(self, source, outfile): """Return the source with a code, pre, and div.""" return self._wrap_div(self._wrap_pre(self._wrap_code(source))) formatter_opts.setdefault("cssclass", "codehilite") formatter = HtmlCodeFormatter(**formatter_opts) return pygments.highlight(codeblock, lexer, formatter) def _code_block_sub(self, match, is_fenced_code_block=False): lexer_name = None if is_fenced_code_block: lexer_name = match.group(1) if lexer_name: formatter_opts = self.extras['fenced-code-blocks'] or {} codeblock = match.group(2) codeblock = codeblock[:-1] # drop one trailing newline else: codeblock = match.group(1) codeblock = self._outdent(codeblock) codeblock = self._detab(codeblock) codeblock = codeblock.lstrip('\n') # trim leading newlines codeblock = codeblock.rstrip() # trim trailing whitespace # Note: "code-color" extra is DEPRECATED. if "code-color" in self.extras and codeblock.startswith(":::"): lexer_name, rest = codeblock.split('\n', 1) lexer_name = lexer_name[3:].strip() codeblock = rest.lstrip("\n") # Remove lexer declaration line. formatter_opts = self.extras['code-color'] or {} if lexer_name: lexer = self._get_pygments_lexer(lexer_name) if lexer: colored = self._color_with_pygments(codeblock, lexer, **formatter_opts) return "\n\n%s\n\n" % colored codeblock = self._encode_code(codeblock) pre_class_str = self._html_class_str_from_tag("pre") code_class_str = self._html_class_str_from_tag("code") return "\n\n<pre%s><code%s>%s\n</code></pre>\n\n" % ( pre_class_str, code_class_str, codeblock) def _html_class_str_from_tag(self, tag): """Get the appropriate ' class="..."' string (note the leading space), if any, for the given tag. """ if "html-classes" not in self.extras: return "" try: html_classes_from_tag = self.extras["html-classes"] except TypeError: return "" else: if tag in html_classes_from_tag: return ' class="%s"' % html_classes_from_tag[tag] return "" def _do_code_blocks(self, text): """Process Markdown `<pre><code>` blocks.""" code_block_re = re.compile(r''' (?:\n\n|\A\n?) ( # $1 = the code block -- one or more lines, starting with a space/tab (?: (?:[ ]{%d} | \t) # Lines must start with a tab or a tab-width of spaces .*\n+ )+ ) ((?=^[ ]{0,%d}\S)|\Z) # Lookahead for non-space at line-start, or end of doc ''' % (self.tab_width, self.tab_width), re.M | re.X) return code_block_re.sub(self._code_block_sub, text) _fenced_code_block_re = re.compile(r''' (?:\n\n|\A\n?) ^```([\w+-]+)?[ \t]*\n # opening fence, $1 = optional lang (.*?) # $2 = code block content ^```[ \t]*\n # closing fence ''', re.M | re.X | re.S) def _fenced_code_block_sub(self, match): return self._code_block_sub(match, is_fenced_code_block=True); def _do_fenced_code_blocks(self, text): """Process ```-fenced unindented code blocks ('fenced-code-blocks' extra).""" return self._fenced_code_block_re.sub(self._fenced_code_block_sub, text) # Rules for a code span: # - backslash escapes are not interpreted in a code span # - to include one or or a run of more backticks the delimiters must # be a longer run of backticks # - cannot start or end a code span with a backtick; pad with a # space and that space will be removed in the emitted HTML # See `test/tm-cases/escapes.text` for a number of edge-case # examples. _code_span_re = re.compile(r''' (?<!\\) (`+) # \1 = Opening run of ` (?!`) # See Note A test/tm-cases/escapes.text (.+?) # \2 = The code block (?<!`) \1 # Matching closer (?!`) ''', re.X | re.S) def _code_span_sub(self, match): c = match.group(2).strip(" \t") c = self._encode_code(c) return "<code>%s</code>" % c def _do_code_spans(self, text): # * Backtick quotes are used for <code></code> spans. # # * You can use multiple backticks as the delimiters if you want to # include literal backticks in the code span. So, this input: # # Just type ``foo `bar` baz`` at the prompt. # # Will translate to: # # <p>Just type <code>foo `bar` baz</code> at the prompt.</p> # # There's no arbitrary limit to the number of backticks you # can use as delimters. If you need three consecutive backticks # in your code, use four for delimiters, etc. # # * You can use spaces to get literal backticks at the edges: # # ... type `` `bar` `` ... # # Turns to: # # ... type <code>`bar`</code> ... return self._code_span_re.sub(self._code_span_sub, text) def _encode_code(self, text): """Encode/escape certain characters inside Markdown code runs. The point is that in code, these characters are literals, and lose their special Markdown meanings. """ replacements = [ # Encode all ampersands; HTML entities are not # entities within a Markdown code span. ('&', '&amp;'), # Do the angle bracket song and dance: ('<', '&lt;'), ('>', '&gt;'), ] for before, after in replacements: text = text.replace(before, after) hashed = _hash_text(text) self._escape_table[text] = hashed return hashed _strong_re = re.compile(r"(\*\*|__)(?=\S)(.+?[*_]*)(?<=\S)\1", re.S) _em_re = re.compile(r"(\*|_)(?=\S)(.+?)(?<=\S)\1", re.S) _code_friendly_strong_re = re.compile(r"\*\*(?=\S)(.+?[*_]*)(?<=\S)\*\*", re.S) _code_friendly_em_re = re.compile(r"\*(?=\S)(.+?)(?<=\S)\*", re.S) def _do_italics_and_bold(self, text): # <strong> must go first: if "code-friendly" in self.extras: text = self._code_friendly_strong_re.sub(r"<strong>\1</strong>", text) text = self._code_friendly_em_re.sub(r"<em>\1</em>", text) else: text = self._strong_re.sub(r"<strong>\2</strong>", text) text = self._em_re.sub(r"<em>\2</em>", text) return text # "smarty-pants" extra: Very liberal in interpreting a single prime as an # apostrophe; e.g. ignores the fact that "round", "bout", "twer", and # "twixt" can be written without an initial apostrophe. This is fine because # using scare quotes (single quotation marks) is rare. _apostrophe_year_re = re.compile(r"'(\d\d)(?=(\s|,|;|\.|\?|!|$))") _contractions = ["tis", "twas", "twer", "neath", "o", "n", "round", "bout", "twixt", "nuff", "fraid", "sup"] def _do_smart_contractions(self, text): text = self._apostrophe_year_re.sub(r"&#8217;\1", text) for c in self._contractions: text = text.replace("'%s" % c, "&#8217;%s" % c) text = text.replace("'%s" % c.capitalize(), "&#8217;%s" % c.capitalize()) return text # Substitute double-quotes before single-quotes. _opening_single_quote_re = re.compile(r"(?<!\S)'(?=\S)") _opening_double_quote_re = re.compile(r'(?<!\S)"(?=\S)') _closing_single_quote_re = re.compile(r"(?<=\S)'") _closing_double_quote_re = re.compile(r'(?<=\S)"(?=(\s|,|;|\.|\?|!|$))') def _do_smart_punctuation(self, text): """Fancifies 'single quotes', "double quotes", and apostrophes. Converts --, ---, and ... into en dashes, em dashes, and ellipses. Inspiration is: <http://daringfireball.net/projects/smartypants/> See "test/tm-cases/smarty_pants.text" for a full discussion of the support here and <http://code.google.com/p/python-markdown2/issues/detail?id=42> for a discussion of some diversion from the original SmartyPants. """ if "'" in text: # guard for perf text = self._do_smart_contractions(text) text = self._opening_single_quote_re.sub("&#8216;", text) text = self._closing_single_quote_re.sub("&#8217;", text) if '"' in text: # guard for perf text = self._opening_double_quote_re.sub("&#8220;", text) text = self._closing_double_quote_re.sub("&#8221;", text) text = text.replace("---", "&#8212;") text = text.replace("--", "&#8211;") text = text.replace("...", "&#8230;") text = text.replace(" . . . ", "&#8230;") text = text.replace(". . .", "&#8230;") return text _block_quote_re = re.compile(r''' ( # Wrap whole match in \1 ( ^[ \t]*>[ \t]? # '>' at the start of a line .+\n # rest of the first line (.+\n)* # subsequent consecutive lines \n* # blanks )+ ) ''', re.M | re.X) _bq_one_level_re = re.compile('^[ \t]*>[ \t]?', re.M); _html_pre_block_re = re.compile(r'(\s*<pre>.+?</pre>)', re.S) def _dedent_two_spaces_sub(self, match): return re.sub(r'(?m)^ ', '', match.group(1)) def _block_quote_sub(self, match): bq = match.group(1) bq = self._bq_one_level_re.sub('', bq) # trim one level of quoting bq = self._ws_only_line_re.sub('', bq) # trim whitespace-only lines bq = self._run_block_gamut(bq) # recurse bq = re.sub('(?m)^', ' ', bq) # These leading spaces screw with <pre> content, so we need to fix that: bq = self._html_pre_block_re.sub(self._dedent_two_spaces_sub, bq) return "<blockquote>\n%s\n</blockquote>\n\n" % bq def _do_block_quotes(self, text): if '>' not in text: return text return self._block_quote_re.sub(self._block_quote_sub, text) def _form_paragraphs(self, text): # Strip leading and trailing lines: text = text.strip('\n') # Wrap <p> tags. grafs = [] for i, graf in enumerate(re.split(r"\n{2,}", text)): if graf in self.html_blocks: # Unhashify HTML blocks grafs.append(self.html_blocks[graf]) else: cuddled_list = None if "cuddled-lists" in self.extras: # Need to put back trailing '\n' for `_list_item_re` # match at the end of the paragraph. li = self._list_item_re.search(graf + '\n') # Two of the same list marker in this paragraph: a likely # candidate for a list cuddled to preceding paragraph # text (issue 33). Note the `[-1]` is a quick way to # consider numeric bullets (e.g. "1." and "2.") to be # equal. if (li and len(li.group(2)) <= 3 and li.group("next_marker") and li.group("marker")[-1] == li.group("next_marker")[-1]): start = li.start() cuddled_list = self._do_lists(graf[start:]).rstrip("\n") assert cuddled_list.startswith("<ul>") or cuddled_list.startswith("<ol>") graf = graf[:start] # Wrap <p> tags. graf = self._run_span_gamut(graf) grafs.append("<p>" + graf.lstrip(" \t") + "</p>") if cuddled_list: grafs.append(cuddled_list) return "\n\n".join(grafs) def _add_footnotes(self, text): if self.footnotes: footer = [ '<div class="footnotes">', '<hr' + self.empty_element_suffix, '<ol>', ] for i, id in enumerate(self.footnote_ids): if i != 0: footer.append('') footer.append('<li id="fn-%s">' % id) footer.append(self._run_block_gamut(self.footnotes[id])) backlink = ('<a href="#fnref-%s" ' 'class="footnoteBackLink" ' 'title="Jump back to footnote %d in the text.">' '&#8617;</a>' % (id, i+1)) if footer[-1].endswith("</p>"): footer[-1] = footer[-1][:-len("</p>")] \ + '&nbsp;' + backlink + "</p>" else: footer.append("\n<p>%s</p>" % backlink) footer.append('</li>') footer.append('</ol>') footer.append('</div>') return text + '\n\n' + '\n'.join(footer) else: return text # Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin: # http://bumppo.net/projects/amputator/ _ampersand_re = re.compile(r'&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)') _naked_lt_re = re.compile(r'<(?![a-z/?\$!])', re.I) _naked_gt_re = re.compile(r'''(?<![a-z0-9?!/'"-])>''', re.I) def _encode_amps_and_angles(self, text): # Smart processing for ampersands and angle brackets that need # to be encoded. text = self._ampersand_re.sub('&amp;', text) # Encode naked <'s text = self._naked_lt_re.sub('&lt;', text) # Encode naked >'s # Note: Other markdown implementations (e.g. Markdown.pl, PHP # Markdown) don't do this. text = self._naked_gt_re.sub('&gt;', text) return text def _encode_backslash_escapes(self, text): for ch, escape in list(self._escape_table.items()): text = text.replace("\\"+ch, escape) return text _auto_link_re = re.compile(r'<((https?|ftp):[^\'">\s]+)>', re.I) def _auto_link_sub(self, match): g1 = match.group(1) return '<a href="%s">%s</a>' % (g1, g1) _auto_email_link_re = re.compile(r""" < (?:mailto:)? ( [-.\w]+ \@ [-\w]+(\.[-\w]+)*\.[a-z]+ ) > """, re.I | re.X | re.U) def _auto_email_link_sub(self, match): return self._encode_email_address( self._unescape_special_chars(match.group(1))) def _do_auto_links(self, text): text = self._auto_link_re.sub(self._auto_link_sub, text) text = self._auto_email_link_re.sub(self._auto_email_link_sub, text) return text def _encode_email_address(self, addr): # Input: an email address, e.g. "foo@example.com" # # Output: the email address as a mailto link, with each character # of the address encoded as either a decimal or hex entity, in # the hopes of foiling most address harvesting spam bots. E.g.: # # <a href="&#x6D;&#97;&#105;&#108;&#x74;&#111;:&#102;&#111;&#111;&#64;&#101; # x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;">&#102;&#111;&#111; # &#64;&#101;x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;</a> # # Based on a filter by Matthew Wickline, posted to the BBEdit-Talk # mailing list: <http://tinyurl.com/yu7ue> chars = [_xml_encode_email_char_at_random(ch) for ch in "mailto:" + addr] # Strip the mailto: from the visible part. addr = '<a href="%s">%s</a>' \ % (''.join(chars), ''.join(chars[7:])) return addr def _do_link_patterns(self, text): """Caveat emptor: there isn't much guarding against link patterns being formed inside other standard Markdown links, e.g. inside a [link def][like this]. Dev Notes: *Could* consider prefixing regexes with a negative lookbehind assertion to attempt to guard against this. """ link_from_hash = {} for regex, repl in self.link_patterns: replacements = [] for match in regex.finditer(text): if hasattr(repl, "__call__"): href = repl(match) else: href = match.expand(repl) replacements.append((match.span(), href)) for (start, end), href in reversed(replacements): escaped_href = ( href.replace('"', '&quot;') # b/c of attr quote # To avoid markdown <em> and <strong>: .replace('*', self._escape_table['*']) .replace('_', self._escape_table['_'])) link = '<a href="%s">%s</a>' % (escaped_href, text[start:end]) hash = _hash_text(link) link_from_hash[hash] = link text = text[:start] + hash + text[end:] for hash, link in list(link_from_hash.items()): text = text.replace(hash, link) return text def _unescape_special_chars(self, text): # Swap back in all the special characters we've hidden. for ch, hash in list(self._escape_table.items()): text = text.replace(hash, ch) return text def _outdent(self, text): # Remove one level of line-leading tabs or spaces return self._outdent_re.sub('', text) class MarkdownWithExtras(Markdown): """A markdowner class that enables most extras: - footnotes - code-color (only has effect if 'pygments' Python module on path) These are not included: - pyshell (specific to Python-related documenting) - code-friendly (because it *disables* part of the syntax) - link-patterns (because you need to specify some actual link-patterns anyway) """ extras = ["footnotes", "code-color"] #---- internal support functions class UnicodeWithAttrs(unicode): """A subclass of unicode used for the return value of conversion to possibly attach some attributes. E.g. the "toc_html" attribute when the "toc" extra is used. """ metadata = None _toc = None def toc_html(self): """Return the HTML for the current TOC. This expects the `_toc` attribute to have been set on this instance. """ if self._toc is None: return None def indent(): return ' ' * (len(h_stack) - 1) lines = [] h_stack = [0] # stack of header-level numbers for level, id, name in self._toc: if level > h_stack[-1]: lines.append("%s<ul>" % indent()) h_stack.append(level) elif level == h_stack[-1]: lines[-1] += "</li>" else: while level < h_stack[-1]: h_stack.pop() if not lines[-1].endswith("</li>"): lines[-1] += "</li>" lines.append("%s</ul></li>" % indent()) lines.append('%s<li><a href="#%s">%s</a>' % ( indent(), id, name)) while len(h_stack) > 1: h_stack.pop() if not lines[-1].endswith("</li>"): lines[-1] += "</li>" lines.append("%s</ul>" % indent()) return '\n'.join(lines) + '\n' toc_html = property(toc_html) ## {{{ http://code.activestate.com/recipes/577257/ (r1) import re char_map = {u'À': 'A', u'Á': 'A', u'Â': 'A', u'Ã': 'A', u'Ä': 'Ae', u'Å': 'A', u'Æ': 'A', u'Ā': 'A', u'Ą': 'A', u'Ă': 'A', u'Ç': 'C', u'Ć': 'C', u'Č': 'C', u'Ĉ': 'C', u'Ċ': 'C', u'Ď': 'D', u'Đ': 'D', u'È': 'E', u'É': 'E', u'Ê': 'E', u'Ë': 'E', u'Ē': 'E', u'Ę': 'E', u'Ě': 'E', u'Ĕ': 'E', u'Ė': 'E', u'Ĝ': 'G', u'Ğ': 'G', u'Ġ': 'G', u'Ģ': 'G', u'Ĥ': 'H', u'Ħ': 'H', u'Ì': 'I', u'Í': 'I', u'Î': 'I', u'Ï': 'I', u'Ī': 'I', u'Ĩ': 'I', u'Ĭ': 'I', u'Į': 'I', u'İ': 'I', u'IJ': 'IJ', u'Ĵ': 'J', u'Ķ': 'K', u'Ľ': 'K', u'Ĺ': 'K', u'Ļ': 'K', u'Ŀ': 'K', u'Ł': 'L', u'Ñ': 'N', u'Ń': 'N', u'Ň': 'N', u'Ņ': 'N', u'Ŋ': 'N', u'Ò': 'O', u'Ó': 'O', u'Ô': 'O', u'Õ': 'O', u'Ö': 'Oe', u'Ø': 'O', u'Ō': 'O', u'Ő': 'O', u'Ŏ': 'O', u'Œ': 'OE', u'Ŕ': 'R', u'Ř': 'R', u'Ŗ': 'R', u'Ś': 'S', u'Ş': 'S', u'Ŝ': 'S', u'Ș': 'S', u'Š': 'S', u'Ť': 'T', u'Ţ': 'T', u'Ŧ': 'T', u'Ț': 'T', u'Ù': 'U', u'Ú': 'U', u'Û': 'U', u'Ü': 'Ue', u'Ū': 'U', u'Ů': 'U', u'Ű': 'U', u'Ŭ': 'U', u'Ũ': 'U', u'Ų': 'U', u'Ŵ': 'W', u'Ŷ': 'Y', u'Ÿ': 'Y', u'Ý': 'Y', u'Ź': 'Z', u'Ż': 'Z', u'Ž': 'Z', u'à': 'a', u'á': 'a', u'â': 'a', u'ã': 'a', u'ä': 'ae', u'ā': 'a', u'ą': 'a', u'ă': 'a', u'å': 'a', u'æ': 'ae', u'ç': 'c', u'ć': 'c', u'č': 'c', u'ĉ': 'c', u'ċ': 'c', u'ď': 'd', u'đ': 'd', u'è': 'e', u'é': 'e', u'ê': 'e', u'ë': 'e', u'ē': 'e', u'ę': 'e', u'ě': 'e', u'ĕ': 'e', u'ė': 'e', u'ƒ': 'f', u'ĝ': 'g', u'ğ': 'g', u'ġ': 'g', u'ģ': 'g', u'ĥ': 'h', u'ħ': 'h', u'ì': 'i', u'í': 'i', u'î': 'i', u'ï': 'i', u'ī': 'i', u'ĩ': 'i', u'ĭ': 'i', u'į': 'i', u'ı': 'i', u'ij': 'ij', u'ĵ': 'j', u'ķ': 'k', u'ĸ': 'k', u'ł': 'l', u'ľ': 'l', u'ĺ': 'l', u'ļ': 'l', u'ŀ': 'l', u'ñ': 'n', u'ń': 'n', u'ň': 'n', u'ņ': 'n', u'ʼn': 'n', u'ŋ': 'n', u'ò': 'o', u'ó': 'o', u'ô': 'o', u'õ': 'o', u'ö': 'oe', u'ø': 'o', u'ō': 'o', u'ő': 'o', u'ŏ': 'o', u'œ': 'oe', u'ŕ': 'r', u'ř': 'r', u'ŗ': 'r', u'ś': 's', u'š': 's', u'ť': 't', u'ù': 'u', u'ú': 'u', u'û': 'u', u'ü': 'ue', u'ū': 'u', u'ů': 'u', u'ű': 'u', u'ŭ': 'u', u'ũ': 'u', u'ų': 'u', u'ŵ': 'w', u'ÿ': 'y', u'ý': 'y', u'ŷ': 'y', u'ż': 'z', u'ź': 'z', u'ž': 'z', u'ß': 'ss', u'ſ': 'ss', u'Α': 'A', u'Ά': 'A', u'Ἀ': 'A', u'Ἁ': 'A', u'Ἂ': 'A', u'Ἃ': 'A', u'Ἄ': 'A', u'Ἅ': 'A', u'Ἆ': 'A', u'Ἇ': 'A', u'ᾈ': 'A', u'ᾉ': 'A', u'ᾊ': 'A', u'ᾋ': 'A', u'ᾌ': 'A', u'ᾍ': 'A', u'ᾎ': 'A', u'ᾏ': 'A', u'Ᾰ': 'A', u'Ᾱ': 'A', u'Ὰ': 'A', u'Ά': 'A', u'ᾼ': 'A', u'Β': 'B', u'Γ': 'G', u'Δ': 'D', u'Ε': 'E', u'Έ': 'E', u'Ἐ': 'E', u'Ἑ': 'E', u'Ἒ': 'E', u'Ἓ': 'E', u'Ἔ': 'E', u'Ἕ': 'E', u'Έ': 'E', u'Ὲ': 'E', u'Ζ': 'Z', u'Η': 'I', u'Ή': 'I', u'Ἠ': 'I', u'Ἡ': 'I', u'Ἢ': 'I', u'Ἣ': 'I', u'Ἤ': 'I', u'Ἥ': 'I', u'Ἦ': 'I', u'Ἧ': 'I', u'ᾘ': 'I', u'ᾙ': 'I', u'ᾚ': 'I', u'ᾛ': 'I', u'ᾜ': 'I', u'ᾝ': 'I', u'ᾞ': 'I', u'ᾟ': 'I', u'Ὴ': 'I', u'Ή': 'I', u'ῌ': 'I', u'Θ': 'TH', u'Ι': 'I', u'Ί': 'I', u'Ϊ': 'I', u'Ἰ': 'I', u'Ἱ': 'I', u'Ἲ': 'I', u'Ἳ': 'I', u'Ἴ': 'I', u'Ἵ': 'I', u'Ἶ': 'I', u'Ἷ': 'I', u'Ῐ': 'I', u'Ῑ': 'I', u'Ὶ': 'I', u'Ί': 'I', u'Κ': 'K', u'Λ': 'L', u'Μ': 'M', u'Ν': 'N', u'Ξ': 'KS', u'Ο': 'O', u'Ό': 'O', u'Ὀ': 'O', u'Ὁ': 'O', u'Ὂ': 'O', u'Ὃ': 'O', u'Ὄ': 'O', u'Ὅ': 'O', u'Ὸ': 'O', u'Ό': 'O', u'Π': 'P', u'Ρ': 'R', u'Ῥ': 'R', u'Σ': 'S', u'Τ': 'T', u'Υ': 'Y', u'Ύ': 'Y', u'Ϋ': 'Y', u'Ὑ': 'Y', u'Ὓ': 'Y', u'Ὕ': 'Y', u'Ὗ': 'Y', u'Ῠ': 'Y', u'Ῡ': 'Y', u'Ὺ': 'Y', u'Ύ': 'Y', u'Φ': 'F', u'Χ': 'X', u'Ψ': 'PS', u'Ω': 'O', u'Ώ': 'O', u'Ὠ': 'O', u'Ὡ': 'O', u'Ὢ': 'O', u'Ὣ': 'O', u'Ὤ': 'O', u'Ὥ': 'O', u'Ὦ': 'O', u'Ὧ': 'O', u'ᾨ': 'O', u'ᾩ': 'O', u'ᾪ': 'O', u'ᾫ': 'O', u'ᾬ': 'O', u'ᾭ': 'O', u'ᾮ': 'O', u'ᾯ': 'O', u'Ὼ': 'O', u'Ώ': 'O', u'ῼ': 'O', u'α': 'a', u'ά': 'a', u'ἀ': 'a', u'ἁ': 'a', u'ἂ': 'a', u'ἃ': 'a', u'ἄ': 'a', u'ἅ': 'a', u'ἆ': 'a', u'ἇ': 'a', u'ᾀ': 'a', u'ᾁ': 'a', u'ᾂ': 'a', u'ᾃ': 'a', u'ᾄ': 'a', u'ᾅ': 'a', u'ᾆ': 'a', u'ᾇ': 'a', u'ὰ': 'a', u'ά': 'a', u'ᾰ': 'a', u'ᾱ': 'a', u'ᾲ': 'a', u'ᾳ': 'a', u'ᾴ': 'a', u'ᾶ': 'a', u'ᾷ': 'a', u'β': 'b', u'γ': 'g', u'δ': 'd', u'ε': 'e', u'έ': 'e', u'ἐ': 'e', u'ἑ': 'e', u'ἒ': 'e', u'ἓ': 'e', u'ἔ': 'e', u'ἕ': 'e', u'ὲ': 'e', u'έ': 'e', u'ζ': 'z', u'η': 'i', u'ή': 'i', u'ἠ': 'i', u'ἡ': 'i', u'ἢ': 'i', u'ἣ': 'i', u'ἤ': 'i', u'ἥ': 'i', u'ἦ': 'i', u'ἧ': 'i', u'ᾐ': 'i', u'ᾑ': 'i', u'ᾒ': 'i', u'ᾓ': 'i', u'ᾔ': 'i', u'ᾕ': 'i', u'ᾖ': 'i', u'ᾗ': 'i', u'ὴ': 'i', u'ή': 'i', u'ῂ': 'i', u'ῃ': 'i', u'ῄ': 'i', u'ῆ': 'i', u'ῇ': 'i', u'θ': 'th', u'ι': 'i', u'ί': 'i', u'ϊ': 'i', u'ΐ': 'i', u'ἰ': 'i', u'ἱ': 'i', u'ἲ': 'i', u'ἳ': 'i', u'ἴ': 'i', u'ἵ': 'i', u'ἶ': 'i', u'ἷ': 'i', u'ὶ': 'i', u'ί': 'i', u'ῐ': 'i', u'ῑ': 'i', u'ῒ': 'i', u'ΐ': 'i', u'ῖ': 'i', u'ῗ': 'i', u'κ': 'k', u'λ': 'l', u'μ': 'm', u'ν': 'n', u'ξ': 'ks', u'ο': 'o', u'ό': 'o', u'ὀ': 'o', u'ὁ': 'o', u'ὂ': 'o', u'ὃ': 'o', u'ὄ': 'o', u'ὅ': 'o', u'ὸ': 'o', u'ό': 'o', u'π': 'p', u'ρ': 'r', u'ῤ': 'r', u'ῥ': 'r', u'σ': 's', u'ς': 's', u'τ': 't', u'υ': 'y', u'ύ': 'y', u'ϋ': 'y', u'ΰ': 'y', u'ὐ': 'y', u'ὑ': 'y', u'ὒ': 'y', u'ὓ': 'y', u'ὔ': 'y', u'ὕ': 'y', u'ὖ': 'y', u'ὗ': 'y', u'ὺ': 'y', u'ύ': 'y', u'ῠ': 'y', u'ῡ': 'y', u'ῢ': 'y', u'ΰ': 'y', u'ῦ': 'y', u'ῧ': 'y', u'φ': 'f', u'χ': 'x', u'ψ': 'ps', u'ω': 'o', u'ώ': 'o', u'ὠ': 'o', u'ὡ': 'o', u'ὢ': 'o', u'ὣ': 'o', u'ὤ': 'o', u'ὥ': 'o', u'ὦ': 'o', u'ὧ': 'o', u'ᾠ': 'o', u'ᾡ': 'o', u'ᾢ': 'o', u'ᾣ': 'o', u'ᾤ': 'o', u'ᾥ': 'o', u'ᾦ': 'o', u'ᾧ': 'o', u'ὼ': 'o', u'ώ': 'o', u'ῲ': 'o', u'ῳ': 'o', u'ῴ': 'o', u'ῶ': 'o', u'ῷ': 'o', u'¨': '', u'΅': '', u'᾿': '', u'῾': '', u'῍': '', u'῝': '', u'῎': '', u'῞': '', u'῏': '', u'῟': '', u'῀': '', u'῁': '', u'΄': '', u'΅': '', u'`': '', u'῭': '', u'ͺ': '', u'᾽': '', u'А': 'A', u'Б': 'B', u'В': 'V', u'Г': 'G', u'Д': 'D', u'Е': 'E', u'Ё': 'YO', u'Ж': 'ZH', u'З': 'Z', u'И': 'I', u'Й': 'J', u'К': 'K', u'Л': 'L', u'М': 'M', u'Н': 'N', u'О': 'O', u'П': 'P', u'Р': 'R', u'С': 'S', u'Т': 'T', u'У': 'U', u'Ф': 'F', u'Х': 'H', u'Ц': 'TS', u'Ч': 'CH', u'Ш': 'SH', u'Щ': 'SCH', u'Ы': 'YI', u'Э': 'E', u'Ю': 'YU', u'Я': 'YA', u'а': 'A', u'б': 'B', u'в': 'V', u'г': 'G', u'д': 'D', u'е': 'E', u'ё': 'YO', u'ж': 'ZH', u'з': 'Z', u'и': 'I', u'й': 'J', u'к': 'K', u'л': 'L', u'м': 'M', u'н': 'N', u'о': 'O', u'п': 'P', u'р': 'R', u'с': 'S', u'т': 'T', u'у': 'U', u'ф': 'F', u'х': 'H', u'ц': 'TS', u'ч': 'CH', u'ш': 'SH', u'щ': 'SCH', u'ы': 'YI', u'э': 'E', u'ю': 'YU', u'я': 'YA', u'Ъ': '', u'ъ': '', u'Ь': '', u'ь': '', u'ð': 'd', u'Ð': 'D', u'þ': 'th', u'Þ': 'TH',u'ა': 'a', u'ბ': 'b', u'გ': 'g', u'დ': 'd', u'ე': 'e', u'ვ': 'v', u'ზ': 'z', u'თ': 't', u'ი': 'i', u'კ': 'k', u'ლ': 'l', u'მ': 'm', u'ნ': 'n', u'ო': 'o', u'პ': 'p', u'ჟ': 'zh', u'რ': 'r', u'ს': 's', u'ტ': 't', u'უ': 'u', u'ფ': 'p', u'ქ': 'k', u'ღ': 'gh', u'ყ': 'q', u'შ': 'sh', u'ჩ': 'ch', u'ც': 'ts', u'ძ': 'dz', u'წ': 'ts', u'ჭ': 'ch', u'ხ': 'kh', u'ჯ': 'j', u'ჰ': 'h' } def replace_char(m): char = m.group() if char_map.has_key(char): return char_map[char] else: return char _punct_re = re.compile(r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.]+') def _slugify(text, delim=u'-'): """Generates an ASCII-only slug.""" result = [] for word in _punct_re.split(text.lower()): word = word.encode('utf-8') if word: result.append(word) slugified = delim.join([i.decode('utf-8') for i in result]) return re.sub('[^a-zA-Z0-9\\s\\-]{1}', replace_char, slugified).lower() ## end of http://code.activestate.com/recipes/577257/ }}} # From http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52549 def _curry(*args, **kwargs): function, args = args[0], args[1:] def result(*rest, **kwrest): combined = kwargs.copy() combined.update(kwrest) return function(*args + rest, **combined) return result # Recipe: regex_from_encoded_pattern (1.0) def _regex_from_encoded_pattern(s): """'foo' -> re.compile(re.escape('foo')) '/foo/' -> re.compile('foo') '/foo/i' -> re.compile('foo', re.I) """ if s.startswith('/') and s.rfind('/') != 0: # Parse it: /PATTERN/FLAGS idx = s.rfind('/') pattern, flags_str = s[1:idx], s[idx+1:] flag_from_char = { "i": re.IGNORECASE, "l": re.LOCALE, "s": re.DOTALL, "m": re.MULTILINE, "u": re.UNICODE, } flags = 0 for char in flags_str: try: flags |= flag_from_char[char] except KeyError: raise ValueError("unsupported regex flag: '%s' in '%s' " "(must be one of '%s')" % (char, s, ''.join(list(flag_from_char.keys())))) return re.compile(s[1:idx], flags) else: # not an encoded regex return re.compile(re.escape(s)) # Recipe: dedent (0.1.2) def _dedent(text, tabsize=8, skip_first_line=False): """_dedent(text, tabsize=8, skip_first_line=False) -> dedented text "text" is the text to dedent. "tabsize" is the tab width to use for indent width calculations. "skip_first_line" is a boolean indicating if the first line should be skipped for calculating the indent width and for dedenting. This is sometimes useful for docstrings and similar. textwrap.dedent(s), but don't expand tabs to spaces """ lines = text.splitlines(1) _dedentlines(lines, tabsize=tabsize, skip_first_line=skip_first_line) return ''.join(lines) class _memoized(object): """Decorator that caches a function's return value each time it is called. If called later with the same arguments, the cached value is returned, and not re-evaluated. http://wiki.python.org/moin/PythonDecoratorLibrary """ def __init__(self, func): self.func = func self.cache = {} def __call__(self, *args): try: return self.cache[args] except KeyError: self.cache[args] = value = self.func(*args) return value except TypeError: # uncachable -- for instance, passing a list as an argument. # Better to not cache than to blow up entirely. return self.func(*args) def __repr__(self): """Return the function's docstring.""" return self.func.__doc__ def _xml_oneliner_re_from_tab_width(tab_width): """Standalone XML processing instruction regex.""" return re.compile(r""" (?: (?<=\n\n) # Starting after a blank line | # or \A\n? # the beginning of the doc ) ( # save in $1 [ ]{0,%d} (?: <\?\w+\b\s+.*?\?> # XML processing instruction | <\w+:\w+\b\s+.*?/> # namespaced single tag ) [ \t]* (?=\n{2,}|\Z) # followed by a blank line or end of document ) """ % (tab_width - 1), re.X) _xml_oneliner_re_from_tab_width = _memoized(_xml_oneliner_re_from_tab_width) def _hr_tag_re_from_tab_width(tab_width): return re.compile(r""" (?: (?<=\n\n) # Starting after a blank line | # or \A\n? # the beginning of the doc ) ( # save in \1 [ ]{0,%d} <(hr) # start tag = \2 \b # word break ([^<>])*? # /?> # the matching end tag [ \t]* (?=\n{2,}|\Z) # followed by a blank line or end of document ) """ % (tab_width - 1), re.X) _hr_tag_re_from_tab_width = _memoized(_hr_tag_re_from_tab_width) def _xml_escape_attr(attr, skip_single_quote=True): """Escape the given string for use in an HTML/XML tag attribute. By default this doesn't bother with escaping `'` to `&#39;`, presuming that the tag attribute is surrounded by double quotes. """ escaped = (attr .replace('&', '&amp;') .replace('"', '&quot;') .replace('<', '&lt;') .replace('>', '&gt;')) if not skip_single_quote: escaped = escaped.replace("'", "&#39;") return escaped def _xml_encode_email_char_at_random(ch): r = random() # Roughly 10% raw, 45% hex, 45% dec. # '@' *must* be encoded. I [John Gruber] insist. # Issue 26: '_' must be encoded. if r > 0.9 and ch not in "@_": return ch elif r < 0.45: # The [1:] is to drop leading '0': 0x63 -> x63 return '&#%s;' % hex(ord(ch))[1:] else: return '&#%s;' % ord(ch) #---- mainline class _NoReflowFormatter(optparse.IndentedHelpFormatter): """An optparse formatter that does NOT reflow the description.""" def format_description(self, description): return description or "" def _test(): import doctest doctest.testmod() def main(argv=None): if argv is None: argv = sys.argv if not logging.root.handlers: logging.basicConfig() usage = "usage: %prog [PATHS...]" version = "%prog "+__version__ parser = optparse.OptionParser(prog="markdown2", usage=usage, version=version, description=cmdln_desc, formatter=_NoReflowFormatter()) parser.add_option("-v", "--verbose", dest="log_level", action="store_const", const=logging.DEBUG, help="more verbose output") parser.add_option("--encoding", help="specify encoding of text content") parser.add_option("--html4tags", action="store_true", default=False, help="use HTML 4 style for empty element tags") parser.add_option("-s", "--safe", metavar="MODE", dest="safe_mode", help="sanitize literal HTML: 'escape' escapes " "HTML meta chars, 'replace' replaces with an " "[HTML_REMOVED] note") parser.add_option("-x", "--extras", action="append", help="Turn on specific extra features (not part of " "the core Markdown spec). See above.") parser.add_option("--use-file-vars", help="Look for and use Emacs-style 'markdown-extras' " "file var to turn on extras. See " "<https://github.com/trentm/python-markdown2/wiki/Extras>") parser.add_option("--link-patterns-file", help="path to a link pattern file") parser.add_option("--self-test", action="store_true", help="run internal self-tests (some doctests)") parser.add_option("--compare", action="store_true", help="run against Markdown.pl as well (for testing)") parser.set_defaults(log_level=logging.INFO, compare=False, encoding="utf-8", safe_mode=None, use_file_vars=False) opts, paths = parser.parse_args() log.setLevel(opts.log_level) if opts.self_test: return _test() if opts.extras: extras = {} for s in opts.extras: splitter = re.compile("[,;: ]+") for e in splitter.split(s): if '=' in e: ename, earg = e.split('=', 1) try: earg = int(earg) except ValueError: pass else: ename, earg = e, None extras[ename] = earg else: extras = None if opts.link_patterns_file: link_patterns = [] f = open(opts.link_patterns_file) try: for i, line in enumerate(f.readlines()): if not line.strip(): continue if line.lstrip().startswith("#"): continue try: pat, href = line.rstrip().rsplit(None, 1) except ValueError: raise MarkdownError("%s:%d: invalid link pattern line: %r" % (opts.link_patterns_file, i+1, line)) link_patterns.append( (_regex_from_encoded_pattern(pat), href)) finally: f.close() else: link_patterns = None from os.path import join, dirname, abspath, exists markdown_pl = join(dirname(dirname(abspath(__file__))), "test", "Markdown.pl") if not paths: paths = ['-'] for path in paths: if path == '-': text = sys.stdin.read() else: fp = codecs.open(path, 'r', opts.encoding) text = fp.read() fp.close() if opts.compare: from subprocess import Popen, PIPE print("==== Markdown.pl ====") p = Popen('perl %s' % markdown_pl, shell=True, stdin=PIPE, stdout=PIPE, close_fds=True) p.stdin.write(text.encode('utf-8')) p.stdin.close() perl_html = p.stdout.read().decode('utf-8') if py3: sys.stdout.write(perl_html) else: sys.stdout.write(perl_html.encode( sys.stdout.encoding or "utf-8", 'xmlcharrefreplace')) print("==== markdown2.py ====") html = markdown(text, html4tags=opts.html4tags, safe_mode=opts.safe_mode, extras=extras, link_patterns=link_patterns, use_file_vars=opts.use_file_vars) if py3: sys.stdout.write(html) else: sys.stdout.write(html.encode( sys.stdout.encoding or "utf-8", 'xmlcharrefreplace')) if extras and "toc" in extras: log.debug("toc_html: " + html.toc_html.encode(sys.stdout.encoding or "utf-8", 'xmlcharrefreplace')) if opts.compare: test_dir = join(dirname(dirname(abspath(__file__))), "test") if exists(join(test_dir, "test_markdown2.py")): sys.path.insert(0, test_dir) from test_markdown2 import norm_html_from_html norm_html = norm_html_from_html(html) norm_perl_html = norm_html_from_html(perl_html) else: norm_html = html norm_perl_html = perl_html print("==== match? %r ====" % (norm_perl_html == norm_html)) template_html = u'''<!DOCTYPE html> <!-- Backdoc is a tool for backbone-like documentation generation. Backdoc main goal is to help to generate one page documentation from one markdown source file. https://github.com/chibisov/backdoc --> <html lang="ru"> <head> <meta charset="UTF-8"/> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> <meta name="HandheldFriendly" content="true" /> <title><!-- title --></title> <!-- Bootstrap --> <style type="text/css"> /*! * Bootstrap v3.0.0 * * Copyright 2013 Twitter, Inc * Licensed under the Apache License v2.0 * http://www.apache.org/licenses/LICENSE-2.0 * * Designed and built with all the love in the world by @mdo and @fat. *//*! normalize.css v2.1.0 | MIT License | git.io/normalize */ article,aside,details,figcaption,figure,footer,header,hgroup,main,nav,section,summary{display:block}audio,canvas,video{display:inline-block}audio:not([controls]){display:none;height:0}[hidden]{display:none}html{font-family:sans-serif;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%}body{margin:0}a:focus{outline:thin dotted}a:active,a:hover{outline:0}h1{margin:.67em 0;font-size:2em}abbr[title]{border-bottom:1px dotted}b,strong{font-weight:bold}dfn{font-style:italic}hr{height:0;-moz-box-sizing:content-box;box-sizing:content-box}mark{color:#000;background:#ff0}code,kbd,pre,samp{font-family:monospace,serif;font-size:1em}pre{white-space:pre-wrap}q{quotes:"\201C" "\201D" "\2018" "\2019"}small{font-size:80%}sub,sup{position:relative;font-size:75%;line-height:0;vertical-align:baseline}sup{top:-0.5em}sub{bottom:-0.25em}img{border:0}svg:not(:root){overflow:hidden}figure{margin:0}fieldset{padding:.35em .625em .75em;margin:0 2px;border:1px solid #c0c0c0}legend{padding:0;border:0}button,input,select,textarea{margin:0;font-family:inherit;font-size:100%}button,input{line-height:normal}button,select{text-transform:none}button,html input[type="button"],input[type="reset"],input[type="submit"]{cursor:pointer;-webkit-appearance:button}button[disabled],html input[disabled]{cursor:default}input[type="checkbox"],input[type="radio"]{padding:0;box-sizing:border-box}input[type="search"]{-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;-webkit-appearance:textfield}input[type="search"]::-webkit-search-cancel-button,input[type="search"]::-webkit-search-decoration{-webkit-appearance:none}button::-moz-focus-inner,input::-moz-focus-inner{padding:0;border:0}textarea{overflow:auto;vertical-align:top}table{border-collapse:collapse;border-spacing:0}@media print{*{color:#000!important;text-shadow:none!important;background:transparent!important;box-shadow:none!important}a,a:visited{text-decoration:underline}a[href]:after{content:" (" attr(href) ")"}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100%!important}@page{margin:2cm .5cm}p,h2,h3{orphans:3;widows:3}h2,h3{page-break-after:avoid}.navbar{display:none}.table td,.table th{background-color:#fff!important}.btn>.caret,.dropup>.btn>.caret{border-top-color:#000!important}.label{border:1px solid #000}.table{border-collapse:collapse!important}.table-bordered th,.table-bordered td{border:1px solid #ddd!important}}*{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}html{font-size:62.5%;-webkit-tap-highlight-color:rgba(0,0,0,0)}body{font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px;line-height:1.428571429;color:#333;background-color:#fff}input,button,select,textarea{font-family:inherit;font-size:inherit;line-height:inherit}a{color:#428bca;text-decoration:none}a:hover,a:focus{color:#2a6496;text-decoration:underline}a:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}img{vertical-align:middle}.img-responsive{display:inline-block;height:auto;max-width:100%}.img-rounded{border-radius:6px}.img-circle{border-radius:500px}hr{margin-top:20px;margin-bottom:20px;border:0;border-top:1px solid #eee}p{margin:0 0 10px}.lead{margin-bottom:20px;font-size:16.099999999999998px;font-weight:200;line-height:1.4}@media(min-width:768px){.lead{font-size:21px}}small{font-size:85%}cite{font-style:normal}.text-muted{color:#999}.text-primary{color:#428bca}.text-warning{color:#c09853}.text-danger{color:#b94a48}.text-success{color:#468847}.text-info{color:#3a87ad}.text-left{text-align:left}.text-right{text-align:right}.text-center{text-align:center}h1,h2,h3,h4,h5,h6,.h1,.h2,.h3,.h4,.h5,.h6{font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-weight:500;line-height:1.1}h1 small,h2 small,h3 small,h4 small,h5 small,h6 small,.h1 small,.h2 small,.h3 small,.h4 small,.h5 small,.h6 small{font-weight:normal;line-height:1;color:#999}h1,h2,h3{margin-top:20px;margin-bottom:10px}h4,h5,h6{margin-top:10px;margin-bottom:10px}h1,.h1{font-size:38px}h2,.h2{font-size:32px}h3,.h3{font-size:24px}h4,.h4{font-size:18px}h5,.h5{font-size:14px}h6,.h6{font-size:12px}h1 small,.h1 small{font-size:24px}h2 small,.h2 small{font-size:18px}h3 small,.h3 small,h4 small,.h4 small{font-size:14px}.page-header{padding-bottom:9px;margin:40px 0 20px;border-bottom:1px solid #eee}ul,ol{margin-top:0;margin-bottom:10px}ul ul,ol ul,ul ol,ol ol{margin-bottom:0}.list-unstyled{padding-left:0;list-style:none}.list-inline{padding-left:0;list-style:none}.list-inline>li{display:inline-block;padding-right:5px;padding-left:5px}dl{margin-bottom:20px}dt,dd{line-height:1.428571429}dt{font-weight:bold}dd{margin-left:0}.dl-horizontal dt{float:left;width:160px;overflow:hidden;clear:left;text-align:right;text-overflow:ellipsis;white-space:nowrap}.dl-horizontal dd{margin-left:180px}.dl-horizontal dd:before,.dl-horizontal dd:after{display:table;content:" "}.dl-horizontal dd:after{clear:both}.dl-horizontal dd:before,.dl-horizontal dd:after{display:table;content:" "}.dl-horizontal dd:after{clear:both}abbr[title],abbr[data-original-title]{cursor:help;border-bottom:1px dotted #999}abbr.initialism{font-size:90%;text-transform:uppercase}blockquote{padding:10px 20px;margin:0 0 20px;border-left:5px solid #eee}blockquote p{font-size:17.5px;font-weight:300;line-height:1.25}blockquote p:last-child{margin-bottom:0}blockquote small{display:block;line-height:1.428571429;color:#999}blockquote small:before{content:'\2014 \00A0'}blockquote.pull-right{float:right;padding-right:15px;padding-left:0;border-right:5px solid #eee;border-left:0}blockquote.pull-right p,blockquote.pull-right small{text-align:right}blockquote.pull-right small:before{content:''}blockquote.pull-right small:after{content:'\00A0 \2014'}q:before,q:after,blockquote:before,blockquote:after{content:""}address{display:block;margin-bottom:20px;font-style:normal;line-height:1.428571429}code,pre{font-family:Monaco,Menlo,Consolas,"Courier New",monospace}code{padding:2px 4px;font-size:90%;color:#c7254e;white-space:nowrap;background-color:#f9f2f4;border-radius:4px}pre{display:block;padding:9.5px;margin:0 0 10px;font-size:13px;line-height:1.428571429;color:#333;word-break:break-all;word-wrap:break-word;background-color:#f5f5f5;border:1px solid #ccc;border-radius:4px}pre.prettyprint{margin-bottom:20px}pre code{padding:0;color:inherit;white-space:pre-wrap;background-color:transparent;border:0}.pre-scrollable{max-height:340px;overflow-y:scroll}.container{margin-right:auto;margin-left:auto}.container:before,.container:after{display:table;content:" "}.container:after{clear:both}.container:before,.container:after{display:table;content:" "}.container:after{clear:both}.row:before,.row:after{display:table;content:" "}.row:after{clear:both}.row:before,.row:after{display:table;content:" "}.row:after{clear:both}@media(min-width:768px){.row{margin-right:-15px;margin-left:-15px}}.row .row{margin-right:-15px;margin-left:-15px}.col-1,.col-2,.col-3,.col-4,.col-5,.col-6,.col-7,.col-8,.col-9,.col-10,.col-11,.col-12,.col-sm-1,.col-sm-2,.col-sm-3,.col-sm-4,.col-sm-5,.col-sm-6,.col-sm-7,.col-sm-8,.col-sm-9,.col-sm-10,.col-sm-11,.col-sm-12,.col-lg-1,.col-lg-2,.col-lg-3,.col-lg-4,.col-lg-5,.col-lg-6,.col-lg-7,.col-lg-8,.col-lg-9,.col-lg-10,.col-lg-11,.col-lg-12{position:relative;min-height:1px;padding-right:15px;padding-left:15px}.col-1,.col-2,.col-3,.col-4,.col-5,.col-6,.col-7,.col-8,.col-9,.col-10,.col-11,.col-12{float:left}.col-1{width:8.333333333333332%}.col-2{width:16.666666666666664%}.col-3{width:25%}.col-4{width:33.33333333333333%}.col-5{width:41.66666666666667%}.col-6{width:50%}.col-7{width:58.333333333333336%}.col-8{width:66.66666666666666%}.col-9{width:75%}.col-10{width:83.33333333333334%}.col-11{width:91.66666666666666%}.col-12{width:100%}@media(min-width:768px){.container{max-width:728px}.col-sm-1,.col-sm-2,.col-sm-3,.col-sm-4,.col-sm-5,.col-sm-6,.col-sm-7,.col-sm-8,.col-sm-9,.col-sm-10,.col-sm-11,.col-sm-12{float:left}.col-sm-1{width:8.333333333333332%}.col-sm-2{width:16.666666666666664%}.col-sm-3{width:25%}.col-sm-4{width:33.33333333333333%}.col-sm-5{width:41.66666666666667%}.col-sm-6{width:50%}.col-sm-7{width:58.333333333333336%}.col-sm-8{width:66.66666666666666%}.col-sm-9{width:75%}.col-sm-10{width:83.33333333333334%}.col-sm-11{width:91.66666666666666%}.col-sm-12{width:100%}.col-push-1{left:8.333333333333332%}.col-push-2{left:16.666666666666664%}.col-push-3{left:25%}.col-push-4{left:33.33333333333333%}.col-push-5{left:41.66666666666667%}.col-push-6{left:50%}.col-push-7{left:58.333333333333336%}.col-push-8{left:66.66666666666666%}.col-push-9{left:75%}.col-push-10{left:83.33333333333334%}.col-push-11{left:91.66666666666666%}.col-pull-1{right:8.333333333333332%}.col-pull-2{right:16.666666666666664%}.col-pull-3{right:25%}.col-pull-4{right:33.33333333333333%}.col-pull-5{right:41.66666666666667%}.col-pull-6{right:50%}.col-pull-7{right:58.333333333333336%}.col-pull-8{right:66.66666666666666%}.col-pull-9{right:75%}.col-pull-10{right:83.33333333333334%}.col-pull-11{right:91.66666666666666%}}@media(min-width:992px){.container{max-width:940px}.col-lg-1,.col-lg-2,.col-lg-3,.col-lg-4,.col-lg-5,.col-lg-6,.col-lg-7,.col-lg-8,.col-lg-9,.col-lg-10,.col-lg-11,.col-lg-12{float:left}.col-lg-1{width:8.333333333333332%}.col-lg-2{width:16.666666666666664%}.col-lg-3{width:25%}.col-lg-4{width:33.33333333333333%}.col-lg-5{width:41.66666666666667%}.col-lg-6{width:50%}.col-lg-7{width:58.333333333333336%}.col-lg-8{width:66.66666666666666%}.col-lg-9{width:75%}.col-lg-10{width:83.33333333333334%}.col-lg-11{width:91.66666666666666%}.col-lg-12{width:100%}.col-offset-1{margin-left:8.333333333333332%}.col-offset-2{margin-left:16.666666666666664%}.col-offset-3{margin-left:25%}.col-offset-4{margin-left:33.33333333333333%}.col-offset-5{margin-left:41.66666666666667%}.col-offset-6{margin-left:50%}.col-offset-7{margin-left:58.333333333333336%}.col-offset-8{margin-left:66.66666666666666%}.col-offset-9{margin-left:75%}.col-offset-10{margin-left:83.33333333333334%}.col-offset-11{margin-left:91.66666666666666%}}@media(min-width:1200px){.container{max-width:1170px}}table{max-width:100%;background-color:transparent}th{text-align:left}.table{width:100%;margin-bottom:20px}.table thead>tr>th,.table tbody>tr>th,.table tfoot>tr>th,.table thead>tr>td,.table tbody>tr>td,.table tfoot>tr>td{padding:8px;line-height:1.428571429;vertical-align:top;border-top:1px solid #ddd}.table thead>tr>th{vertical-align:bottom}.table caption+thead tr:first-child th,.table colgroup+thead tr:first-child th,.table thead:first-child tr:first-child th,.table caption+thead tr:first-child td,.table colgroup+thead tr:first-child td,.table thead:first-child tr:first-child td{border-top:0}.table tbody+tbody{border-top:2px solid #ddd}.table .table{background-color:#fff}.table-condensed thead>tr>th,.table-condensed tbody>tr>th,.table-condensed tfoot>tr>th,.table-condensed thead>tr>td,.table-condensed tbody>tr>td,.table-condensed tfoot>tr>td{padding:5px}.table-bordered{border:1px solid #ddd}.table-bordered>thead>tr>th,.table-bordered>tbody>tr>th,.table-bordered>tfoot>tr>th,.table-bordered>thead>tr>td,.table-bordered>tbody>tr>td,.table-bordered>tfoot>tr>td{border:1px solid #ddd}.table-striped>tbody>tr:nth-child(odd)>td,.table-striped>tbody>tr:nth-child(odd)>th{background-color:#f9f9f9}.table-hover>tbody>tr:hover>td,.table-hover>tbody>tr:hover>th{background-color:#f5f5f5}table col[class^="col-"]{display:table-column;float:none}table td[class^="col-"],table th[class^="col-"]{display:table-cell;float:none}.table>thead>tr>td.active,.table>tbody>tr>td.active,.table>tfoot>tr>td.active,.table>thead>tr>th.active,.table>tbody>tr>th.active,.table>tfoot>tr>th.active,.table>thead>tr.active>td,.table>tbody>tr.active>td,.table>tfoot>tr.active>td,.table>thead>tr.active>th,.table>tbody>tr.active>th,.table>tfoot>tr.active>th{background-color:#f5f5f5}.table>thead>tr>td.success,.table>tbody>tr>td.success,.table>tfoot>tr>td.success,.table>thead>tr>th.success,.table>tbody>tr>th.success,.table>tfoot>tr>th.success,.table>thead>tr.success>td,.table>tbody>tr.success>td,.table>tfoot>tr.success>td,.table>thead>tr.success>th,.table>tbody>tr.success>th,.table>tfoot>tr.success>th{background-color:#dff0d8;border-color:#d6e9c6}.table>thead>tr>td.danger,.table>tbody>tr>td.danger,.table>tfoot>tr>td.danger,.table>thead>tr>th.danger,.table>tbody>tr>th.danger,.table>tfoot>tr>th.danger,.table>thead>tr.danger>td,.table>tbody>tr.danger>td,.table>tfoot>tr.danger>td,.table>thead>tr.danger>th,.table>tbody>tr.danger>th,.table>tfoot>tr.danger>th{background-color:#f2dede;border-color:#eed3d7}.table>thead>tr>td.warning,.table>tbody>tr>td.warning,.table>tfoot>tr>td.warning,.table>thead>tr>th.warning,.table>tbody>tr>th.warning,.table>tfoot>tr>th.warning,.table>thead>tr.warning>td,.table>tbody>tr.warning>td,.table>tfoot>tr.warning>td,.table>thead>tr.warning>th,.table>tbody>tr.warning>th,.table>tfoot>tr.warning>th{background-color:#fcf8e3;border-color:#fbeed5}.table-hover>tbody>tr>td.success:hover,.table-hover>tbody>tr>th.success:hover,.table-hover>tbody>tr.success:hover>td{background-color:#d0e9c6;border-color:#c9e2b3}.table-hover>tbody>tr>td.danger:hover,.table-hover>tbody>tr>th.danger:hover,.table-hover>tbody>tr.danger:hover>td{background-color:#ebcccc;border-color:#e6c1c7}.table-hover>tbody>tr>td.warning:hover,.table-hover>tbody>tr>th.warning:hover,.table-hover>tbody>tr.warning:hover>td{background-color:#faf2cc;border-color:#f8e5be}fieldset{padding:0;margin:0;border:0}legend{display:block;width:100%;padding:0;margin-bottom:20px;font-size:21px;line-height:inherit;color:#333;border:0;border-bottom:1px solid #e5e5e5}label{display:inline-block;margin-bottom:5px;font-weight:bold}input[type="search"]{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}input[type="radio"],input[type="checkbox"]{margin:4px 0 0;margin-top:1px \9;line-height:normal}input[type="file"]{display:block}select[multiple],select[size]{height:auto}select optgroup{font-family:inherit;font-size:inherit;font-style:inherit}input[type="file"]:focus,input[type="radio"]:focus,input[type="checkbox"]:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}input[type="number"]::-webkit-outer-spin-button,input[type="number"]::-webkit-inner-spin-button{height:auto}.form-control:-moz-placeholder{color:#999}.form-control::-moz-placeholder{color:#999}.form-control:-ms-input-placeholder{color:#999}.form-control::-webkit-input-placeholder{color:#999}.form-control{display:block;width:100%;height:38px;padding:8px 12px;font-size:14px;line-height:1.428571429;color:#555;vertical-align:middle;background-color:#fff;border:1px solid #ccc;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);-webkit-transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s;transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s}.form-control:focus{border-color:rgba(82,168,236,0.8);outline:0;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6)}.form-control[disabled],.form-control[readonly],fieldset[disabled] .form-control{cursor:not-allowed;background-color:#eee}textarea.form-control{height:auto}.form-group{margin-bottom:15px}.radio,.checkbox{display:block;min-height:20px;padding-left:20px;margin-top:10px;margin-bottom:10px;vertical-align:middle}.radio label,.checkbox label{display:inline;margin-bottom:0;font-weight:normal;cursor:pointer}.radio input[type="radio"],.radio-inline input[type="radio"],.checkbox input[type="checkbox"],.checkbox-inline input[type="checkbox"]{float:left;margin-left:-20px}.radio+.radio,.checkbox+.checkbox{margin-top:-5px}.radio-inline,.checkbox-inline{display:inline-block;padding-left:20px;margin-bottom:0;font-weight:normal;vertical-align:middle;cursor:pointer}.radio-inline+.radio-inline,.checkbox-inline+.checkbox-inline{margin-top:0;margin-left:10px}.form-control.input-large{height:56px;padding:14px 16px;font-size:18px;border-radius:6px}.form-control.input-small{height:30px;padding:5px 10px;font-size:12px;border-radius:3px}select.input-large{height:56px;line-height:56px}select.input-small{height:30px;line-height:30px}.has-warning .help-block,.has-warning .control-label{color:#c09853}.has-warning .form-control{padding-right:32px;border-color:#c09853;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075)}.has-warning .form-control:focus{border-color:#a47e3c;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #dbc59e;box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #dbc59e}.has-warning .input-group-addon{color:#c09853;background-color:#fcf8e3;border-color:#c09853}.has-error .help-block,.has-error .control-label{color:#b94a48}.has-error .form-control{padding-right:32px;border-color:#b94a48;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075)}.has-error .form-control:focus{border-color:#953b39;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #d59392;box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #d59392}.has-error .input-group-addon{color:#b94a48;background-color:#f2dede;border-color:#b94a48}.has-success .help-block,.has-success .control-label{color:#468847}.has-success .form-control{padding-right:32px;border-color:#468847;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075)}.has-success .form-control:focus{border-color:#356635;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7aba7b;box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7aba7b}.has-success .input-group-addon{color:#468847;background-color:#dff0d8;border-color:#468847}.help-block{display:block;margin-top:5px;margin-bottom:10px;color:#737373}.input-group{display:table;border-collapse:separate}.input-group.col{float:none;padding-right:0;padding-left:0}.input-group .form-control{width:100%;margin-bottom:0}.input-group-addon,.input-group-btn,.input-group .form-control{display:table-cell}.input-group-addon:not(:first-child):not(:last-child),.input-group-btn:not(:first-child):not(:last-child),.input-group .form-control:not(:first-child):not(:last-child){border-radius:0}.input-group-addon,.input-group-btn{width:1%;white-space:nowrap;vertical-align:middle}.input-group-addon{padding:8px 12px;font-size:14px;font-weight:normal;line-height:1.428571429;text-align:center;background-color:#eee;border:1px solid #ccc;border-radius:4px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.input-group-addon.input-small{padding:5px 10px;font-size:12px;border-radius:3px}.input-group-addon.input-large{padding:14px 16px;font-size:18px;border-radius:6px}.input-group .form-control:first-child,.input-group-addon:first-child,.input-group-btn:first-child>.btn,.input-group-btn:first-child>.dropdown-toggle,.input-group-btn:last-child>.btn:not(:last-child):not(.dropdown-toggle){border-top-right-radius:0;border-bottom-right-radius:0}.input-group-addon:first-child{border-right:0}.input-group .form-control:last-child,.input-group-addon:last-child,.input-group-btn:last-child>.btn,.input-group-btn:last-child>.dropdown-toggle,.input-group-btn:first-child>.btn:not(:first-child){border-bottom-left-radius:0;border-top-left-radius:0}.input-group-addon:last-child{border-left:0}.input-group-btn{position:relative;white-space:nowrap}.input-group-btn>.btn{position:relative}.input-group-btn>.btn+.btn{margin-left:-4px}.input-group-btn>.btn:hover,.input-group-btn>.btn:active{z-index:2}.form-inline .form-control,.form-inline .radio,.form-inline .checkbox{display:inline-block}.form-inline .radio,.form-inline .checkbox{margin-top:0;margin-bottom:0}.form-horizontal .control-label{padding-top:6px}.form-horizontal .form-group:before,.form-horizontal .form-group:after{display:table;content:" "}.form-horizontal .form-group:after{clear:both}.form-horizontal .form-group:before,.form-horizontal .form-group:after{display:table;content:" "}.form-horizontal .form-group:after{clear:both}@media(min-width:768px){.form-horizontal .form-group{margin-right:-15px;margin-left:-15px}}.form-horizontal .form-group .row{margin-right:-15px;margin-left:-15px}@media(min-width:768px){.form-horizontal .control-label{text-align:right}}.btn{display:inline-block;padding:8px 12px;margin-bottom:0;font-size:14px;font-weight:500;line-height:1.428571429;text-align:center;white-space:nowrap;vertical-align:middle;cursor:pointer;border:1px solid transparent;border-radius:4px}.btn:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn:hover,.btn:focus{color:#fff;text-decoration:none}.btn:active,.btn.active{outline:0;-webkit-box-shadow:inset 0 3px 5px rgba(0,0,0,0.125);box-shadow:inset 0 3px 5px rgba(0,0,0,0.125)}.btn.disabled,.btn[disabled],fieldset[disabled] .btn{pointer-events:none;cursor:default;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;box-shadow:none}.btn-default{color:#fff;background-color:#474949;border-color:#474949}.btn-default:hover,.btn-default:focus,.btn-default:active,.btn-default.active{background-color:#3a3c3c;border-color:#2e2f2f}.btn-default.disabled,.btn-default[disabled],fieldset[disabled] .btn-default,.btn-default.disabled:hover,.btn-default[disabled]:hover,fieldset[disabled] .btn-default:hover,.btn-default.disabled:focus,.btn-default[disabled]:focus,fieldset[disabled] .btn-default:focus,.btn-default.disabled:active,.btn-default[disabled]:active,fieldset[disabled] .btn-default:active,.btn-default.disabled.active,.btn-default[disabled].active,fieldset[disabled] .btn-default.active{background-color:#474949;border-color:#474949}.btn-primary{color:#fff;background-color:#428bca;border-color:#428bca}.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active{background-color:#357ebd;border-color:#3071a9}.btn-primary.disabled,.btn-primary[disabled],fieldset[disabled] .btn-primary,.btn-primary.disabled:hover,.btn-primary[disabled]:hover,fieldset[disabled] .btn-primary:hover,.btn-primary.disabled:focus,.btn-primary[disabled]:focus,fieldset[disabled] .btn-primary:focus,.btn-primary.disabled:active,.btn-primary[disabled]:active,fieldset[disabled] .btn-primary:active,.btn-primary.disabled.active,.btn-primary[disabled].active,fieldset[disabled] .btn-primary.active{background-color:#428bca;border-color:#428bca}.btn-warning{color:#fff;background-color:#f0ad4e;border-color:#f0ad4e}.btn-warning:hover,.btn-warning:focus,.btn-warning:active,.btn-warning.active{background-color:#eea236;border-color:#ec971f}.btn-warning.disabled,.btn-warning[disabled],fieldset[disabled] .btn-warning,.btn-warning.disabled:hover,.btn-warning[disabled]:hover,fieldset[disabled] .btn-warning:hover,.btn-warning.disabled:focus,.btn-warning[disabled]:focus,fieldset[disabled] .btn-warning:focus,.btn-warning.disabled:active,.btn-warning[disabled]:active,fieldset[disabled] .btn-warning:active,.btn-warning.disabled.active,.btn-warning[disabled].active,fieldset[disabled] .btn-warning.active{background-color:#f0ad4e;border-color:#f0ad4e}.btn-danger{color:#fff;background-color:#d9534f;border-color:#d9534f}.btn-danger:hover,.btn-danger:focus,.btn-danger:active,.btn-danger.active{background-color:#d43f3a;border-color:#c9302c}.btn-danger.disabled,.btn-danger[disabled],fieldset[disabled] .btn-danger,.btn-danger.disabled:hover,.btn-danger[disabled]:hover,fieldset[disabled] .btn-danger:hover,.btn-danger.disabled:focus,.btn-danger[disabled]:focus,fieldset[disabled] .btn-danger:focus,.btn-danger.disabled:active,.btn-danger[disabled]:active,fieldset[disabled] .btn-danger:active,.btn-danger.disabled.active,.btn-danger[disabled].active,fieldset[disabled] .btn-danger.active{background-color:#d9534f;border-color:#d9534f}.btn-success{color:#fff;background-color:#5cb85c;border-color:#5cb85c}.btn-success:hover,.btn-success:focus,.btn-success:active,.btn-success.active{background-color:#4cae4c;border-color:#449d44}.btn-success.disabled,.btn-success[disabled],fieldset[disabled] .btn-success,.btn-success.disabled:hover,.btn-success[disabled]:hover,fieldset[disabled] .btn-success:hover,.btn-success.disabled:focus,.btn-success[disabled]:focus,fieldset[disabled] .btn-success:focus,.btn-success.disabled:active,.btn-success[disabled]:active,fieldset[disabled] .btn-success:active,.btn-success.disabled.active,.btn-success[disabled].active,fieldset[disabled] .btn-success.active{background-color:#5cb85c;border-color:#5cb85c}.btn-info{color:#fff;background-color:#5bc0de;border-color:#5bc0de}.btn-info:hover,.btn-info:focus,.btn-info:active,.btn-info.active{background-color:#46b8da;border-color:#31b0d5}.btn-info.disabled,.btn-info[disabled],fieldset[disabled] .btn-info,.btn-info.disabled:hover,.btn-info[disabled]:hover,fieldset[disabled] .btn-info:hover,.btn-info.disabled:focus,.btn-info[disabled]:focus,fieldset[disabled] .btn-info:focus,.btn-info.disabled:active,.btn-info[disabled]:active,fieldset[disabled] .btn-info:active,.btn-info.disabled.active,.btn-info[disabled].active,fieldset[disabled] .btn-info.active{background-color:#5bc0de;border-color:#5bc0de}.btn-link{font-weight:normal;color:#428bca;cursor:pointer;border-radius:0}.btn-link,.btn-link:active,.btn-link[disabled],fieldset[disabled] .btn-link{background-color:transparent;-webkit-box-shadow:none;box-shadow:none}.btn-link,.btn-link:hover,.btn-link:focus,.btn-link:active{border-color:transparent}.btn-link:hover,.btn-link:focus{color:#2a6496;text-decoration:underline;background-color:transparent}.btn-link[disabled]:hover,fieldset[disabled] .btn-link:hover,.btn-link[disabled]:focus,fieldset[disabled] .btn-link:focus{color:#333;text-decoration:none}.btn-large{padding:14px 16px;font-size:18px;border-radius:6px}.btn-small{padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}.btn-block{display:block;width:100%;padding-right:0;padding-left:0}.btn-block+.btn-block{margin-top:5px}input[type="submit"].btn-block,input[type="reset"].btn-block,input[type="button"].btn-block{width:100%}.fade{opacity:0;-webkit-transition:opacity .15s linear;transition:opacity .15s linear}.fade.in{opacity:1}.collapse{display:none}.collapse.in{display:block}.collapsing{position:relative;height:0;overflow:hidden;-webkit-transition:height .35s ease;transition:height .35s ease}.caret{display:inline-block;width:0;height:0;margin-left:2px;vertical-align:middle;border-top:4px solid #000;border-right:4px solid transparent;border-left:4px solid transparent;content:""}.dropdown-menu{position:absolute;top:100%;left:0;z-index:1000;display:none;float:left;min-width:160px;padding:5px 0;margin:2px 0 0;list-style:none;background-color:#fff;border:1px solid #ccc;border:1px solid rgba(0,0,0,0.15);border-radius:4px;-webkit-box-shadow:0 6px 12px rgba(0,0,0,0.175);box-shadow:0 6px 12px rgba(0,0,0,0.175);background-clip:padding-box}.dropdown-menu.pull-right{right:0;left:auto}.dropdown-menu .divider{height:1px;margin:9px 0;overflow:hidden;background-color:#e5e5e5}.dropdown-menu>li>a{display:block;padding:3px 20px;clear:both;font-weight:normal;line-height:1.428571429;color:#333;white-space:nowrap}.dropdown-menu>li>a:hover,.dropdown-menu>li>a:focus{color:#fff;text-decoration:none;background-color:#357ebd;background-image:-webkit-gradient(linear,left 0,left 100%,from(#428bca),to(#357ebd));background-image:-webkit-linear-gradient(top,#428bca,0%,#357ebd,100%);background-image:-moz-linear-gradient(top,#428bca 0,#357ebd 100%);background-image:linear-gradient(to bottom,#428bca 0,#357ebd 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff428bca',endColorstr='#ff357ebd',GradientType=0)}.dropdown-menu>.active>a,.dropdown-menu>.active>a:hover,.dropdown-menu>.active>a:focus{color:#fff;text-decoration:none;background-color:#357ebd;background-image:-webkit-gradient(linear,left 0,left 100%,from(#428bca),to(#357ebd));background-image:-webkit-linear-gradient(top,#428bca,0%,#357ebd,100%);background-image:-moz-linear-gradient(top,#428bca 0,#357ebd 100%);background-image:linear-gradient(to bottom,#428bca 0,#357ebd 100%);background-repeat:repeat-x;outline:0;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff428bca',endColorstr='#ff357ebd',GradientType=0)}.dropdown-menu>.disabled>a,.dropdown-menu>.disabled>a:hover,.dropdown-menu>.disabled>a:focus{color:#999}.dropdown-menu>.disabled>a:hover,.dropdown-menu>.disabled>a:focus{text-decoration:none;cursor:not-allowed;background-color:transparent;background-image:none;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.open>.dropdown-menu{display:block}.open>a{outline:0}.dropdown-header{display:block;padding:3px 20px;font-size:12px;line-height:1.428571429;color:#999}.dropdown-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:990}.pull-right>.dropdown-menu{right:0;left:auto}.dropup .caret,.navbar-fixed-bottom .dropdown .caret{border-top:0;border-bottom:4px solid #000;content:""}.dropup .dropdown-menu,.navbar-fixed-bottom .dropdown .dropdown-menu{top:auto;bottom:100%;margin-bottom:1px}.list-group{padding-left:0;margin-bottom:20px;background-color:#fff}.list-group-item{position:relative;display:block;padding:10px 30px 10px 15px;margin-bottom:-1px;border:1px solid #ddd}.list-group-item:first-child{border-top-right-radius:4px;border-top-left-radius:4px}.list-group-item:last-child{margin-bottom:0;border-bottom-right-radius:4px;border-bottom-left-radius:4px}.list-group-item>.badge{float:right;margin-right:-15px}.list-group-item-heading{margin-top:0;margin-bottom:5px}.list-group-item-text{margin-bottom:0;line-height:1.3}a.list-group-item .list-group-item-heading{color:#333}a.list-group-item .list-group-item-text{color:#555}a.list-group-item:hover,a.list-group-item:focus{text-decoration:none;background-color:#f5f5f5}a.list-group-item.active{z-index:2;color:#fff;background-color:#428bca;border-color:#428bca}a.list-group-item.active .list-group-item-heading{color:inherit}a.list-group-item.active .list-group-item-text{color:#e1edf7}.panel{padding:15px;margin-bottom:20px;background-color:#fff;border:1px solid #ddd;border-radius:4px;-webkit-box-shadow:0 1px 1px rgba(0,0,0,0.05);box-shadow:0 1px 1px rgba(0,0,0,0.05)}.panel-heading{padding:10px 15px;margin:-15px -15px 15px;background-color:#f5f5f5;border-bottom:1px solid #ddd;border-top-right-radius:3px;border-top-left-radius:3px}.panel-title{margin-top:0;margin-bottom:0;font-size:17.5px;font-weight:500}.panel-footer{padding:10px 15px;margin:15px -15px -15px;background-color:#f5f5f5;border-top:1px solid #ddd;border-bottom-right-radius:3px;border-bottom-left-radius:3px}.panel-primary{border-color:#428bca}.panel-primary .panel-heading{color:#fff;background-color:#428bca;border-color:#428bca}.panel-success{border-color:#d6e9c6}.panel-success .panel-heading{color:#468847;background-color:#dff0d8;border-color:#d6e9c6}.panel-warning{border-color:#fbeed5}.panel-warning .panel-heading{color:#c09853;background-color:#fcf8e3;border-color:#fbeed5}.panel-danger{border-color:#eed3d7}.panel-danger .panel-heading{color:#b94a48;background-color:#f2dede;border-color:#eed3d7}.panel-info{border-color:#bce8f1}.panel-info .panel-heading{color:#3a87ad;background-color:#d9edf7;border-color:#bce8f1}.list-group-flush{margin:15px -15px -15px}.list-group-flush .list-group-item{border-width:1px 0}.list-group-flush .list-group-item:first-child{border-top-right-radius:0;border-top-left-radius:0}.list-group-flush .list-group-item:last-child{border-bottom:0}.well{min-height:20px;padding:19px;margin-bottom:20px;background-color:#f5f5f5;border:1px solid #e3e3e3;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.05);box-shadow:inset 0 1px 1px rgba(0,0,0,0.05)}.well blockquote{border-color:#ddd;border-color:rgba(0,0,0,0.15)}.well-large{padding:24px;border-radius:6px}.well-small{padding:9px;border-radius:3px}.close{float:right;font-size:21px;font-weight:bold;line-height:1;color:#000;text-shadow:0 1px 0 #fff;opacity:.2;filter:alpha(opacity=20)}.close:hover,.close:focus{color:#000;text-decoration:none;cursor:pointer;opacity:.5;filter:alpha(opacity=50)}button.close{padding:0;cursor:pointer;background:transparent;border:0;-webkit-appearance:none}.nav{padding-left:0;margin-bottom:0;list-style:none}.nav:before,.nav:after{display:table;content:" "}.nav:after{clear:both}.nav:before,.nav:after{display:table;content:" "}.nav:after{clear:both}.nav>li{position:relative;display:block}.nav>li>a{position:relative;display:block;padding:10px 15px}.nav>li>a:hover,.nav>li>a:focus{text-decoration:none;background-color:#eee}.nav>li.disabled>a{color:#999}.nav>li.disabled>a:hover,.nav>li.disabled>a:focus{color:#999;text-decoration:none;cursor:not-allowed;background-color:transparent}.nav>li+.nav-header{margin-top:9px}.nav.open>a,.nav.open>a:hover,.nav.open>a:focus{color:#fff;background-color:#428bca;border-color:#428bca}.nav.open>a .caret,.nav.open>a:hover .caret,.nav.open>a:focus .caret{border-top-color:#fff;border-bottom-color:#fff}.nav>.pull-right{float:right}.nav .nav-divider{height:1px;margin:9px 0;overflow:hidden;background-color:#e5e5e5}.nav-tabs{border-bottom:1px solid #ddd}.nav-tabs>li{float:left;margin-bottom:-1px}.nav-tabs>li>a{margin-right:2px;line-height:1.428571429;border:1px solid transparent;border-radius:4px 4px 0 0}.nav-tabs>li>a:hover{border-color:#eee}.nav-tabs>li.active>a,.nav-tabs>li.active>a:hover,.nav-tabs>li.active>a:focus{color:#555;cursor:default;background-color:#fff;border:1px solid #ddd;border-bottom-color:transparent}.nav-tabs.nav-justified{width:100%;border-bottom:0}.nav-tabs.nav-justified>li{display:table-cell;float:none;width:1%}.nav-tabs.nav-justified>li>a{text-align:center}.nav-tabs.nav-justified>li>a{margin-right:0;border-bottom:1px solid #ddd}.nav-tabs.nav-justified>.active>a{border-bottom-color:#fff}.nav-pills>li{float:left}.nav-pills>li>a{border-radius:5px}.nav-pills>li+li{margin-left:2px}.nav-pills>li.active>a,.nav-pills>li.active>a:hover,.nav-pills>li.active>a:focus{color:#fff;background-color:#428bca}.nav-stacked>li{float:none}.nav-stacked>li+li>a{margin-top:2px;margin-left:0}.nav-justified{width:100%}.nav-justified>li{display:table-cell;float:none;width:1%}.nav-justified>li>a{text-align:center}.nav-tabs-justified{border-bottom:0}.nav-tabs-justified>li>a{margin-right:0;border-bottom:1px solid #ddd}.nav-tabs-justified>.active>a{border-bottom-color:#fff}.tabbable:before,.tabbable:after{display:table;content:" "}.tabbable:after{clear:both}.tabbable:before,.tabbable:after{display:table;content:" "}.tabbable:after{clear:both}.tab-content>.tab-pane,.pill-content>.pill-pane{display:none}.tab-content>.active,.pill-content>.active{display:block}.nav .caret{border-top-color:#428bca;border-bottom-color:#428bca}.nav a:hover .caret{border-top-color:#2a6496;border-bottom-color:#2a6496}.nav-tabs .dropdown-menu{margin-top:-1px;border-top-right-radius:0;border-top-left-radius:0}.navbar{position:relative;min-height:50px;padding-right:15px;padding-left:15px;margin-bottom:20px;background-color:#eee;border-radius:4px}.navbar:before,.navbar:after{display:table;content:" "}.navbar:after{clear:both}.navbar:before,.navbar:after{display:table;content:" "}.navbar:after{clear:both}.navbar-nav{margin-top:10px;margin-bottom:15px}.navbar-nav>li>a{padding-top:15px;padding-bottom:15px;line-height:20px;color:#777;border-radius:4px}.navbar-nav>li>a:hover,.navbar-nav>li>a:focus{color:#333;background-color:transparent}.navbar-nav>.active>a,.navbar-nav>.active>a:hover,.navbar-nav>.active>a:focus{color:#555;background-color:#d5d5d5}.navbar-nav>.disabled>a,.navbar-nav>.disabled>a:hover,.navbar-nav>.disabled>a:focus{color:#ccc;background-color:transparent}.navbar-nav.pull-right{width:100%}.navbar-static-top{border-radius:0}.navbar-fixed-top,.navbar-fixed-bottom{position:fixed;right:0;left:0;z-index:1030;border-radius:0}.navbar-fixed-top{top:0}.navbar-fixed-bottom{bottom:0;margin-bottom:0}.navbar-brand{display:block;max-width:200px;padding:15px 15px;margin-right:auto;margin-left:auto;font-size:18px;font-weight:500;line-height:20px;color:#777;text-align:center}.navbar-brand:hover,.navbar-brand:focus{color:#5e5e5e;text-decoration:none;background-color:transparent}.navbar-toggle{position:absolute;top:9px;right:10px;width:48px;height:32px;padding:8px 12px;background-color:transparent;border:1px solid #ddd;border-radius:4px}.navbar-toggle:hover,.navbar-toggle:focus{background-color:#ddd}.navbar-toggle .icon-bar{display:block;width:22px;height:2px;background-color:#ccc;border-radius:1px}.navbar-toggle .icon-bar+.icon-bar{margin-top:4px}.navbar-form{margin-top:6px;margin-bottom:6px}.navbar-form .form-control,.navbar-form .radio,.navbar-form .checkbox{display:inline-block}.navbar-form .radio,.navbar-form .checkbox{margin-top:0;margin-bottom:0}.navbar-nav>li>.dropdown-menu{margin-top:0;border-top-right-radius:0;border-top-left-radius:0}.navbar-fixed-bottom .navbar-nav>li>.dropdown-menu{border-bottom-right-radius:0;border-bottom-left-radius:0}.navbar-nav>.dropdown>a:hover .caret,.navbar-nav>.dropdown>a:focus .caret{border-top-color:#333;border-bottom-color:#333}.navbar-nav>.open>a,.navbar-nav>.open>a:hover,.navbar-nav>.open>a:focus{color:#555;background-color:#d5d5d5}.navbar-nav>.open>a .caret,.navbar-nav>.open>a:hover .caret,.navbar-nav>.open>a:focus .caret{border-top-color:#555;border-bottom-color:#555}.navbar-nav>.dropdown>a .caret{border-top-color:#777;border-bottom-color:#777}.navbar-nav.pull-right>li>.dropdown-menu,.navbar-nav>li>.dropdown-menu.pull-right{right:0;left:auto}.navbar-inverse{background-color:#222}.navbar-inverse .navbar-brand{color:#999}.navbar-inverse .navbar-brand:hover,.navbar-inverse .navbar-brand:focus{color:#fff;background-color:transparent}.navbar-inverse .navbar-text{color:#999}.navbar-inverse .navbar-nav>li>a{color:#999}.navbar-inverse .navbar-nav>li>a:hover,.navbar-inverse .navbar-nav>li>a:focus{color:#fff;background-color:transparent}.navbar-inverse .navbar-nav>.active>a,.navbar-inverse .navbar-nav>.active>a:hover,.navbar-inverse .navbar-nav>.active>a:focus{color:#fff;background-color:#080808}.navbar-inverse .navbar-nav>.disabled>a,.navbar-inverse .navbar-nav>.disabled>a:hover,.navbar-inverse .navbar-nav>.disabled>a:focus{color:#444;background-color:transparent}.navbar-inverse .navbar-toggle{border-color:#333}.navbar-inverse .navbar-toggle:hover,.navbar-inverse .navbar-toggle:focus{background-color:#333}.navbar-inverse .navbar-toggle .icon-bar{background-color:#fff}.navbar-inverse .navbar-nav>.open>a,.navbar-inverse .navbar-nav>.open>a:hover,.navbar-inverse .navbar-nav>.open>a:focus{color:#fff;background-color:#080808}.navbar-inverse .navbar-nav>.dropdown>a:hover .caret{border-top-color:#fff;border-bottom-color:#fff}.navbar-inverse .navbar-nav>.dropdown>a .caret{border-top-color:#999;border-bottom-color:#999}.navbar-inverse .navbar-nav>.open>a .caret,.navbar-inverse .navbar-nav>.open>a:hover .caret,.navbar-inverse .navbar-nav>.open>a:focus .caret{border-top-color:#fff;border-bottom-color:#fff}@media screen and (min-width:768px){.navbar-brand{float:left;margin-right:5px;margin-left:-15px}.navbar-nav{float:left;margin-top:0;margin-bottom:0}.navbar-nav>li{float:left}.navbar-nav>li>a{border-radius:0}.navbar-nav.pull-right{float:right;width:auto}.navbar-toggle{position:relative;top:auto;left:auto;display:none}.nav-collapse.collapse{display:block!important;height:auto!important;overflow:visible!important}}.navbar-btn{margin-top:6px}.navbar-text{margin-top:15px;margin-bottom:15px}.navbar-link{color:#777}.navbar-link:hover{color:#333}.navbar-inverse .navbar-link{color:#999}.navbar-inverse .navbar-link:hover{color:#fff}.btn .caret{border-top-color:#fff}.dropup .btn .caret{border-bottom-color:#fff}.btn-group,.btn-group-vertical{position:relative;display:inline-block;vertical-align:middle}.btn-group>.btn,.btn-group-vertical>.btn{position:relative;float:left}.btn-group>.btn:hover,.btn-group-vertical>.btn:hover,.btn-group>.btn:active,.btn-group-vertical>.btn:active{z-index:2}.btn-group .btn+.btn{margin-left:-1px}.btn-toolbar:before,.btn-toolbar:after{display:table;content:" "}.btn-toolbar:after{clear:both}.btn-toolbar:before,.btn-toolbar:after{display:table;content:" "}.btn-toolbar:after{clear:both}.btn-toolbar .btn-group{float:left}.btn-toolbar>.btn+.btn,.btn-toolbar>.btn-group+.btn,.btn-toolbar>.btn+.btn-group,.btn-toolbar>.btn-group+.btn-group{margin-left:5px}.btn-group>.btn:not(:first-child):not(:last-child):not(.dropdown-toggle){border-radius:0}.btn-group>.btn:first-child{margin-left:0}.btn-group>.btn:first-child:not(:last-child):not(.dropdown-toggle){border-top-right-radius:0;border-bottom-right-radius:0}.btn-group>.btn:last-child:not(:first-child),.btn-group>.dropdown-toggle:not(:first-child){border-bottom-left-radius:0;border-top-left-radius:0}.btn-group>.btn-group{float:left}.btn-group>.btn-group:not(:first-child):not(:last-child)>.btn{border-radius:0}.btn-group>.btn-group:first-child>.btn:last-child,.btn-group>.btn-group:first-child>.dropdown-toggle{border-top-right-radius:0;border-bottom-right-radius:0}.btn-group>.btn-group:last-child>.btn:first-child{border-bottom-left-radius:0;border-top-left-radius:0}.btn-group .dropdown-toggle:active,.btn-group.open .dropdown-toggle{outline:0}.btn-group>.btn+.dropdown-toggle{padding-right:8px;padding-left:8px}.btn-group>.btn-large+.dropdown-toggle{padding-right:12px;padding-left:12px}.btn-group.open .dropdown-toggle{-webkit-box-shadow:inset 0 3px 5px rgba(0,0,0,0.125);box-shadow:inset 0 3px 5px rgba(0,0,0,0.125)}.btn .caret{margin-left:0}.btn-large .caret{border-width:5px}.dropup .btn-large .caret{border-bottom-width:5px}.btn-group-vertical>.btn{display:block;float:none;width:100%;max-width:100%}.btn-group-vertical>.btn+.btn{margin-top:-1px}.btn-group-vertical .btn:not(:first-child):not(:last-child){border-radius:0}.btn-group-vertical .btn:first-child{border-bottom-right-radius:0;border-bottom-left-radius:0}.btn-group-vertical .btn:last-child{border-top-right-radius:0;border-top-left-radius:0}.btn-group-justified{display:table;width:100%}.btn-group-justified .btn{display:table-cell;float:none;width:1%}.btn-group[data-toggle="buttons"]>.btn>input[type="radio"],.btn-group[data-toggle="buttons"]>.btn>input[type="checkbox"]{display:none}.breadcrumb{padding:8px 15px;margin-bottom:20px;list-style:none;background-color:#f5f5f5;border-radius:4px}.breadcrumb>li{display:inline-block}.breadcrumb>li+li:before{padding:0 5px;color:#ccc;content:"/\00a0"}.breadcrumb>.active{color:#999}.pagination{display:inline-block;padding-left:0;margin:20px 0;border-radius:4px}.pagination>li{display:inline}.pagination>li>a,.pagination>li>span{float:left;padding:4px 12px;line-height:1.428571429;text-decoration:none;background-color:#fff;border:1px solid #ddd;border-left-width:0}.pagination>li:first-child>a,.pagination>li:first-child>span{border-left-width:1px;border-bottom-left-radius:4px;border-top-left-radius:4px}.pagination>li:last-child>a,.pagination>li:last-child>span{border-top-right-radius:4px;border-bottom-right-radius:4px}.pagination>li>a:hover,.pagination>li>a:focus,.pagination>.active>a,.pagination>.active>span{background-color:#f5f5f5}.pagination>.active>a,.pagination>.active>span{color:#999;cursor:default}.pagination>.disabled>span,.pagination>.disabled>a,.pagination>.disabled>a:hover,.pagination>.disabled>a:focus{color:#999;cursor:not-allowed;background-color:#fff}.pagination-large>li>a,.pagination-large>li>span{padding:14px 16px;font-size:18px}.pagination-large>li:first-child>a,.pagination-large>li:first-child>span{border-bottom-left-radius:6px;border-top-left-radius:6px}.pagination-large>li:last-child>a,.pagination-large>li:last-child>span{border-top-right-radius:6px;border-bottom-right-radius:6px}.pagination-small>li>a,.pagination-small>li>span{padding:5px 10px;font-size:12px}.pagination-small>li:first-child>a,.pagination-small>li:first-child>span{border-bottom-left-radius:3px;border-top-left-radius:3px}.pagination-small>li:last-child>a,.pagination-small>li:last-child>span{border-top-right-radius:3px;border-bottom-right-radius:3px}.pager{padding-left:0;margin:20px 0;text-align:center;list-style:none}.pager:before,.pager:after{display:table;content:" "}.pager:after{clear:both}.pager:before,.pager:after{display:table;content:" "}.pager:after{clear:both}.pager li{display:inline}.pager li>a,.pager li>span{display:inline-block;padding:5px 14px;background-color:#fff;border:1px solid #ddd;border-radius:15px}.pager li>a:hover,.pager li>a:focus{text-decoration:none;background-color:#f5f5f5}.pager .next>a,.pager .next>span{float:right}.pager .previous>a,.pager .previous>span{float:left}.pager .disabled>a,.pager .disabled>a:hover,.pager .disabled>a:focus,.pager .disabled>span{color:#999;cursor:not-allowed;background-color:#fff}.modal-open{overflow:hidden}.modal{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1040;display:none;overflow:auto;overflow-y:scroll}.modal.fade .modal-dialog{-webkit-transform:translate(0,-25%);-ms-transform:translate(0,-25%);transform:translate(0,-25%);-webkit-transition:-webkit-transform .3s ease-out;-moz-transition:-moz-transform .3s ease-out;-o-transition:-o-transform .3s ease-out;transition:transform .3s ease-out}.modal.fade.in .modal-dialog{-webkit-transform:translate(0,0);-ms-transform:translate(0,0);transform:translate(0,0)}.modal-dialog{position:relative;top:0;right:0;left:0;z-index:1050;width:auto;padding:10px}.modal-content{position:relative;background-color:#fff;border:1px solid #999;border:1px solid rgba(0,0,0,0.2);border-radius:6px;outline:0;-webkit-box-shadow:0 3px 9px rgba(0,0,0,0.5);box-shadow:0 3px 9px rgba(0,0,0,0.5);background-clip:padding-box}.modal-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1030;background-color:#000}.modal-backdrop.fade{opacity:0;filter:alpha(opacity=0)}.modal-backdrop.fade.in{opacity:.5;filter:alpha(opacity=50)}.modal-header{min-height:16.428571429px;padding:15px;border-bottom:1px solid #e5e5e5}.modal-header .close{margin-top:-2px}.modal-title{margin:0;line-height:1.428571429}.modal-body{position:relative;padding:20px}.modal-footer{padding:19px 20px 20px;margin-top:15px;text-align:right;border-top:1px solid #e5e5e5}.modal-footer:before,.modal-footer:after{display:table;content:" "}.modal-footer:after{clear:both}.modal-footer:before,.modal-footer:after{display:table;content:" "}.modal-footer:after{clear:both}.modal-footer .btn+.btn{margin-bottom:0;margin-left:5px}.modal-footer .btn-group .btn+.btn{margin-left:-1px}.modal-footer .btn-block+.btn-block{margin-left:0}@media screen and (min-width:768px){.modal-dialog{right:auto;left:50%;width:560px;padding-top:30px;padding-bottom:30px;margin-left:-280px}.modal-content{-webkit-box-shadow:0 5px 15px rgba(0,0,0,0.5);box-shadow:0 5px 15px rgba(0,0,0,0.5)}}.tooltip{position:absolute;z-index:1030;display:block;font-size:12px;line-height:1.4;opacity:0;filter:alpha(opacity=0);visibility:visible}.tooltip.in{opacity:1;filter:alpha(opacity=100)}.tooltip.top{padding:5px 0;margin-top:-3px}.tooltip.right{padding:0 5px;margin-left:3px}.tooltip.bottom{padding:5px 0;margin-top:3px}.tooltip.left{padding:0 5px;margin-left:-3px}.tooltip-inner{max-width:200px;padding:3px 8px;color:#fff;text-align:center;text-decoration:none;background-color:rgba(0,0,0,0.9);border-radius:4px}.tooltip-arrow{position:absolute;width:0;height:0;border-color:transparent;border-style:solid}.tooltip.top .tooltip-arrow{bottom:0;left:50%;margin-left:-5px;border-top-color:rgba(0,0,0,0.9);border-width:5px 5px 0}.tooltip.top-left .tooltip-arrow{bottom:0;left:5px;border-top-color:rgba(0,0,0,0.9);border-width:5px 5px 0}.tooltip.top-right .tooltip-arrow{right:5px;bottom:0;border-top-color:rgba(0,0,0,0.9);border-width:5px 5px 0}.tooltip.right .tooltip-arrow{top:50%;left:0;margin-top:-5px;border-right-color:rgba(0,0,0,0.9);border-width:5px 5px 5px 0}.tooltip.left .tooltip-arrow{top:50%;right:0;margin-top:-5px;border-left-color:rgba(0,0,0,0.9);border-width:5px 0 5px 5px}.tooltip.bottom .tooltip-arrow{top:0;left:50%;margin-left:-5px;border-bottom-color:rgba(0,0,0,0.9);border-width:0 5px 5px}.tooltip.bottom-left .tooltip-arrow{top:0;left:5px;border-bottom-color:rgba(0,0,0,0.9);border-width:0 5px 5px}.tooltip.bottom-right .tooltip-arrow{top:0;right:5px;border-bottom-color:rgba(0,0,0,0.9);border-width:0 5px 5px}.popover{position:absolute;top:0;left:0;z-index:1010;display:none;max-width:276px;padding:1px;text-align:left;white-space:normal;background-color:#fff;border:1px solid #ccc;border:1px solid rgba(0,0,0,0.2);border-radius:6px;-webkit-box-shadow:0 5px 10px rgba(0,0,0,0.2);box-shadow:0 5px 10px rgba(0,0,0,0.2);background-clip:padding-box;-webkit-bg-clip:padding-box;-moz-bg-clip:padding}.popover.top{margin-top:-10px}.popover.right{margin-left:10px}.popover.bottom{margin-top:10px}.popover.left{margin-left:-10px}.popover-title{padding:8px 14px;margin:0;font-size:14px;font-weight:normal;line-height:18px;background-color:#f7f7f7;border-bottom:1px solid #ebebeb;border-radius:5px 5px 0 0}.popover-content{padding:9px 14px}.popover .arrow,.popover .arrow:after{position:absolute;display:block;width:0;height:0;border-color:transparent;border-style:solid}.popover .arrow{border-width:11px}.popover .arrow:after{border-width:10px;content:""}.popover.top .arrow{bottom:-11px;left:50%;margin-left:-11px;border-top-color:#999;border-top-color:rgba(0,0,0,0.25);border-bottom-width:0}.popover.top .arrow:after{bottom:1px;margin-left:-10px;border-top-color:#fff;border-bottom-width:0;content:" "}.popover.right .arrow{top:50%;left:-11px;margin-top:-11px;border-right-color:#999;border-right-color:rgba(0,0,0,0.25);border-left-width:0}.popover.right .arrow:after{bottom:-10px;left:1px;border-right-color:#fff;border-left-width:0;content:" "}.popover.bottom .arrow{top:-11px;left:50%;margin-left:-11px;border-bottom-color:#999;border-bottom-color:rgba(0,0,0,0.25);border-top-width:0}.popover.bottom .arrow:after{top:1px;margin-left:-10px;border-bottom-color:#fff;border-top-width:0;content:" "}.popover.left .arrow{top:50%;right:-11px;margin-top:-11px;border-left-color:#999;border-left-color:rgba(0,0,0,0.25);border-right-width:0}.popover.left .arrow:after{right:1px;bottom:-10px;border-left-color:#fff;border-right-width:0;content:" "}.alert{padding:10px 35px 10px 15px;margin-bottom:20px;color:#c09853;background-color:#fcf8e3;border:1px solid #fbeed5;border-radius:4px}.alert h4{margin-top:0;color:inherit}.alert hr{border-top-color:#f8e5be}.alert .alert-link{font-weight:500;color:#a47e3c}.alert .close{position:relative;top:-2px;right:-21px;color:inherit}.alert-success{color:#468847;background-color:#dff0d8;border-color:#d6e9c6}.alert-success hr{border-top-color:#c9e2b3}.alert-success .alert-link{color:#356635}.alert-danger{color:#b94a48;background-color:#f2dede;border-color:#eed3d7}.alert-danger hr{border-top-color:#e6c1c7}.alert-danger .alert-link{color:#953b39}.alert-info{color:#3a87ad;background-color:#d9edf7;border-color:#bce8f1}.alert-info hr{border-top-color:#a6e1ec}.alert-info .alert-link{color:#2d6987}.alert-block{padding-top:15px;padding-bottom:15px}.alert-block>p,.alert-block>ul{margin-bottom:0}.alert-block p+p{margin-top:5px}.thumbnail,.img-thumbnail{padding:4px;line-height:1.428571429;background-color:#fff;border:1px solid #ddd;border-radius:4px;-webkit-transition:all .2s ease-in-out;transition:all .2s ease-in-out}.thumbnail{display:block}.thumbnail>img,.img-thumbnail{display:inline-block;height:auto;max-width:100%}a.thumbnail:hover,a.thumbnail:focus{border-color:#428bca}.thumbnail>img{margin-right:auto;margin-left:auto}.thumbnail .caption{padding:9px;color:#333}.media,.media-body{overflow:hidden;zoom:1}.media,.media .media{margin-top:15px}.media:first-child{margin-top:0}.media-object{display:block}.media-heading{margin:0 0 5px}.media>.pull-left{margin-right:10px}.media>.pull-right{margin-left:10px}.media-list{padding-left:0;list-style:none}.label{display:inline;padding:.25em .6em;font-size:75%;font-weight:500;line-height:1;color:#fff;text-align:center;white-space:nowrap;vertical-align:middle;background-color:#999;border-radius:.25em}.label[href]:hover,.label[href]:focus{color:#fff;text-decoration:none;cursor:pointer;background-color:#808080}.label-danger{background-color:#d9534f}.label-danger[href]:hover,.label-danger[href]:focus{background-color:#c9302c}.label-success{background-color:#5cb85c}.label-success[href]:hover,.label-success[href]:focus{background-color:#449d44}.label-warning{background-color:#f0ad4e}.label-warning[href]:hover,.label-warning[href]:focus{background-color:#ec971f}.label-info{background-color:#5bc0de}.label-info[href]:hover,.label-info[href]:focus{background-color:#31b0d5}.badge{display:inline-block;min-width:10px;padding:3px 7px;font-size:12px;font-weight:bold;line-height:1;color:#fff;text-align:center;white-space:nowrap;vertical-align:middle;background-color:#999;border-radius:10px}.badge:empty{display:none}a.badge:hover,a.badge:focus{color:#fff;text-decoration:none;cursor:pointer}.btn .badge{position:relative;top:-1px}a.list-group-item.active>.badge,.nav-pills>.active>a>.badge{color:#428bca;background-color:#fff}.nav-pills>li>a>.badge{margin-left:3px}@-webkit-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@-moz-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@-ms-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@-o-keyframes progress-bar-stripes{from{background-position:0 0}to{background-position:40px 0}}@keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}.progress{height:20px;margin-bottom:20px;overflow:hidden;background-color:#f5f5f5;border-radius:4px;-webkit-box-shadow:inset 0 1px 2px rgba(0,0,0,0.1);box-shadow:inset 0 1px 2px rgba(0,0,0,0.1)}.progress-bar{float:left;width:0;height:100%;font-size:12px;color:#fff;text-align:center;background-color:#428bca;-webkit-box-shadow:inset 0 -1px 0 rgba(0,0,0,0.15);box-shadow:inset 0 -1px 0 rgba(0,0,0,0.15);-webkit-transition:width .6s ease;transition:width .6s ease}.progress-striped .progress-bar{background-color:#428bca;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-size:40px 40px}.progress.active .progress-bar{-webkit-animation:progress-bar-stripes 2s linear infinite;-moz-animation:progress-bar-stripes 2s linear infinite;-ms-animation:progress-bar-stripes 2s linear infinite;-o-animation:progress-bar-stripes 2s linear infinite;animation:progress-bar-stripes 2s linear infinite}.progress-bar-danger{background-color:#d9534f}.progress-striped .progress-bar-danger{background-color:#d9534f;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.progress-bar-success{background-color:#5cb85c}.progress-striped .progress-bar-success{background-color:#5cb85c;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.progress-bar-warning{background-color:#f0ad4e}.progress-striped .progress-bar-warning{background-color:#f0ad4e;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.progress-bar-info{background-color:#5bc0de}.progress-striped .progress-bar-info{background-color:#5bc0de;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.accordion{margin-bottom:20px}.accordion-group{margin-bottom:2px;border:1px solid #e5e5e5;border-radius:4px}.accordion-heading{border-bottom:0}.accordion-heading .accordion-toggle{display:block;padding:8px 15px;cursor:pointer}.accordion-inner{padding:9px 15px;border-top:1px solid #e5e5e5}.carousel{position:relative}.carousel-inner{position:relative;width:100%;overflow:hidden}.carousel-inner>.item{position:relative;display:none;-webkit-transition:.6s ease-in-out left;transition:.6s ease-in-out left}.carousel-inner>.item>img,.carousel-inner>.item>a>img{display:inline-block;height:auto;max-width:100%;line-height:1}.carousel-inner>.active,.carousel-inner>.next,.carousel-inner>.prev{display:block}.carousel-inner>.active{left:0}.carousel-inner>.next,.carousel-inner>.prev{position:absolute;top:0;width:100%}.carousel-inner>.next{left:100%}.carousel-inner>.prev{left:-100%}.carousel-inner>.next.left,.carousel-inner>.prev.right{left:0}.carousel-inner>.active.left{left:-100%}.carousel-inner>.active.right{left:100%}.carousel-control{position:absolute;top:0;bottom:0;left:0;width:15%;font-size:20px;color:#fff;text-align:center;text-shadow:0 1px 2px rgba(0,0,0,0.6);opacity:.5;filter:alpha(opacity=50)}.carousel-control.left{background-color:rgba(0,0,0,0.0001);background-color:transparent;background-image:-webkit-gradient(linear,0 top,100% top,from(rgba(0,0,0,0.5)),to(rgba(0,0,0,0.0001)));background-image:-webkit-linear-gradient(left,color-stop(rgba(0,0,0,0.5) 0),color-stop(rgba(0,0,0,0.0001) 100%));background-image:-moz-linear-gradient(left,rgba(0,0,0,0.5) 0,rgba(0,0,0,0.0001) 100%);background-image:linear-gradient(to right,rgba(0,0,0,0.5) 0,rgba(0,0,0,0.0001) 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#80000000',endColorstr='#00000000',GradientType=1)}.carousel-control.right{right:0;left:auto;background-color:rgba(0,0,0,0.5);background-color:transparent;background-image:-webkit-gradient(linear,0 top,100% top,from(rgba(0,0,0,0.0001)),to(rgba(0,0,0,0.5)));background-image:-webkit-linear-gradient(left,color-stop(rgba(0,0,0,0.0001) 0),color-stop(rgba(0,0,0,0.5) 100%));background-image:-moz-linear-gradient(left,rgba(0,0,0,0.0001) 0,rgba(0,0,0,0.5) 100%);background-image:linear-gradient(to right,rgba(0,0,0,0.0001) 0,rgba(0,0,0,0.5) 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#00000000',endColorstr='#80000000',GradientType=1)}.carousel-control:hover,.carousel-control:focus{color:#fff;text-decoration:none;opacity:.9;filter:alpha(opacity=90)}.carousel-control .glyphicon,.carousel-control .icon-prev,.carousel-control .icon-next{position:absolute;top:50%;left:50%;z-index:5;display:inline-block;width:20px;height:20px;margin-top:-10px;margin-left:-10px;font-family:serif}.carousel-control .icon-prev:before{content:'\2039'}.carousel-control .icon-next:before{content:'\203a'}.carousel-indicators{position:absolute;bottom:10px;left:50%;z-index:15;width:120px;padding-left:0;margin-left:-60px;text-align:center;list-style:none}.carousel-indicators li{display:inline-block;width:10px;height:10px;margin:1px;text-indent:-999px;cursor:pointer;border:1px solid #fff;border-radius:10px}.carousel-indicators .active{width:12px;height:12px;margin:0;background-color:#fff}.carousel-caption{position:absolute;right:15%;bottom:20px;left:15%;z-index:10;padding-top:20px;padding-bottom:20px;color:#fff;text-align:center;text-shadow:0 1px 2px rgba(0,0,0,0.6)}.carousel-caption .btn{text-shadow:none}@media screen and (min-width:768px){.carousel-control .glyphicon,.carousel-control .icon-prev,.carousel-control .icon-next{width:30px;height:30px;margin-top:-15px;margin-left:-15px;font-size:30px}.carousel-caption{right:20%;left:20%;padding-bottom:30px}.carousel-indicators{bottom:20px}}.jumbotron{padding:30px;margin-bottom:30px;font-size:21px;font-weight:200;line-height:2.1428571435;color:inherit;background-color:#eee}.jumbotron h1{line-height:1;color:inherit}.jumbotron p{line-height:1.4}@media screen and (min-width:768px){.jumbotron{padding:50px 60px;border-radius:6px}.jumbotron h1{font-size:63px}}.clearfix:before,.clearfix:after{display:table;content:" "}.clearfix:after{clear:both}.pull-right{float:right}.pull-left{float:left}.hide{display:none!important}.show{display:block!important}.invisible{visibility:hidden}.text-hide{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0}.affix{position:fixed}@-ms-viewport{width:device-width}@media screen and (max-width:400px){@-ms-viewport{width:320px}}.hidden{display:none!important;visibility:hidden!important}.visible-sm{display:block!important}tr.visible-sm{display:table-row!important}th.visible-sm,td.visible-sm{display:table-cell!important}.visible-md{display:none!important}tr.visible-md{display:none!important}th.visible-md,td.visible-md{display:none!important}.visible-lg{display:none!important}tr.visible-lg{display:none!important}th.visible-lg,td.visible-lg{display:none!important}.hidden-sm{display:none!important}tr.hidden-sm{display:none!important}th.hidden-sm,td.hidden-sm{display:none!important}.hidden-md{display:block!important}tr.hidden-md{display:table-row!important}th.hidden-md,td.hidden-md{display:table-cell!important}.hidden-lg{display:block!important}tr.hidden-lg{display:table-row!important}th.hidden-lg,td.hidden-lg{display:table-cell!important}@media(min-width:768px) and (max-width:991px){.visible-sm{display:none!important}tr.visible-sm{display:none!important}th.visible-sm,td.visible-sm{display:none!important}.visible-md{display:block!important}tr.visible-md{display:table-row!important}th.visible-md,td.visible-md{display:table-cell!important}.visible-lg{display:none!important}tr.visible-lg{display:none!important}th.visible-lg,td.visible-lg{display:none!important}.hidden-sm{display:block!important}tr.hidden-sm{display:table-row!important}th.hidden-sm,td.hidden-sm{display:table-cell!important}.hidden-md{display:none!important}tr.hidden-md{display:none!important}th.hidden-md,td.hidden-md{display:none!important}.hidden-lg{display:block!important}tr.hidden-lg{display:table-row!important}th.hidden-lg,td.hidden-lg{display:table-cell!important}}@media(min-width:992px){.visible-sm{display:none!important}tr.visible-sm{display:none!important}th.visible-sm,td.visible-sm{display:none!important}.visible-md{display:none!important}tr.visible-md{display:none!important}th.visible-md,td.visible-md{display:none!important}.visible-lg{display:block!important}tr.visible-lg{display:table-row!important}th.visible-lg,td.visible-lg{display:table-cell!important}.hidden-sm{display:block!important}tr.hidden-sm{display:table-row!important}th.hidden-sm,td.hidden-sm{display:table-cell!important}.hidden-md{display:block!important}tr.hidden-md{display:table-row!important}th.hidden-md,td.hidden-md{display:table-cell!important}.hidden-lg{display:none!important}tr.hidden-lg{display:none!important}th.hidden-lg,td.hidden-lg{display:none!important}}.visible-print{display:none!important}tr.visible-print{display:none!important}th.visible-print,td.visible-print{display:none!important}@media print{.visible-print{display:block!important}tr.visible-print{display:table-row!important}th.visible-print,td.visible-print{display:table-cell!important}.hidden-print{display:none!important}tr.hidden-print{display:none!important}th.hidden-print,td.hidden-print{display:none!important}} </style> <!-- zepto --> <script type="text/javascript"> /* Zepto v1.1.2 - zepto event ajax form ie - zeptojs.com/license */ var Zepto=function(){function G(a){return a==null?String(a):z[A.call(a)]||"object"}function H(a){return G(a)=="function"}function I(a){return a!=null&&a==a.window}function J(a){return a!=null&&a.nodeType==a.DOCUMENT_NODE}function K(a){return G(a)=="object"}function L(a){return K(a)&&!I(a)&&Object.getPrototypeOf(a)==Object.prototype}function M(a){return a instanceof Array}function N(a){return typeof a.length=="number"}function O(a){return g.call(a,function(a){return a!=null})}function P(a){return a.length>0?c.fn.concat.apply([],a):a}function Q(a){return a.replace(/::/g,"/").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/_/g,"-").toLowerCase()}function R(a){return a in j?j[a]:j[a]=new RegExp("(^|\\s)"+a+"(\\s|$)")}function S(a,b){return typeof b=="number"&&!k[Q(a)]?b+"px":b}function T(a){var b,c;return i[a]||(b=h.createElement(a),h.body.appendChild(b),c=getComputedStyle(b,"").getPropertyValue("display"),b.parentNode.removeChild(b),c=="none"&&(c="block"),i[a]=c),i[a]}function U(a){return"children"in a?f.call(a.children):c.map(a.childNodes,function(a){if(a.nodeType==1)return a})}function V(c,d,e){for(b in d)e&&(L(d[b])||M(d[b]))?(L(d[b])&&!L(c[b])&&(c[b]={}),M(d[b])&&!M(c[b])&&(c[b]=[]),V(c[b],d[b],e)):d[b]!==a&&(c[b]=d[b])}function W(a,b){return b==null?c(a):c(a).filter(b)}function X(a,b,c,d){return H(b)?b.call(a,c,d):b}function Y(a,b,c){c==null?a.removeAttribute(b):a.setAttribute(b,c)}function Z(b,c){var d=b.className,e=d&&d.baseVal!==a;if(c===a)return e?d.baseVal:d;e?d.baseVal=c:b.className=c}function $(a){var b;try{return a?a=="true"||(a=="false"?!1:a=="null"?null:!/^0/.test(a)&&!isNaN(b=Number(a))?b:/^[\[\{]/.test(a)?c.parseJSON(a):a):a}catch(d){return a}}function _(a,b){b(a);for(var c in a.childNodes)_(a.childNodes[c],b)}var a,b,c,d,e=[],f=e.slice,g=e.filter,h=window.document,i={},j={},k={"column-count":1,columns:1,"font-weight":1,"line-height":1,opacity:1,"z-index":1,zoom:1},l=/^\s*<(\w+|!)[^>]*>/,m=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,n=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,o=/^(?:body|html)$/i,p=/([A-Z])/g,q=["val","css","html","text","data","width","height","offset"],r=["after","prepend","before","append"],s=h.createElement("table"),t=h.createElement("tr"),u={tr:h.createElement("tbody"),tbody:s,thead:s,tfoot:s,td:t,th:t,"*":h.createElement("div")},v=/complete|loaded|interactive/,w=/^\.([\w-]+)$/,x=/^#([\w-]*)$/,y=/^[\w-]*$/,z={},A=z.toString,B={},C,D,E=h.createElement("div"),F={tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"};return B.matches=function(a,b){if(!b||!a||a.nodeType!==1)return!1;var c=a.webkitMatchesSelector||a.mozMatchesSelector||a.oMatchesSelector||a.matchesSelector;if(c)return c.call(a,b);var d,e=a.parentNode,f=!e;return f&&(e=E).appendChild(a),d=~B.qsa(e,b).indexOf(a),f&&E.removeChild(a),d},C=function(a){return a.replace(/-+(.)?/g,function(a,b){return b?b.toUpperCase():""})},D=function(a){return g.call(a,function(b,c){return a.indexOf(b)==c})},B.fragment=function(b,d,e){var g,i,j;return m.test(b)&&(g=c(h.createElement(RegExp.$1))),g||(b.replace&&(b=b.replace(n,"<$1></$2>")),d===a&&(d=l.test(b)&&RegExp.$1),d in u||(d="*"),j=u[d],j.innerHTML=""+b,g=c.each(f.call(j.childNodes),function(){j.removeChild(this)})),L(e)&&(i=c(g),c.each(e,function(a,b){q.indexOf(a)>-1?i[a](b):i.attr(a,b)})),g},B.Z=function(a,b){return a=a||[],a.__proto__=c.fn,a.selector=b||"",a},B.isZ=function(a){return a instanceof B.Z},B.init=function(b,d){var e;if(!b)return B.Z();if(typeof b=="string"){b=b.trim();if(b[0]=="<"&&l.test(b))e=B.fragment(b,RegExp.$1,d),b=null;else{if(d!==a)return c(d).find(b);e=B.qsa(h,b)}}else{if(H(b))return c(h).ready(b);if(B.isZ(b))return b;if(M(b))e=O(b);else if(K(b))e=[b],b=null;else if(l.test(b))e=B.fragment(b.trim(),RegExp.$1,d),b=null;else{if(d!==a)return c(d).find(b);e=B.qsa(h,b)}}return B.Z(e,b)},c=function(a,b){return B.init(a,b)},c.extend=function(a){var b,c=f.call(arguments,1);return typeof a=="boolean"&&(b=a,a=c.shift()),c.forEach(function(c){V(a,c,b)}),a},B.qsa=function(a,b){var c,d=b[0]=="#",e=!d&&b[0]==".",g=d||e?b.slice(1):b,h=y.test(g);return J(a)&&h&&d?(c=a.getElementById(g))?[c]:[]:a.nodeType!==1&&a.nodeType!==9?[]:f.call(h&&!d?e?a.getElementsByClassName(g):a.getElementsByTagName(b):a.querySelectorAll(b))},c.contains=function(a,b){return a!==b&&a.contains(b)},c.type=G,c.isFunction=H,c.isWindow=I,c.isArray=M,c.isPlainObject=L,c.isEmptyObject=function(a){var b;for(b in a)return!1;return!0},c.inArray=function(a,b,c){return e.indexOf.call(b,a,c)},c.camelCase=C,c.trim=function(a){return a==null?"":String.prototype.trim.call(a)},c.uuid=0,c.support={},c.expr={},c.map=function(a,b){var c,d=[],e,f;if(N(a))for(e=0;e<a.length;e++)c=b(a[e],e),c!=null&&d.push(c);else for(f in a)c=b(a[f],f),c!=null&&d.push(c);return P(d)},c.each=function(a,b){var c,d;if(N(a)){for(c=0;c<a.length;c++)if(b.call(a[c],c,a[c])===!1)return a}else for(d in a)if(b.call(a[d],d,a[d])===!1)return a;return a},c.grep=function(a,b){return g.call(a,b)},window.JSON&&(c.parseJSON=JSON.parse),c.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){z["[object "+b+"]"]=b.toLowerCase()}),c.fn={forEach:e.forEach,reduce:e.reduce,push:e.push,sort:e.sort,indexOf:e.indexOf,concat:e.concat,map:function(a){return c(c.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return c(f.apply(this,arguments))},ready:function(a){return v.test(h.readyState)&&h.body?a(c):h.addEventListener("DOMContentLoaded",function(){a(c)},!1),this},get:function(b){return b===a?f.call(this):this[b>=0?b:b+this.length]},toArray:function(){return this.get()},size:function(){return this.length},remove:function(){return this.each(function(){this.parentNode!=null&&this.parentNode.removeChild(this)})},each:function(a){return e.every.call(this,function(b,c){return a.call(b,c,b)!==!1}),this},filter:function(a){return H(a)?this.not(this.not(a)):c(g.call(this,function(b){return B.matches(b,a)}))},add:function(a,b){return c(D(this.concat(c(a,b))))},is:function(a){return this.length>0&&B.matches(this[0],a)},not:function(b){var d=[];if(H(b)&&b.call!==a)this.each(function(a){b.call(this,a)||d.push(this)});else{var e=typeof b=="string"?this.filter(b):N(b)&&H(b.item)?f.call(b):c(b);this.forEach(function(a){e.indexOf(a)<0&&d.push(a)})}return c(d)},has:function(a){return this.filter(function(){return K(a)?c.contains(this,a):c(this).find(a).size()})},eq:function(a){return a===-1?this.slice(a):this.slice(a,+a+1)},first:function(){var a=this[0];return a&&!K(a)?a:c(a)},last:function(){var a=this[this.length-1];return a&&!K(a)?a:c(a)},find:function(a){var b,d=this;return typeof a=="object"?b=c(a).filter(function(){var a=this;return e.some.call(d,function(b){return c.contains(b,a)})}):this.length==1?b=c(B.qsa(this[0],a)):b=this.map(function(){return B.qsa(this,a)}),b},closest:function(a,b){var d=this[0],e=!1;typeof a=="object"&&(e=c(a));while(d&&!(e?e.indexOf(d)>=0:B.matches(d,a)))d=d!==b&&!J(d)&&d.parentNode;return c(d)},parents:function(a){var b=[],d=this;while(d.length>0)d=c.map(d,function(a){if((a=a.parentNode)&&!J(a)&&b.indexOf(a)<0)return b.push(a),a});return W(b,a)},parent:function(a){return W(D(this.pluck("parentNode")),a)},children:function(a){return W(this.map(function(){return U(this)}),a)},contents:function(){return this.map(function(){return f.call(this.childNodes)})},siblings:function(a){return W(this.map(function(a,b){return g.call(U(b.parentNode),function(a){return a!==b})}),a)},empty:function(){return this.each(function(){this.innerHTML=""})},pluck:function(a){return c.map(this,function(b){return b[a]})},show:function(){return this.each(function(){this.style.display=="none"&&(this.style.display=""),getComputedStyle(this,"").getPropertyValue("display")=="none"&&(this.style.display=T(this.nodeName))})},replaceWith:function(a){return this.before(a).remove()},wrap:function(a){var b=H(a);if(this[0]&&!b)var d=c(a).get(0),e=d.parentNode||this.length>1;return this.each(function(f){c(this).wrapAll(b?a.call(this,f):e?d.cloneNode(!0):d)})},wrapAll:function(a){if(this[0]){c(this[0]).before(a=c(a));var b;while((b=a.children()).length)a=b.first();c(a).append(this)}return this},wrapInner:function(a){var b=H(a);return this.each(function(d){var e=c(this),f=e.contents(),g=b?a.call(this,d):a;f.length?f.wrapAll(g):e.append(g)})},unwrap:function(){return this.parent().each(function(){c(this).replaceWith(c(this).children())}),this},clone:function(){return this.map(function(){return this.cloneNode(!0)})},hide:function(){return this.css("display","none")},toggle:function(b){return this.each(function(){var d=c(this);(b===a?d.css("display")=="none":b)?d.show():d.hide()})},prev:function(a){return c(this.pluck("previousElementSibling")).filter(a||"*")},next:function(a){return c(this.pluck("nextElementSibling")).filter(a||"*")},html:function(a){return arguments.length===0?this.length>0?this[0].innerHTML:null:this.each(function(b){var d=this.innerHTML;c(this).empty().append(X(this,a,b,d))})},text:function(b){return arguments.length===0?this.length>0?this[0].textContent:null:this.each(function(){this.textContent=b===a?"":""+b})},attr:function(c,d){var e;return typeof c=="string"&&d===a?this.length==0||this[0].nodeType!==1?a:c=="value"&&this[0].nodeName=="INPUT"?this.val():!(e=this[0].getAttribute(c))&&c in this[0]?this[0][c]:e:this.each(function(a){if(this.nodeType!==1)return;if(K(c))for(b in c)Y(this,b,c[b]);else Y(this,c,X(this,d,a,this.getAttribute(c)))})},removeAttr:function(a){return this.each(function(){this.nodeType===1&&Y(this,a)})},prop:function(b,c){return b=F[b]||b,c===a?this[0]&&this[0][b]:this.each(function(a){this[b]=X(this,c,a,this[b])})},data:function(b,c){var d=this.attr("data-"+b.replace(p,"-$1").toLowerCase(),c);return d!==null?$(d):a},val:function(a){return arguments.length===0?this[0]&&(this[0].multiple?c(this[0]).find("option").filter(function(){return this.selected}).pluck("value"):this[0].value):this.each(function(b){this.value=X(this,a,b,this.value)})},offset:function(a){if(a)return this.each(function(b){var d=c(this),e=X(this,a,b,d.offset()),f=d.offsetParent().offset(),g={top:e.top-f.top,left:e.left-f.left};d.css("position")=="static"&&(g.position="relative"),d.css(g)});if(this.length==0)return null;var b=this[0].getBoundingClientRect();return{left:b.left+window.pageXOffset,top:b.top+window.pageYOffset,width:Math.round(b.width),height:Math.round(b.height)}},css:function(a,d){if(arguments.length<2){var e=this[0],f=getComputedStyle(e,"");if(!e)return;if(typeof a=="string")return e.style[C(a)]||f.getPropertyValue(a);if(M(a)){var g={};return c.each(M(a)?a:[a],function(a,b){g[b]=e.style[C(b)]||f.getPropertyValue(b)}),g}}var h="";if(G(a)=="string")!d&&d!==0?this.each(function(){this.style.removeProperty(Q(a))}):h=Q(a)+":"+S(a,d);else for(b in a)!a[b]&&a[b]!==0?this.each(function(){this.style.removeProperty(Q(b))}):h+=Q(b)+":"+S(b,a[b])+";";return this.each(function(){this.style.cssText+=";"+h})},index:function(a){return a?this.indexOf(c(a)[0]):this.parent().children().indexOf(this[0])},hasClass:function(a){return a?e.some.call(this,function(a){return this.test(Z(a))},R(a)):!1},addClass:function(a){return a?this.each(function(b){d=[];var e=Z(this),f=X(this,a,b,e);f.split(/\s+/g).forEach(function(a){c(this).hasClass(a)||d.push(a)},this),d.length&&Z(this,e+(e?" ":"")+d.join(" "))}):this},removeClass:function(b){return this.each(function(c){if(b===a)return Z(this,"");d=Z(this),X(this,b,c,d).split(/\s+/g).forEach(function(a){d=d.replace(R(a)," ")}),Z(this,d.trim())})},toggleClass:function(b,d){return b?this.each(function(e){var f=c(this),g=X(this,b,e,Z(this));g.split(/\s+/g).forEach(function(b){(d===a?!f.hasClass(b):d)?f.addClass(b):f.removeClass(b)})}):this},scrollTop:function(b){if(!this.length)return;var c="scrollTop"in this[0];return b===a?c?this[0].scrollTop:this[0].pageYOffset:this.each(c?function(){this.scrollTop=b}:function(){this.scrollTo(this.scrollX,b)})},scrollLeft:function(b){if(!this.length)return;var c="scrollLeft"in this[0];return b===a?c?this[0].scrollLeft:this[0].pageXOffset:this.each(c?function(){this.scrollLeft=b}:function(){this.scrollTo(b,this.scrollY)})},position:function(){if(!this.length)return;var a=this[0],b=this.offsetParent(),d=this.offset(),e=o.test(b[0].nodeName)?{top:0,left:0}:b.offset();return d.top-=parseFloat(c(a).css("margin-top"))||0,d.left-=parseFloat(c(a).css("margin-left"))||0,e.top+=parseFloat(c(b[0]).css("border-top-width"))||0,e.left+=parseFloat(c(b[0]).css("border-left-width"))||0,{top:d.top-e.top,left:d.left-e.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||h.body;while(a&&!o.test(a.nodeName)&&c(a).css("position")=="static")a=a.offsetParent;return a})}},c.fn.detach=c.fn.remove,["width","height"].forEach(function(b){var d=b.replace(/./,function(a){return a[0].toUpperCase()});c.fn[b]=function(e){var f,g=this[0];return e===a?I(g)?g["inner"+d]:J(g)?g.documentElement["scroll"+d]:(f=this.offset())&&f[b]:this.each(function(a){g=c(this),g.css(b,X(this,e,a,g[b]()))})}}),r.forEach(function(a,b){var d=b%2;c.fn[a]=function(){var a,e=c.map(arguments,function(b){return a=G(b),a=="object"||a=="array"||b==null?b:B.fragment(b)}),f,g=this.length>1;return e.length<1?this:this.each(function(a,h){f=d?h:h.parentNode,h=b==0?h.nextSibling:b==1?h.firstChild:b==2?h:null,e.forEach(function(a){if(g)a=a.cloneNode(!0);else if(!f)return c(a).remove();_(f.insertBefore(a,h),function(a){a.nodeName!=null&&a.nodeName.toUpperCase()==="SCRIPT"&&(!a.type||a.type==="text/javascript")&&!a.src&&window.eval.call(window,a.innerHTML)})})})},c.fn[d?a+"To":"insert"+(b?"Before":"After")]=function(b){return c(b)[a](this),this}}),B.Z.prototype=c.fn,B.uniq=D,B.deserializeValue=$,c.zepto=B,c}();window.Zepto=Zepto,window.$===undefined&&(window.$=Zepto),function(a){function m(a){return a._zid||(a._zid=c++)}function n(a,b,c,d){b=o(b);if(b.ns)var e=p(b.ns);return(h[m(a)]||[]).filter(function(a){return a&&(!b.e||a.e==b.e)&&(!b.ns||e.test(a.ns))&&(!c||m(a.fn)===m(c))&&(!d||a.sel==d)})}function o(a){var b=(""+a).split(".");return{e:b[0],ns:b.slice(1).sort().join(" ")}}function p(a){return new RegExp("(?:^| )"+a.replace(" "," .* ?")+"(?: |$)")}function q(a,b){return a.del&&!j&&a.e in k||!!b}function r(a){return l[a]||j&&k[a]||a}function s(b,c,e,f,g,i,j){var k=m(b),n=h[k]||(h[k]=[]);c.split(/\s/).forEach(function(c){if(c=="ready")return a(document).ready(e);var h=o(c);h.fn=e,h.sel=g,h.e in l&&(e=function(b){var c=b.relatedTarget;if(!c||c!==this&&!a.contains(this,c))return h.fn.apply(this,arguments)}),h.del=i;var k=i||e;h.proxy=function(a){a=y(a);if(a.isImmediatePropagationStopped())return;a.data=f;var c=k.apply(b,a._args==d?[a]:[a].concat(a._args));return c===!1&&(a.preventDefault(),a.stopPropagation()),c},h.i=n.length,n.push(h),"addEventListener"in b&&b.addEventListener(r(h.e),h.proxy,q(h,j))})}function t(a,b,c,d,e){var f=m(a);(b||"").split(/\s/).forEach(function(b){n(a,b,c,d).forEach(function(b){delete h[f][b.i],"removeEventListener"in a&&a.removeEventListener(r(b.e),b.proxy,q(b,e))})})}function y(b,c){if(c||!b.isDefaultPrevented){c||(c=b),a.each(x,function(a,d){var e=c[a];b[a]=function(){return this[d]=u,e&&e.apply(c,arguments)},b[d]=v});if(c.defaultPrevented!==d?c.defaultPrevented:"returnValue"in c?c.returnValue===!1:c.getPreventDefault&&c.getPreventDefault())b.isDefaultPrevented=u}return b}function z(a){var b,c={originalEvent:a};for(b in a)!w.test(b)&&a[b]!==d&&(c[b]=a[b]);return y(c,a)}var b=a.zepto.qsa,c=1,d,e=Array.prototype.slice,f=a.isFunction,g=function(a){return typeof a=="string"},h={},i={},j="onfocusin"in window,k={focus:"focusin",blur:"focusout"},l={mouseenter:"mouseover",mouseleave:"mouseout"};i.click=i.mousedown=i.mouseup=i.mousemove="MouseEvents",a.event={add:s,remove:t},a.proxy=function(b,c){if(f(b)){var d=function(){return b.apply(c,arguments)};return d._zid=m(b),d}if(g(c))return a.proxy(b[c],b);throw new TypeError("expected function")},a.fn.bind=function(a,b,c){return this.on(a,b,c)},a.fn.unbind=function(a,b){return this.off(a,b)},a.fn.one=function(a,b,c,d){return this.on(a,b,c,d,1)};var u=function(){return!0},v=function(){return!1},w=/^([A-Z]|returnValue$|layer[XY]$)/,x={preventDefault:"isDefaultPrevented",stopImmediatePropagation:"isImmediatePropagationStopped",stopPropagation:"isPropagationStopped"};a.fn.delegate=function(a,b,c){return this.on(b,a,c)},a.fn.undelegate=function(a,b,c){return this.off(b,a,c)},a.fn.live=function(b,c){return a(document.body).delegate(this.selector,b,c),this},a.fn.die=function(b,c){return a(document.body).undelegate(this.selector,b,c),this},a.fn.on=function(b,c,h,i,j){var k,l,m=this;if(b&&!g(b))return a.each(b,function(a,b){m.on(a,c,h,b,j)}),m;!g(c)&&!f(i)&&i!==!1&&(i=h,h=c,c=d);if(f(h)||h===!1)i=h,h=d;return i===!1&&(i=v),m.each(function(d,f){j&&(k=function(a){return t(f,a.type,i),i.apply(this,arguments)}),c&&(l=function(b){var d,g=a(b.target).closest(c,f).get(0);if(g&&g!==f)return d=a.extend(z(b),{currentTarget:g,liveFired:f}),(k||i).apply(g,[d].concat(e.call(arguments,1)))}),s(f,b,i,h,c,l||k)})},a.fn.off=function(b,c,e){var h=this;return b&&!g(b)?(a.each(b,function(a,b){h.off(a,c,b)}),h):(!g(c)&&!f(e)&&e!==!1&&(e=c,c=d),e===!1&&(e=v),h.each(function(){t(this,b,e,c)}))},a.fn.trigger=function(b,c){return b=g(b)||a.isPlainObject(b)?a.Event(b):y(b),b._args=c,this.each(function(){"dispatchEvent"in this?this.dispatchEvent(b):a(this).triggerHandler(b,c)})},a.fn.triggerHandler=function(b,c){var d,e;return this.each(function(f,h){d=z(g(b)?a.Event(b):b),d._args=c,d.target=h,a.each(n(h,b.type||b),function(a,b){e=b.proxy(d);if(d.isImmediatePropagationStopped())return!1})}),e},"focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select keydown keypress keyup error".split(" ").forEach(function(b){a.fn[b]=function(a){return a?this.bind(b,a):this.trigger(b)}}),["focus","blur"].forEach(function(b){a.fn[b]=function(a){return a?this.bind(b,a):this.each(function(){try{this[b]()}catch(a){}}),this}}),a.Event=function(a,b){g(a)||(b=a,a=b.type);var c=document.createEvent(i[a]||"Events"),d=!0;if(b)for(var e in b)e=="bubbles"?d=!!b[e]:c[e]=b[e];return c.initEvent(a,d,!0),y(c)}}(Zepto),function($){function triggerAndReturn(a,b,c){var d=$.Event(b);return $(a).trigger(d,c),!d.isDefaultPrevented()}function triggerGlobal(a,b,c,d){if(a.global)return triggerAndReturn(b||document,c,d)}function ajaxStart(a){a.global&&$.active++===0&&triggerGlobal(a,null,"ajaxStart")}function ajaxStop(a){a.global&&!--$.active&&triggerGlobal(a,null,"ajaxStop")}function ajaxBeforeSend(a,b){var c=b.context;if(b.beforeSend.call(c,a,b)===!1||triggerGlobal(b,c,"ajaxBeforeSend",[a,b])===!1)return!1;triggerGlobal(b,c,"ajaxSend",[a,b])}function ajaxSuccess(a,b,c,d){var e=c.context,f="success";c.success.call(e,a,f,b),d&&d.resolveWith(e,[a,f,b]),triggerGlobal(c,e,"ajaxSuccess",[b,c,a]),ajaxComplete(f,b,c)}function ajaxError(a,b,c,d,e){var f=d.context;d.error.call(f,c,b,a),e&&e.rejectWith(f,[c,b,a]),triggerGlobal(d,f,"ajaxError",[c,d,a||b]),ajaxComplete(b,c,d)}function ajaxComplete(a,b,c){var d=c.context;c.complete.call(d,b,a),triggerGlobal(c,d,"ajaxComplete",[b,c]),ajaxStop(c)}function empty(){}function mimeToDataType(a){return a&&(a=a.split(";",2)[0]),a&&(a==htmlType?"html":a==jsonType?"json":scriptTypeRE.test(a)?"script":xmlTypeRE.test(a)&&"xml")||"text"}function appendQuery(a,b){return b==""?a:(a+"&"+b).replace(/[&?]{1,2}/,"?")}function serializeData(a){a.processData&&a.data&&$.type(a.data)!="string"&&(a.data=$.param(a.data,a.traditional)),a.data&&(!a.type||a.type.toUpperCase()=="GET")&&(a.url=appendQuery(a.url,a.data),a.data=undefined)}function parseArguments(a,b,c,d){var e=!$.isFunction(b);return{url:a,data:e?b:undefined,success:e?$.isFunction(c)?c:undefined:b,dataType:e?d||c:c}}function serialize(a,b,c,d){var e,f=$.isArray(b),g=$.isPlainObject(b);$.each(b,function(b,h){e=$.type(h),d&&(b=c?d:d+"["+(g||e=="object"||e=="array"?b:"")+"]"),!d&&f?a.add(h.name,h.value):e=="array"||!c&&e=="object"?serialize(a,h,c,b):a.add(b,h)})}var jsonpID=0,document=window.document,key,name,rscript=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,scriptTypeRE=/^(?:text|application)\/javascript/i,xmlTypeRE=/^(?:text|application)\/xml/i,jsonType="application/json",htmlType="text/html",blankRE=/^\s*$/;$.active=0,$.ajaxJSONP=function(a,b){if("type"in a){var c=a.jsonpCallback,d=($.isFunction(c)?c():c)||"jsonp"+ ++jsonpID,e=document.createElement("script"),f=window[d],g,h=function(a){$(e).triggerHandler("error",a||"abort")},i={abort:h},j;return b&&b.promise(i),$(e).on("load error",function(c,h){clearTimeout(j),$(e).off().remove(),c.type=="error"||!g?ajaxError(null,h||"error",i,a,b):ajaxSuccess(g[0],i,a,b),window[d]=f,g&&$.isFunction(f)&&f(g[0]),f=g=undefined}),ajaxBeforeSend(i,a)===!1?(h("abort"),i):(window[d]=function(){g=arguments},e.src=a.url.replace(/=\?/,"="+d),document.head.appendChild(e),a.timeout>0&&(j=setTimeout(function(){h("timeout")},a.timeout)),i)}return $.ajax(a)},$.ajaxSettings={type:"GET",beforeSend:empty,success:empty,error:empty,complete:empty,context:null,global:!0,xhr:function(){return new window.XMLHttpRequest},accepts:{script:"text/javascript, application/javascript, application/x-javascript",json:jsonType,xml:"application/xml, text/xml",html:htmlType,text:"text/plain"},crossDomain:!1,timeout:0,processData:!0,cache:!0},$.ajax=function(options){var settings=$.extend({},options||{}),deferred=$.Deferred&&$.Deferred();for(key in $.ajaxSettings)settings[key]===undefined&&(settings[key]=$.ajaxSettings[key]);ajaxStart(settings),settings.crossDomain||(settings.crossDomain=/^([\w-]+:)?\/\/([^\/]+)/.test(settings.url)&&RegExp.$2!=window.location.host),settings.url||(settings.url=window.location.toString()),serializeData(settings),settings.cache===!1&&(settings.url=appendQuery(settings.url,"_="+Date.now()));var dataType=settings.dataType,hasPlaceholder=/=\?/.test(settings.url);if(dataType=="jsonp"||hasPlaceholder)return hasPlaceholder||(settings.url=appendQuery(settings.url,settings.jsonp?settings.jsonp+"=?":settings.jsonp===!1?"":"callback=?")),$.ajaxJSONP(settings,deferred);var mime=settings.accepts[dataType],headers={},setHeader=function(a,b){headers[a.toLowerCase()]=[a,b]},protocol=/^([\w-]+:)\/\//.test(settings.url)?RegExp.$1:window.location.protocol,xhr=settings.xhr(),nativeSetHeader=xhr.setRequestHeader,abortTimeout;deferred&&deferred.promise(xhr),settings.crossDomain||setHeader("X-Requested-With","XMLHttpRequest"),setHeader("Accept",mime||"*/*");if(mime=settings.mimeType||mime)mime.indexOf(",")>-1&&(mime=mime.split(",",2)[0]),xhr.overrideMimeType&&xhr.overrideMimeType(mime);(settings.contentType||settings.contentType!==!1&&settings.data&&settings.type.toUpperCase()!="GET")&&setHeader("Content-Type",settings.contentType||"application/x-www-form-urlencoded");if(settings.headers)for(name in settings.headers)setHeader(name,settings.headers[name]);xhr.setRequestHeader=setHeader,xhr.onreadystatechange=function(){if(xhr.readyState==4){xhr.onreadystatechange=empty,clearTimeout(abortTimeout);var result,error=!1;if(xhr.status>=200&&xhr.status<300||xhr.status==304||xhr.status==0&&protocol=="file:"){dataType=dataType||mimeToDataType(settings.mimeType||xhr.getResponseHeader("content-type")),result=xhr.responseText;try{dataType=="script"?(1,eval)(result):dataType=="xml"?result=xhr.responseXML:dataType=="json"&&(result=blankRE.test(result)?null:$.parseJSON(result))}catch(e){error=e}error?ajaxError(error,"parsererror",xhr,settings,deferred):ajaxSuccess(result,xhr,settings,deferred)}else ajaxError(xhr.statusText||null,xhr.status?"error":"abort",xhr,settings,deferred)}};if(ajaxBeforeSend(xhr,settings)===!1)return xhr.abort(),ajaxError(null,"abort",xhr,settings,deferred),xhr;if(settings.xhrFields)for(name in settings.xhrFields)xhr[name]=settings.xhrFields[name];var async="async"in settings?settings.async:!0;xhr.open(settings.type,settings.url,async,settings.username,settings.password);for(name in headers)nativeSetHeader.apply(xhr,headers[name]);return settings.timeout>0&&(abortTimeout=setTimeout(function(){xhr.onreadystatechange=empty,xhr.abort(),ajaxError(null,"timeout",xhr,settings,deferred)},settings.timeout)),xhr.send(settings.data?settings.data:null),xhr},$.get=function(a,b,c,d){return $.ajax(parseArguments.apply(null,arguments))},$.post=function(a,b,c,d){var e=parseArguments.apply(null,arguments);return e.type="POST",$.ajax(e)},$.getJSON=function(a,b,c){var d=parseArguments.apply(null,arguments);return d.dataType="json",$.ajax(d)},$.fn.load=function(a,b,c){if(!this.length)return this;var d=this,e=a.split(/\s/),f,g=parseArguments(a,b,c),h=g.success;return e.length>1&&(g.url=e[0],f=e[1]),g.success=function(a){d.html(f?$("<div>").html(a.replace(rscript,"")).find(f):a),h&&h.apply(d,arguments)},$.ajax(g),this};var escape=encodeURIComponent;$.param=function(a,b){var c=[];return c.add=function(a,b){this.push(escape(a)+"="+escape(b))},serialize(c,a,b),c.join("&").replace(/%20/g,"+")}}(Zepto),function(a){a.fn.serializeArray=function(){var b=[],c;return a([].slice.call(this.get(0).elements)).each(function(){c=a(this);var d=c.attr("type");this.nodeName.toLowerCase()!="fieldset"&&!this.disabled&&d!="submit"&&d!="reset"&&d!="button"&&(d!="radio"&&d!="checkbox"||this.checked)&&b.push({name:c.attr("name"),value:c.val()})}),b},a.fn.serialize=function(){var a=[];return this.serializeArray().forEach(function(b){a.push(encodeURIComponent(b.name)+"="+encodeURIComponent(b.value))}),a.join("&")},a.fn.submit=function(b){if(b)this.bind("submit",b);else if(this.length){var c=a.Event("submit");this.eq(0).trigger(c),c.isDefaultPrevented()||this.get(0).submit()}return this}}(Zepto),function(a){"__proto__"in{}||a.extend(a.zepto,{Z:function(b,c){return b=b||[],a.extend(b,a.fn),b.selector=c||"",b.__Z=!0,b},isZ:function(b){return a.type(b)==="array"&&"__Z"in b}});try{getComputedStyle(undefined)}catch(b){var c=getComputedStyle;window.getComputedStyle=function(a){try{return c(a)}catch(b){return null}}}}(Zepto) </script> <style type="text/css"> body { background: #F9F9F9; font-size: 14px; line-height: 22px; font-family: Helvetica Neue, Helvetica, Arial; } a { color: #000; text-decoration: underline; } li ul, li ol{ margin: 0; } .anchor { cursor: pointer; } .anchor .anchor_char{ visibility: hidden; padding-left: 0.2em; font-size: 0.9em; opacity: 0.5; } .anchor:hover .anchor_char{ visibility: visible; } .sidebar{ background: #FFF; position: fixed; z-index: 10; top: 0; left: 0; bottom: 0; width: 230px; overflow-y: auto; overflow-x: hidden; padding: 15px 0 30px 30px; border-right: 1px solid #bbb; font-family: "Lucida Grande", "Lucida Sans Unicode", Helvetica, Arial, sans-serif !important; } .sidebar ul{ margin: 0; list-style: none; padding: 0; } .sidebar ul a:hover { text-decoration: underline; color: #333; } .sidebar > ul > li { margin-top: 15px; } .sidebar > ul > li > a { font-weight: bold; } .sidebar ul ul { margin-top: 5px; font-size: 11px; line-height: 14px; } .sidebar ul ul li:before { content: "- "; } .sidebar ul ul li { margin-bottom: 3px; } .sidebar ul ul li a { text-decoration: none; } .toggle_sidebar_button{ display: none; position: fixed; z-index: 11; top: 0; width: 44px; height: 44px; background: #000; background: rgba(0,0,0,0.7); margin-left: 230px; } .toggle_sidebar_button:hover { background: rgba(0,0,0,1); cursor: pointer; } .toggle_sidebar_button .line{ height: 2px; width: 21px; margin-left: 11px; margin-top: 5px; background: #FFF; } .toggle_sidebar_button .line:first-child { margin-top: 15px; } .main_container { width: 100%; padding-left: 260px; margin: 30px; margin-left: 0px; padding-right: 30px; } .main_container p, ul{ margin: 25px 0; } .main_container ul { list-style: circle; font-size: 13px; line-height: 18px; padding-left: 15px; } pre { font-size: 12px; border: 4px solid #bbb; border-top: 0; border-bottom: 0; margin: 0px 0 25px; padding-top: 0px; padding-bottom: 0px; font-family: Monaco, Consolas, "Lucida Console", monospace; line-height: 18px; font-style: normal; background: none; border-radius: 0px; overflow-x: scroll; word-wrap: normal; white-space: pre; } .main_container { width: 840px; } .main_container p, ul, pre { width: 100%; } code { padding: 0px 3px; color: #333; background: #fff; border: 1px solid #ddd; zoom: 1; white-space: nowrap; border-radius: 0; font-family: Monaco, Consolas, "Lucida Console", monospace; font-size: 12px; line-height: 18px; font-style: normal; } em { font-size: 12px; line-height: 18px; } @media (max-width: 820px) { .sidebar { display: none; } .main_container { padding: 0px; width: 100%; } .main_container > *{ padding-left: 10px; padding-right: 10px; } .main_container > ul, .main_container > ol { padding-left: 27px; } .force_show_sidebar .main_container { display: none; } .force_show_sidebar .sidebar { width: 100%; } .force_show_sidebar .sidebar a{ font-size: 1.5em; line-height: 1.5em; } .force_show_sidebar .toggle_sidebar_button { right: 0; } .force_show_sidebar .toggle_sidebar_button .line:first-child, .force_show_sidebar .toggle_sidebar_button .line:last-child { visibility: hidden; } .toggle_sidebar_button { margin-left: 0px; display: block; } pre { font-size: 12px; border: 1px solid #bbb; border-left: 0; border-right: 0; padding: 9px; background: #FFF; } code { word-wrap: break-word; white-space: normal; } } .force_show_sidebar .sidebar { display: block; } .force_show_sidebar .main_container { padding-left: 260px; } .force_show_sidebar .toggle_sidebar_button{ margin-left: 230px; } </style> <script type="text/javascript"> $(function(){ $('.toggle_sidebar_button').on('click', function(){ $('body').toggleClass('force_show_sidebar'); }); // hide sidebar on every click in menu (if small screen) $('.sidebar').find('a').on('click', function(){ $('body').removeClass('force_show_sidebar'); }); // add anchors $.each($('.main_container').find('h1,h2,h3,h4,h5,h6'), function(key, item){ if ($(item).attr('id')) { $(item).addClass('anchor'); $(item).append($('<span class="anchor_char">¶</span>')) $(item).on('click', function(){ window.location = '#' + $(item).attr('id'); }) } }); // remove <code> tag inside of <pre> $.each($('pre > code'), function(key, item){ $(item).parent().html($(item).html()) }) }) </script> </head> <body> <a class="toggle_sidebar_button"> <div class="line"></div> <div class="line"></div> <div class="line"></div> </a> <div class="sidebar"> <!-- toc --> </div> <div class="main_container"> <!-- main_content --> </div> </body> </html>''' def force_text(text): if isinstance(text, unicode): return text else: return text.decode('utf-8') class BackDoc(object): def __init__(self, markdown_converter, template_html, stdin, stdout): self.markdown_converter = markdown_converter self.template_html = force_text(template_html) self.stdin = stdin self.stdout = stdout self.parser = self.get_parser() def run(self, argv): kwargs = self.get_kwargs(argv) self.stdout.write(self.get_result_html(**kwargs)) def get_kwargs(self, argv): parsed = dict(self.parser.parse_args(argv)._get_kwargs()) return self.prepare_kwargs_from_parsed_data(parsed) def prepare_kwargs_from_parsed_data(self, parsed): kwargs = {} kwargs['title'] = force_text(parsed.get('title') or 'Documentation') if parsed.get('source'): kwargs['markdown_src'] = open(parsed['source'], 'r').read() else: kwargs['markdown_src'] = self.stdin.read() kwargs['markdown_src'] = force_text(kwargs['markdown_src'] or '') return kwargs def get_result_html(self, title, markdown_src): response = self.get_converted_to_html_response(markdown_src) return ( self.template_html.replace('<!-- title -->', title) .replace('<!-- toc -->', response.toc_html and force_text(response.toc_html) or '') .replace('<!-- main_content -->', force_text(response)) ) def get_converted_to_html_response(self, markdown_src): return self.markdown_converter.convert(markdown_src) def get_parser(self): parser = argparse.ArgumentParser() parser.add_argument( '-t', '--title', help='Documentation title header', required=False, ) parser.add_argument( '-s', '--source', help='Markdown source file path', required=False, ) return parser if __name__ == '__main__': BackDoc( markdown_converter=Markdown(extras=['toc']), template_html=template_html, stdin=sys.stdin, stdout=sys.stdout ).run(argv=sys.argv[1:])
chibisov/drf-extensions
docs/backdoc.py
_dedent
python
def _dedent(text, tabsize=8, skip_first_line=False): lines = text.splitlines(1) _dedentlines(lines, tabsize=tabsize, skip_first_line=skip_first_line) return ''.join(lines)
_dedent(text, tabsize=8, skip_first_line=False) -> dedented text "text" is the text to dedent. "tabsize" is the tab width to use for indent width calculations. "skip_first_line" is a boolean indicating if the first line should be skipped for calculating the indent width and for dedenting. This is sometimes useful for docstrings and similar. textwrap.dedent(s), but don't expand tabs to spaces
train
https://github.com/chibisov/drf-extensions/blob/1d28a4b28890eab5cd19e93e042f8590c8c2fb8b/docs/backdoc.py#L2082-L2095
null
# -*- coding: utf-8 -*- #!/usr/bin/env python """ Backdoc is a tool for backbone-like documentation generation. Backdoc main goal is to help to generate one page documentation from one markdown source file. https://github.com/chibisov/backdoc """ import sys import argparse # -*- coding: utf-8 -*- #!/usr/bin/env python # Copyright (c) 2012 Trent Mick. # Copyright (c) 2007-2008 ActiveState Corp. # License: MIT (http://www.opensource.org/licenses/mit-license.php) r"""A fast and complete Python implementation of Markdown. [from http://daringfireball.net/projects/markdown/] > Markdown is a text-to-HTML filter; it translates an easy-to-read / > easy-to-write structured text format into HTML. Markdown's text > format is most similar to that of plain text email, and supports > features such as headers, *emphasis*, code blocks, blockquotes, and > links. > > Markdown's syntax is designed not as a generic markup language, but > specifically to serve as a front-end to (X)HTML. You can use span-level > HTML tags anywhere in a Markdown document, and you can use block level > HTML tags (like <div> and <table> as well). Module usage: >>> import markdown2 >>> markdown2.markdown("*boo!*") # or use `html = markdown_path(PATH)` u'<p><em>boo!</em></p>\n' >>> markdowner = Markdown() >>> markdowner.convert("*boo!*") u'<p><em>boo!</em></p>\n' >>> markdowner.convert("**boom!**") u'<p><strong>boom!</strong></p>\n' This implementation of Markdown implements the full "core" syntax plus a number of extras (e.g., code syntax coloring, footnotes) as described on <https://github.com/trentm/python-markdown2/wiki/Extras>. """ cmdln_desc = """A fast and complete Python implementation of Markdown, a text-to-HTML conversion tool for web writers. Supported extra syntax options (see -x|--extras option below and see <https://github.com/trentm/python-markdown2/wiki/Extras> for details): * code-friendly: Disable _ and __ for em and strong. * cuddled-lists: Allow lists to be cuddled to the preceding paragraph. * fenced-code-blocks: Allows a code block to not have to be indented by fencing it with '```' on a line before and after. Based on <http://github.github.com/github-flavored-markdown/> with support for syntax highlighting. * footnotes: Support footnotes as in use on daringfireball.net and implemented in other Markdown processors (tho not in Markdown.pl v1.0.1). * header-ids: Adds "id" attributes to headers. The id value is a slug of the header text. * html-classes: Takes a dict mapping html tag names (lowercase) to a string to use for a "class" tag attribute. Currently only supports "pre" and "code" tags. Add an issue if you require this for other tags. * markdown-in-html: Allow the use of `markdown="1"` in a block HTML tag to have markdown processing be done on its contents. Similar to <http://michelf.com/projects/php-markdown/extra/#markdown-attr> but with some limitations. * metadata: Extract metadata from a leading '---'-fenced block. See <https://github.com/trentm/python-markdown2/issues/77> for details. * nofollow: Add `rel="nofollow"` to add `<a>` tags with an href. See <http://en.wikipedia.org/wiki/Nofollow>. * pyshell: Treats unindented Python interactive shell sessions as <code> blocks. * link-patterns: Auto-link given regex patterns in text (e.g. bug number references, revision number references). * smarty-pants: Replaces ' and " with curly quotation marks or curly apostrophes. Replaces --, ---, ..., and . . . with en dashes, em dashes, and ellipses. * toc: The returned HTML string gets a new "toc_html" attribute which is a Table of Contents for the document. (experimental) * xml: Passes one-liner processing instructions and namespaced XML tags. * wiki-tables: Google Code Wiki-style tables. See <http://code.google.com/p/support/wiki/WikiSyntax#Tables>. """ # Dev Notes: # - Python's regex syntax doesn't have '\z', so I'm using '\Z'. I'm # not yet sure if there implications with this. Compare 'pydoc sre' # and 'perldoc perlre'. __version_info__ = (2, 1, 1) __version__ = '.'.join(map(str, __version_info__)) __author__ = "Trent Mick" import os import sys from pprint import pprint import re import logging try: from hashlib import md5 except ImportError: from md5 import md5 import optparse from random import random, randint import codecs #---- Python version compat try: from urllib.parse import quote # python3 except ImportError: from urllib import quote # python2 if sys.version_info[:2] < (2,4): from sets import Set as set def reversed(sequence): for i in sequence[::-1]: yield i # Use `bytes` for byte strings and `unicode` for unicode strings (str in Py3). if sys.version_info[0] <= 2: py3 = False try: bytes except NameError: bytes = str base_string_type = basestring elif sys.version_info[0] >= 3: py3 = True unicode = str base_string_type = str #---- globals DEBUG = False log = logging.getLogger("markdown") DEFAULT_TAB_WIDTH = 4 SECRET_SALT = bytes(randint(0, 1000000)) def _hash_text(s): return 'md5-' + md5(SECRET_SALT + s.encode("utf-8")).hexdigest() # Table of hash values for escaped characters: g_escape_table = dict([(ch, _hash_text(ch)) for ch in '\\`*_{}[]()>#+-.!']) #---- exceptions class MarkdownError(Exception): pass #---- public api def markdown_path(path, encoding="utf-8", html4tags=False, tab_width=DEFAULT_TAB_WIDTH, safe_mode=None, extras=None, link_patterns=None, use_file_vars=False): fp = codecs.open(path, 'r', encoding) text = fp.read() fp.close() return Markdown(html4tags=html4tags, tab_width=tab_width, safe_mode=safe_mode, extras=extras, link_patterns=link_patterns, use_file_vars=use_file_vars).convert(text) def markdown(text, html4tags=False, tab_width=DEFAULT_TAB_WIDTH, safe_mode=None, extras=None, link_patterns=None, use_file_vars=False): return Markdown(html4tags=html4tags, tab_width=tab_width, safe_mode=safe_mode, extras=extras, link_patterns=link_patterns, use_file_vars=use_file_vars).convert(text) class Markdown(object): # The dict of "extras" to enable in processing -- a mapping of # extra name to argument for the extra. Most extras do not have an # argument, in which case the value is None. # # This can be set via (a) subclassing and (b) the constructor # "extras" argument. extras = None urls = None titles = None html_blocks = None html_spans = None html_removed_text = "[HTML_REMOVED]" # for compat with markdown.py # Used to track when we're inside an ordered or unordered list # (see _ProcessListItems() for details): list_level = 0 _ws_only_line_re = re.compile(r"^[ \t]+$", re.M) def __init__(self, html4tags=False, tab_width=4, safe_mode=None, extras=None, link_patterns=None, use_file_vars=False): if html4tags: self.empty_element_suffix = ">" else: self.empty_element_suffix = " />" self.tab_width = tab_width # For compatibility with earlier markdown2.py and with # markdown.py's safe_mode being a boolean, # safe_mode == True -> "replace" if safe_mode is True: self.safe_mode = "replace" else: self.safe_mode = safe_mode # Massaging and building the "extras" info. if self.extras is None: self.extras = {} elif not isinstance(self.extras, dict): self.extras = dict([(e, None) for e in self.extras]) if extras: if not isinstance(extras, dict): extras = dict([(e, None) for e in extras]) self.extras.update(extras) assert isinstance(self.extras, dict) if "toc" in self.extras and not "header-ids" in self.extras: self.extras["header-ids"] = None # "toc" implies "header-ids" self._instance_extras = self.extras.copy() self.link_patterns = link_patterns self.use_file_vars = use_file_vars self._outdent_re = re.compile(r'^(\t|[ ]{1,%d})' % tab_width, re.M) self._escape_table = g_escape_table.copy() if "smarty-pants" in self.extras: self._escape_table['"'] = _hash_text('"') self._escape_table["'"] = _hash_text("'") def reset(self): self.urls = {} self.titles = {} self.html_blocks = {} self.html_spans = {} self.list_level = 0 self.extras = self._instance_extras.copy() if "footnotes" in self.extras: self.footnotes = {} self.footnote_ids = [] if "header-ids" in self.extras: self._count_from_header_id = {} # no `defaultdict` in Python 2.4 if "metadata" in self.extras: self.metadata = {} # Per <https://developer.mozilla.org/en-US/docs/HTML/Element/a> "rel" # should only be used in <a> tags with an "href" attribute. _a_nofollow = re.compile(r"<(a)([^>]*href=)", re.IGNORECASE) def convert(self, text): """Convert the given text.""" # Main function. The order in which other subs are called here is # essential. Link and image substitutions need to happen before # _EscapeSpecialChars(), so that any *'s or _'s in the <a> # and <img> tags get encoded. # Clear the global hashes. If we don't clear these, you get conflicts # from other articles when generating a page which contains more than # one article (e.g. an index page that shows the N most recent # articles): self.reset() if not isinstance(text, unicode): #TODO: perhaps shouldn't presume UTF-8 for string input? text = unicode(text, 'utf-8') if self.use_file_vars: # Look for emacs-style file variable hints. emacs_vars = self._get_emacs_vars(text) if "markdown-extras" in emacs_vars: splitter = re.compile("[ ,]+") for e in splitter.split(emacs_vars["markdown-extras"]): if '=' in e: ename, earg = e.split('=', 1) try: earg = int(earg) except ValueError: pass else: ename, earg = e, None self.extras[ename] = earg # Standardize line endings: text = re.sub("\r\n|\r", "\n", text) # Make sure $text ends with a couple of newlines: text += "\n\n" # Convert all tabs to spaces. text = self._detab(text) # Strip any lines consisting only of spaces and tabs. # This makes subsequent regexen easier to write, because we can # match consecutive blank lines with /\n+/ instead of something # contorted like /[ \t]*\n+/ . text = self._ws_only_line_re.sub("", text) # strip metadata from head and extract if "metadata" in self.extras: text = self._extract_metadata(text) text = self.preprocess(text) if self.safe_mode: text = self._hash_html_spans(text) # Turn block-level HTML blocks into hash entries text = self._hash_html_blocks(text, raw=True) # Strip link definitions, store in hashes. if "footnotes" in self.extras: # Must do footnotes first because an unlucky footnote defn # looks like a link defn: # [^4]: this "looks like a link defn" text = self._strip_footnote_definitions(text) text = self._strip_link_definitions(text) text = self._run_block_gamut(text) if "footnotes" in self.extras: text = self._add_footnotes(text) text = self.postprocess(text) text = self._unescape_special_chars(text) if self.safe_mode: text = self._unhash_html_spans(text) if "nofollow" in self.extras: text = self._a_nofollow.sub(r'<\1 rel="nofollow"\2', text) text += "\n" rv = UnicodeWithAttrs(text) if "toc" in self.extras: rv._toc = self._toc if "metadata" in self.extras: rv.metadata = self.metadata return rv def postprocess(self, text): """A hook for subclasses to do some postprocessing of the html, if desired. This is called before unescaping of special chars and unhashing of raw HTML spans. """ return text def preprocess(self, text): """A hook for subclasses to do some preprocessing of the Markdown, if desired. This is called after basic formatting of the text, but prior to any extras, safe mode, etc. processing. """ return text # Is metadata if the content starts with '---'-fenced `key: value` # pairs. E.g. (indented for presentation): # --- # foo: bar # another-var: blah blah # --- _metadata_pat = re.compile("""^---[ \t]*\n((?:[ \t]*[^ \t:]+[ \t]*:[^\n]*\n)+)---[ \t]*\n""") def _extract_metadata(self, text): # fast test if not text.startswith("---"): return text match = self._metadata_pat.match(text) if not match: return text tail = text[len(match.group(0)):] metadata_str = match.group(1).strip() for line in metadata_str.split('\n'): key, value = line.split(':', 1) self.metadata[key.strip()] = value.strip() return tail _emacs_oneliner_vars_pat = re.compile(r"-\*-\s*([^\r\n]*?)\s*-\*-", re.UNICODE) # This regular expression is intended to match blocks like this: # PREFIX Local Variables: SUFFIX # PREFIX mode: Tcl SUFFIX # PREFIX End: SUFFIX # Some notes: # - "[ \t]" is used instead of "\s" to specifically exclude newlines # - "(\r\n|\n|\r)" is used instead of "$" because the sre engine does # not like anything other than Unix-style line terminators. _emacs_local_vars_pat = re.compile(r"""^ (?P<prefix>(?:[^\r\n|\n|\r])*?) [\ \t]*Local\ Variables:[\ \t]* (?P<suffix>.*?)(?:\r\n|\n|\r) (?P<content>.*?\1End:) """, re.IGNORECASE | re.MULTILINE | re.DOTALL | re.VERBOSE) def _get_emacs_vars(self, text): """Return a dictionary of emacs-style local variables. Parsing is done loosely according to this spec (and according to some in-practice deviations from this): http://www.gnu.org/software/emacs/manual/html_node/emacs/Specifying-File-Variables.html#Specifying-File-Variables """ emacs_vars = {} SIZE = pow(2, 13) # 8kB # Search near the start for a '-*-'-style one-liner of variables. head = text[:SIZE] if "-*-" in head: match = self._emacs_oneliner_vars_pat.search(head) if match: emacs_vars_str = match.group(1) assert '\n' not in emacs_vars_str emacs_var_strs = [s.strip() for s in emacs_vars_str.split(';') if s.strip()] if len(emacs_var_strs) == 1 and ':' not in emacs_var_strs[0]: # While not in the spec, this form is allowed by emacs: # -*- Tcl -*- # where the implied "variable" is "mode". This form # is only allowed if there are no other variables. emacs_vars["mode"] = emacs_var_strs[0].strip() else: for emacs_var_str in emacs_var_strs: try: variable, value = emacs_var_str.strip().split(':', 1) except ValueError: log.debug("emacs variables error: malformed -*- " "line: %r", emacs_var_str) continue # Lowercase the variable name because Emacs allows "Mode" # or "mode" or "MoDe", etc. emacs_vars[variable.lower()] = value.strip() tail = text[-SIZE:] if "Local Variables" in tail: match = self._emacs_local_vars_pat.search(tail) if match: prefix = match.group("prefix") suffix = match.group("suffix") lines = match.group("content").splitlines(0) #print "prefix=%r, suffix=%r, content=%r, lines: %s"\ # % (prefix, suffix, match.group("content"), lines) # Validate the Local Variables block: proper prefix and suffix # usage. for i, line in enumerate(lines): if not line.startswith(prefix): log.debug("emacs variables error: line '%s' " "does not use proper prefix '%s'" % (line, prefix)) return {} # Don't validate suffix on last line. Emacs doesn't care, # neither should we. if i != len(lines)-1 and not line.endswith(suffix): log.debug("emacs variables error: line '%s' " "does not use proper suffix '%s'" % (line, suffix)) return {} # Parse out one emacs var per line. continued_for = None for line in lines[:-1]: # no var on the last line ("PREFIX End:") if prefix: line = line[len(prefix):] # strip prefix if suffix: line = line[:-len(suffix)] # strip suffix line = line.strip() if continued_for: variable = continued_for if line.endswith('\\'): line = line[:-1].rstrip() else: continued_for = None emacs_vars[variable] += ' ' + line else: try: variable, value = line.split(':', 1) except ValueError: log.debug("local variables error: missing colon " "in local variables entry: '%s'" % line) continue # Do NOT lowercase the variable name, because Emacs only # allows "mode" (and not "Mode", "MoDe", etc.) in this block. value = value.strip() if value.endswith('\\'): value = value[:-1].rstrip() continued_for = variable else: continued_for = None emacs_vars[variable] = value # Unquote values. for var, val in list(emacs_vars.items()): if len(val) > 1 and (val.startswith('"') and val.endswith('"') or val.startswith('"') and val.endswith('"')): emacs_vars[var] = val[1:-1] return emacs_vars # Cribbed from a post by Bart Lateur: # <http://www.nntp.perl.org/group/perl.macperl.anyperl/154> _detab_re = re.compile(r'(.*?)\t', re.M) def _detab_sub(self, match): g1 = match.group(1) return g1 + (' ' * (self.tab_width - len(g1) % self.tab_width)) def _detab(self, text): r"""Remove (leading?) tabs from a file. >>> m = Markdown() >>> m._detab("\tfoo") ' foo' >>> m._detab(" \tfoo") ' foo' >>> m._detab("\t foo") ' foo' >>> m._detab(" foo") ' foo' >>> m._detab(" foo\n\tbar\tblam") ' foo\n bar blam' """ if '\t' not in text: return text return self._detab_re.subn(self._detab_sub, text)[0] # I broke out the html5 tags here and add them to _block_tags_a and # _block_tags_b. This way html5 tags are easy to keep track of. _html5tags = '|article|aside|header|hgroup|footer|nav|section|figure|figcaption' _block_tags_a = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del' _block_tags_a += _html5tags _strict_tag_block_re = re.compile(r""" ( # save in \1 ^ # start of line (with re.M) <(%s) # start tag = \2 \b # word break (.*\n)*? # any number of lines, minimally matching </\2> # the matching end tag [ \t]* # trailing spaces/tabs (?=\n+|\Z) # followed by a newline or end of document ) """ % _block_tags_a, re.X | re.M) _block_tags_b = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math' _block_tags_b += _html5tags _liberal_tag_block_re = re.compile(r""" ( # save in \1 ^ # start of line (with re.M) <(%s) # start tag = \2 \b # word break (.*\n)*? # any number of lines, minimally matching .*</\2> # the matching end tag [ \t]* # trailing spaces/tabs (?=\n+|\Z) # followed by a newline or end of document ) """ % _block_tags_b, re.X | re.M) _html_markdown_attr_re = re.compile( r'''\s+markdown=("1"|'1')''') def _hash_html_block_sub(self, match, raw=False): html = match.group(1) if raw and self.safe_mode: html = self._sanitize_html(html) elif 'markdown-in-html' in self.extras and 'markdown=' in html: first_line = html.split('\n', 1)[0] m = self._html_markdown_attr_re.search(first_line) if m: lines = html.split('\n') middle = '\n'.join(lines[1:-1]) last_line = lines[-1] first_line = first_line[:m.start()] + first_line[m.end():] f_key = _hash_text(first_line) self.html_blocks[f_key] = first_line l_key = _hash_text(last_line) self.html_blocks[l_key] = last_line return ''.join(["\n\n", f_key, "\n\n", middle, "\n\n", l_key, "\n\n"]) key = _hash_text(html) self.html_blocks[key] = html return "\n\n" + key + "\n\n" def _hash_html_blocks(self, text, raw=False): """Hashify HTML blocks We only want to do this for block-level HTML tags, such as headers, lists, and tables. That's because we still want to wrap <p>s around "paragraphs" that are wrapped in non-block-level tags, such as anchors, phrase emphasis, and spans. The list of tags we're looking for is hard-coded. @param raw {boolean} indicates if these are raw HTML blocks in the original source. It makes a difference in "safe" mode. """ if '<' not in text: return text # Pass `raw` value into our calls to self._hash_html_block_sub. hash_html_block_sub = _curry(self._hash_html_block_sub, raw=raw) # First, look for nested blocks, e.g.: # <div> # <div> # tags for inner block must be indented. # </div> # </div> # # The outermost tags must start at the left margin for this to match, and # the inner nested divs must be indented. # We need to do this before the next, more liberal match, because the next # match will start at the first `<div>` and stop at the first `</div>`. text = self._strict_tag_block_re.sub(hash_html_block_sub, text) # Now match more liberally, simply from `\n<tag>` to `</tag>\n` text = self._liberal_tag_block_re.sub(hash_html_block_sub, text) # Special case just for <hr />. It was easier to make a special # case than to make the other regex more complicated. if "<hr" in text: _hr_tag_re = _hr_tag_re_from_tab_width(self.tab_width) text = _hr_tag_re.sub(hash_html_block_sub, text) # Special case for standalone HTML comments: if "<!--" in text: start = 0 while True: # Delimiters for next comment block. try: start_idx = text.index("<!--", start) except ValueError: break try: end_idx = text.index("-->", start_idx) + 3 except ValueError: break # Start position for next comment block search. start = end_idx # Validate whitespace before comment. if start_idx: # - Up to `tab_width - 1` spaces before start_idx. for i in range(self.tab_width - 1): if text[start_idx - 1] != ' ': break start_idx -= 1 if start_idx == 0: break # - Must be preceded by 2 newlines or hit the start of # the document. if start_idx == 0: pass elif start_idx == 1 and text[0] == '\n': start_idx = 0 # to match minute detail of Markdown.pl regex elif text[start_idx-2:start_idx] == '\n\n': pass else: break # Validate whitespace after comment. # - Any number of spaces and tabs. while end_idx < len(text): if text[end_idx] not in ' \t': break end_idx += 1 # - Must be following by 2 newlines or hit end of text. if text[end_idx:end_idx+2] not in ('', '\n', '\n\n'): continue # Escape and hash (must match `_hash_html_block_sub`). html = text[start_idx:end_idx] if raw and self.safe_mode: html = self._sanitize_html(html) key = _hash_text(html) self.html_blocks[key] = html text = text[:start_idx] + "\n\n" + key + "\n\n" + text[end_idx:] if "xml" in self.extras: # Treat XML processing instructions and namespaced one-liner # tags as if they were block HTML tags. E.g., if standalone # (i.e. are their own paragraph), the following do not get # wrapped in a <p> tag: # <?foo bar?> # # <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="chapter_1.md"/> _xml_oneliner_re = _xml_oneliner_re_from_tab_width(self.tab_width) text = _xml_oneliner_re.sub(hash_html_block_sub, text) return text def _strip_link_definitions(self, text): # Strips link definitions from text, stores the URLs and titles in # hash references. less_than_tab = self.tab_width - 1 # Link defs are in the form: # [id]: url "optional title" _link_def_re = re.compile(r""" ^[ ]{0,%d}\[(.+)\]: # id = \1 [ \t]* \n? # maybe *one* newline [ \t]* <?(.+?)>? # url = \2 [ \t]* (?: \n? # maybe one newline [ \t]* (?<=\s) # lookbehind for whitespace ['"(] ([^\n]*) # title = \3 ['")] [ \t]* )? # title is optional (?:\n+|\Z) """ % less_than_tab, re.X | re.M | re.U) return _link_def_re.sub(self._extract_link_def_sub, text) def _extract_link_def_sub(self, match): id, url, title = match.groups() key = id.lower() # Link IDs are case-insensitive self.urls[key] = self._encode_amps_and_angles(url) if title: self.titles[key] = title return "" def _extract_footnote_def_sub(self, match): id, text = match.groups() text = _dedent(text, skip_first_line=not text.startswith('\n')).strip() normed_id = re.sub(r'\W', '-', id) # Ensure footnote text ends with a couple newlines (for some # block gamut matches). self.footnotes[normed_id] = text + "\n\n" return "" def _strip_footnote_definitions(self, text): """A footnote definition looks like this: [^note-id]: Text of the note. May include one or more indented paragraphs. Where, - The 'note-id' can be pretty much anything, though typically it is the number of the footnote. - The first paragraph may start on the next line, like so: [^note-id]: Text of the note. """ less_than_tab = self.tab_width - 1 footnote_def_re = re.compile(r''' ^[ ]{0,%d}\[\^(.+)\]: # id = \1 [ \t]* ( # footnote text = \2 # First line need not start with the spaces. (?:\s*.*\n+) (?: (?:[ ]{%d} | \t) # Subsequent lines must be indented. .*\n+ )* ) # Lookahead for non-space at line-start, or end of doc. (?:(?=^[ ]{0,%d}\S)|\Z) ''' % (less_than_tab, self.tab_width, self.tab_width), re.X | re.M) return footnote_def_re.sub(self._extract_footnote_def_sub, text) _hr_data = [ ('*', re.compile(r"^[ ]{0,3}\*(.*?)$", re.M)), ('-', re.compile(r"^[ ]{0,3}\-(.*?)$", re.M)), ('_', re.compile(r"^[ ]{0,3}\_(.*?)$", re.M)), ] def _run_block_gamut(self, text): # These are all the transformations that form block-level # tags like paragraphs, headers, and list items. if "fenced-code-blocks" in self.extras: text = self._do_fenced_code_blocks(text) text = self._do_headers(text) # Do Horizontal Rules: # On the number of spaces in horizontal rules: The spec is fuzzy: "If # you wish, you may use spaces between the hyphens or asterisks." # Markdown.pl 1.0.1's hr regexes limit the number of spaces between the # hr chars to one or two. We'll reproduce that limit here. hr = "\n<hr"+self.empty_element_suffix+"\n" for ch, regex in self._hr_data: if ch in text: for m in reversed(list(regex.finditer(text))): tail = m.group(1).rstrip() if not tail.strip(ch + ' ') and tail.count(" ") == 0: start, end = m.span() text = text[:start] + hr + text[end:] text = self._do_lists(text) if "pyshell" in self.extras: text = self._prepare_pyshell_blocks(text) if "wiki-tables" in self.extras: text = self._do_wiki_tables(text) text = self._do_code_blocks(text) text = self._do_block_quotes(text) # We already ran _HashHTMLBlocks() before, in Markdown(), but that # was to escape raw HTML in the original Markdown source. This time, # we're escaping the markup we've just created, so that we don't wrap # <p> tags around block-level tags. text = self._hash_html_blocks(text) text = self._form_paragraphs(text) return text def _pyshell_block_sub(self, match): lines = match.group(0).splitlines(0) _dedentlines(lines) indent = ' ' * self.tab_width s = ('\n' # separate from possible cuddled paragraph + indent + ('\n'+indent).join(lines) + '\n\n') return s def _prepare_pyshell_blocks(self, text): """Ensure that Python interactive shell sessions are put in code blocks -- even if not properly indented. """ if ">>>" not in text: return text less_than_tab = self.tab_width - 1 _pyshell_block_re = re.compile(r""" ^([ ]{0,%d})>>>[ ].*\n # first line ^(\1.*\S+.*\n)* # any number of subsequent lines ^\n # ends with a blank line """ % less_than_tab, re.M | re.X) return _pyshell_block_re.sub(self._pyshell_block_sub, text) def _wiki_table_sub(self, match): ttext = match.group(0).strip() #print 'wiki table: %r' % match.group(0) rows = [] for line in ttext.splitlines(0): line = line.strip()[2:-2].strip() row = [c.strip() for c in re.split(r'(?<!\\)\|\|', line)] rows.append(row) #pprint(rows) hlines = ['<table>', '<tbody>'] for row in rows: hrow = ['<tr>'] for cell in row: hrow.append('<td>') hrow.append(self._run_span_gamut(cell)) hrow.append('</td>') hrow.append('</tr>') hlines.append(''.join(hrow)) hlines += ['</tbody>', '</table>'] return '\n'.join(hlines) + '\n' def _do_wiki_tables(self, text): # Optimization. if "||" not in text: return text less_than_tab = self.tab_width - 1 wiki_table_re = re.compile(r''' (?:(?<=\n\n)|\A\n?) # leading blank line ^([ ]{0,%d})\|\|.+?\|\|[ ]*\n # first line (^\1\|\|.+?\|\|\n)* # any number of subsequent lines ''' % less_than_tab, re.M | re.X) return wiki_table_re.sub(self._wiki_table_sub, text) def _run_span_gamut(self, text): # These are all the transformations that occur *within* block-level # tags like paragraphs, headers, and list items. text = self._do_code_spans(text) text = self._escape_special_chars(text) # Process anchor and image tags. text = self._do_links(text) # Make links out of things like `<http://example.com/>` # Must come after _do_links(), because you can use < and > # delimiters in inline links like [this](<url>). text = self._do_auto_links(text) if "link-patterns" in self.extras: text = self._do_link_patterns(text) text = self._encode_amps_and_angles(text) text = self._do_italics_and_bold(text) if "smarty-pants" in self.extras: text = self._do_smart_punctuation(text) # Do hard breaks: text = re.sub(r" {2,}\n", " <br%s\n" % self.empty_element_suffix, text) return text # "Sorta" because auto-links are identified as "tag" tokens. _sorta_html_tokenize_re = re.compile(r""" ( # tag </? (?:\w+) # tag name (?:\s+(?:[\w-]+:)?[\w-]+=(?:".*?"|'.*?'))* # attributes \s*/?> | # auto-link (e.g., <http://www.activestate.com/>) <\w+[^>]*> | <!--.*?--> # comment | <\?.*?\?> # processing instruction ) """, re.X) def _escape_special_chars(self, text): # Python markdown note: the HTML tokenization here differs from # that in Markdown.pl, hence the behaviour for subtle cases can # differ (I believe the tokenizer here does a better job because # it isn't susceptible to unmatched '<' and '>' in HTML tags). # Note, however, that '>' is not allowed in an auto-link URL # here. escaped = [] is_html_markup = False for token in self._sorta_html_tokenize_re.split(text): if is_html_markup: # Within tags/HTML-comments/auto-links, encode * and _ # so they don't conflict with their use in Markdown for # italics and strong. We're replacing each such # character with its corresponding MD5 checksum value; # this is likely overkill, but it should prevent us from # colliding with the escape values by accident. escaped.append(token.replace('*', self._escape_table['*']) .replace('_', self._escape_table['_'])) else: escaped.append(self._encode_backslash_escapes(token)) is_html_markup = not is_html_markup return ''.join(escaped) def _hash_html_spans(self, text): # Used for safe_mode. def _is_auto_link(s): if ':' in s and self._auto_link_re.match(s): return True elif '@' in s and self._auto_email_link_re.match(s): return True return False tokens = [] is_html_markup = False for token in self._sorta_html_tokenize_re.split(text): if is_html_markup and not _is_auto_link(token): sanitized = self._sanitize_html(token) key = _hash_text(sanitized) self.html_spans[key] = sanitized tokens.append(key) else: tokens.append(token) is_html_markup = not is_html_markup return ''.join(tokens) def _unhash_html_spans(self, text): for key, sanitized in list(self.html_spans.items()): text = text.replace(key, sanitized) return text def _sanitize_html(self, s): if self.safe_mode == "replace": return self.html_removed_text elif self.safe_mode == "escape": replacements = [ ('&', '&amp;'), ('<', '&lt;'), ('>', '&gt;'), ] for before, after in replacements: s = s.replace(before, after) return s else: raise MarkdownError("invalid value for 'safe_mode': %r (must be " "'escape' or 'replace')" % self.safe_mode) _tail_of_inline_link_re = re.compile(r''' # Match tail of: [text](/url/) or [text](/url/ "title") \( # literal paren [ \t]* (?P<url> # \1 <.*?> | .*? ) [ \t]* ( # \2 (['"]) # quote char = \3 (?P<title>.*?) \3 # matching quote )? # title is optional \) ''', re.X | re.S) _tail_of_reference_link_re = re.compile(r''' # Match tail of: [text][id] [ ]? # one optional space (?:\n[ ]*)? # one optional newline followed by spaces \[ (?P<id>.*?) \] ''', re.X | re.S) def _do_links(self, text): """Turn Markdown link shortcuts into XHTML <a> and <img> tags. This is a combination of Markdown.pl's _DoAnchors() and _DoImages(). They are done together because that simplified the approach. It was necessary to use a different approach than Markdown.pl because of the lack of atomic matching support in Python's regex engine used in $g_nested_brackets. """ MAX_LINK_TEXT_SENTINEL = 3000 # markdown2 issue 24 # `anchor_allowed_pos` is used to support img links inside # anchors, but not anchors inside anchors. An anchor's start # pos must be `>= anchor_allowed_pos`. anchor_allowed_pos = 0 curr_pos = 0 while True: # Handle the next link. # The next '[' is the start of: # - an inline anchor: [text](url "title") # - a reference anchor: [text][id] # - an inline img: ![text](url "title") # - a reference img: ![text][id] # - a footnote ref: [^id] # (Only if 'footnotes' extra enabled) # - a footnote defn: [^id]: ... # (Only if 'footnotes' extra enabled) These have already # been stripped in _strip_footnote_definitions() so no # need to watch for them. # - a link definition: [id]: url "title" # These have already been stripped in # _strip_link_definitions() so no need to watch for them. # - not markup: [...anything else... try: start_idx = text.index('[', curr_pos) except ValueError: break text_length = len(text) # Find the matching closing ']'. # Markdown.pl allows *matching* brackets in link text so we # will here too. Markdown.pl *doesn't* currently allow # matching brackets in img alt text -- we'll differ in that # regard. bracket_depth = 0 for p in range(start_idx+1, min(start_idx+MAX_LINK_TEXT_SENTINEL, text_length)): ch = text[p] if ch == ']': bracket_depth -= 1 if bracket_depth < 0: break elif ch == '[': bracket_depth += 1 else: # Closing bracket not found within sentinel length. # This isn't markup. curr_pos = start_idx + 1 continue link_text = text[start_idx+1:p] # Possibly a footnote ref? if "footnotes" in self.extras and link_text.startswith("^"): normed_id = re.sub(r'\W', '-', link_text[1:]) if normed_id in self.footnotes: self.footnote_ids.append(normed_id) result = '<sup class="footnote-ref" id="fnref-%s">' \ '<a href="#fn-%s">%s</a></sup>' \ % (normed_id, normed_id, len(self.footnote_ids)) text = text[:start_idx] + result + text[p+1:] else: # This id isn't defined, leave the markup alone. curr_pos = p+1 continue # Now determine what this is by the remainder. p += 1 if p == text_length: return text # Inline anchor or img? if text[p] == '(': # attempt at perf improvement match = self._tail_of_inline_link_re.match(text, p) if match: # Handle an inline anchor or img. is_img = start_idx > 0 and text[start_idx-1] == "!" if is_img: start_idx -= 1 url, title = match.group("url"), match.group("title") if url and url[0] == '<': url = url[1:-1] # '<url>' -> 'url' # We've got to encode these to avoid conflicting # with italics/bold. url = url.replace('*', self._escape_table['*']) \ .replace('_', self._escape_table['_']) if title: title_str = ' title="%s"' % ( _xml_escape_attr(title) .replace('*', self._escape_table['*']) .replace('_', self._escape_table['_'])) else: title_str = '' if is_img: result = '<img src="%s" alt="%s"%s%s' \ % (url.replace('"', '&quot;'), _xml_escape_attr(link_text), title_str, self.empty_element_suffix) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) curr_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] elif start_idx >= anchor_allowed_pos: result_head = '<a href="%s"%s>' % (url, title_str) result = '%s%s</a>' % (result_head, link_text) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) # <img> allowed from curr_pos on, <a> from # anchor_allowed_pos on. curr_pos = start_idx + len(result_head) anchor_allowed_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] else: # Anchor not allowed here. curr_pos = start_idx + 1 continue # Reference anchor or img? else: match = self._tail_of_reference_link_re.match(text, p) if match: # Handle a reference-style anchor or img. is_img = start_idx > 0 and text[start_idx-1] == "!" if is_img: start_idx -= 1 link_id = match.group("id").lower() if not link_id: link_id = link_text.lower() # for links like [this][] if link_id in self.urls: url = self.urls[link_id] # We've got to encode these to avoid conflicting # with italics/bold. url = url.replace('*', self._escape_table['*']) \ .replace('_', self._escape_table['_']) title = self.titles.get(link_id) if title: before = title title = _xml_escape_attr(title) \ .replace('*', self._escape_table['*']) \ .replace('_', self._escape_table['_']) title_str = ' title="%s"' % title else: title_str = '' if is_img: result = '<img src="%s" alt="%s"%s%s' \ % (url.replace('"', '&quot;'), link_text.replace('"', '&quot;'), title_str, self.empty_element_suffix) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) curr_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] elif start_idx >= anchor_allowed_pos: result = '<a href="%s"%s>%s</a>' \ % (url, title_str, link_text) result_head = '<a href="%s"%s>' % (url, title_str) result = '%s%s</a>' % (result_head, link_text) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) # <img> allowed from curr_pos on, <a> from # anchor_allowed_pos on. curr_pos = start_idx + len(result_head) anchor_allowed_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] else: # Anchor not allowed here. curr_pos = start_idx + 1 else: # This id isn't defined, leave the markup alone. curr_pos = match.end() continue # Otherwise, it isn't markup. curr_pos = start_idx + 1 return text def header_id_from_text(self, text, prefix, n): """Generate a header id attribute value from the given header HTML content. This is only called if the "header-ids" extra is enabled. Subclasses may override this for different header ids. @param text {str} The text of the header tag @param prefix {str} The requested prefix for header ids. This is the value of the "header-ids" extra key, if any. Otherwise, None. @param n {int} The <hN> tag number, i.e. `1` for an <h1> tag. @returns {str} The value for the header tag's "id" attribute. Return None to not have an id attribute and to exclude this header from the TOC (if the "toc" extra is specified). """ header_id = _slugify(text) if prefix and isinstance(prefix, base_string_type): header_id = prefix + '-' + header_id if header_id in self._count_from_header_id: self._count_from_header_id[header_id] += 1 header_id += '-%s' % self._count_from_header_id[header_id] else: self._count_from_header_id[header_id] = 1 return header_id _toc = None def _toc_add_entry(self, level, id, name): if self._toc is None: self._toc = [] self._toc.append((level, id, self._unescape_special_chars(name))) _setext_h_re = re.compile(r'^(.+)[ \t]*\n(=+|-+)[ \t]*\n+', re.M) def _setext_h_sub(self, match): n = {"=": 1, "-": 2}[match.group(2)[0]] demote_headers = self.extras.get("demote-headers") if demote_headers: n = min(n + demote_headers, 6) header_id_attr = "" if "header-ids" in self.extras: header_id = self.header_id_from_text(match.group(1), self.extras["header-ids"], n) if header_id: header_id_attr = ' id="%s"' % header_id html = self._run_span_gamut(match.group(1)) if "toc" in self.extras and header_id: self._toc_add_entry(n, header_id, html) return "<h%d%s>%s</h%d>\n\n" % (n, header_id_attr, html, n) _atx_h_re = re.compile(r''' ^(\#{1,6}) # \1 = string of #'s [ \t]+ (.+?) # \2 = Header text [ \t]* (?<!\\) # ensure not an escaped trailing '#' \#* # optional closing #'s (not counted) \n+ ''', re.X | re.M) def _atx_h_sub(self, match): n = len(match.group(1)) demote_headers = self.extras.get("demote-headers") if demote_headers: n = min(n + demote_headers, 6) header_id_attr = "" if "header-ids" in self.extras: header_id = self.header_id_from_text(match.group(2), self.extras["header-ids"], n) if header_id: header_id_attr = ' id="%s"' % header_id html = self._run_span_gamut(match.group(2)) if "toc" in self.extras and header_id: self._toc_add_entry(n, header_id, html) return "<h%d%s>%s</h%d>\n\n" % (n, header_id_attr, html, n) def _do_headers(self, text): # Setext-style headers: # Header 1 # ======== # # Header 2 # -------- text = self._setext_h_re.sub(self._setext_h_sub, text) # atx-style headers: # # Header 1 # ## Header 2 # ## Header 2 with closing hashes ## # ... # ###### Header 6 text = self._atx_h_re.sub(self._atx_h_sub, text) return text _marker_ul_chars = '*+-' _marker_any = r'(?:[%s]|\d+\.)' % _marker_ul_chars _marker_ul = '(?:[%s])' % _marker_ul_chars _marker_ol = r'(?:\d+\.)' def _list_sub(self, match): lst = match.group(1) lst_type = match.group(3) in self._marker_ul_chars and "ul" or "ol" result = self._process_list_items(lst) if self.list_level: return "<%s>\n%s</%s>\n" % (lst_type, result, lst_type) else: return "<%s>\n%s</%s>\n\n" % (lst_type, result, lst_type) def _do_lists(self, text): # Form HTML ordered (numbered) and unordered (bulleted) lists. # Iterate over each *non-overlapping* list match. pos = 0 while True: # Find the *first* hit for either list style (ul or ol). We # match ul and ol separately to avoid adjacent lists of different # types running into each other (see issue #16). hits = [] for marker_pat in (self._marker_ul, self._marker_ol): less_than_tab = self.tab_width - 1 whole_list = r''' ( # \1 = whole list ( # \2 [ ]{0,%d} (%s) # \3 = first list item marker [ \t]+ (?!\ *\3\ ) # '- - - ...' isn't a list. See 'not_quite_a_list' test case. ) (?:.+?) ( # \4 \Z | \n{2,} (?=\S) (?! # Negative lookahead for another list item marker [ \t]* %s[ \t]+ ) ) ) ''' % (less_than_tab, marker_pat, marker_pat) if self.list_level: # sub-list list_re = re.compile("^"+whole_list, re.X | re.M | re.S) else: list_re = re.compile(r"(?:(?<=\n\n)|\A\n?)"+whole_list, re.X | re.M | re.S) match = list_re.search(text, pos) if match: hits.append((match.start(), match)) if not hits: break hits.sort() match = hits[0][1] start, end = match.span() text = text[:start] + self._list_sub(match) + text[end:] pos = end return text _list_item_re = re.compile(r''' (\n)? # leading line = \1 (^[ \t]*) # leading whitespace = \2 (?P<marker>%s) [ \t]+ # list marker = \3 ((?:.+?) # list item text = \4 (\n{1,2})) # eols = \5 (?= \n* (\Z | \2 (?P<next_marker>%s) [ \t]+)) ''' % (_marker_any, _marker_any), re.M | re.X | re.S) _last_li_endswith_two_eols = False def _list_item_sub(self, match): item = match.group(4) leading_line = match.group(1) leading_space = match.group(2) if leading_line or "\n\n" in item or self._last_li_endswith_two_eols: item = self._run_block_gamut(self._outdent(item)) else: # Recursion for sub-lists: item = self._do_lists(self._outdent(item)) if item.endswith('\n'): item = item[:-1] item = self._run_span_gamut(item) self._last_li_endswith_two_eols = (len(match.group(5)) == 2) return "<li>%s</li>\n" % item def _process_list_items(self, list_str): # Process the contents of a single ordered or unordered list, # splitting it into individual list items. # The $g_list_level global keeps track of when we're inside a list. # Each time we enter a list, we increment it; when we leave a list, # we decrement. If it's zero, we're not in a list anymore. # # We do this because when we're not inside a list, we want to treat # something like this: # # I recommend upgrading to version # 8. Oops, now this line is treated # as a sub-list. # # As a single paragraph, despite the fact that the second line starts # with a digit-period-space sequence. # # Whereas when we're inside a list (or sub-list), that line will be # treated as the start of a sub-list. What a kludge, huh? This is # an aspect of Markdown's syntax that's hard to parse perfectly # without resorting to mind-reading. Perhaps the solution is to # change the syntax rules such that sub-lists must start with a # starting cardinal number; e.g. "1." or "a.". self.list_level += 1 self._last_li_endswith_two_eols = False list_str = list_str.rstrip('\n') + '\n' list_str = self._list_item_re.sub(self._list_item_sub, list_str) self.list_level -= 1 return list_str def _get_pygments_lexer(self, lexer_name): try: from pygments import lexers, util except ImportError: return None try: return lexers.get_lexer_by_name(lexer_name) except util.ClassNotFound: return None def _color_with_pygments(self, codeblock, lexer, **formatter_opts): import pygments import pygments.formatters class HtmlCodeFormatter(pygments.formatters.HtmlFormatter): def _wrap_code(self, inner): """A function for use in a Pygments Formatter which wraps in <code> tags. """ yield 0, "<code>" for tup in inner: yield tup yield 0, "</code>" def wrap(self, source, outfile): """Return the source with a code, pre, and div.""" return self._wrap_div(self._wrap_pre(self._wrap_code(source))) formatter_opts.setdefault("cssclass", "codehilite") formatter = HtmlCodeFormatter(**formatter_opts) return pygments.highlight(codeblock, lexer, formatter) def _code_block_sub(self, match, is_fenced_code_block=False): lexer_name = None if is_fenced_code_block: lexer_name = match.group(1) if lexer_name: formatter_opts = self.extras['fenced-code-blocks'] or {} codeblock = match.group(2) codeblock = codeblock[:-1] # drop one trailing newline else: codeblock = match.group(1) codeblock = self._outdent(codeblock) codeblock = self._detab(codeblock) codeblock = codeblock.lstrip('\n') # trim leading newlines codeblock = codeblock.rstrip() # trim trailing whitespace # Note: "code-color" extra is DEPRECATED. if "code-color" in self.extras and codeblock.startswith(":::"): lexer_name, rest = codeblock.split('\n', 1) lexer_name = lexer_name[3:].strip() codeblock = rest.lstrip("\n") # Remove lexer declaration line. formatter_opts = self.extras['code-color'] or {} if lexer_name: lexer = self._get_pygments_lexer(lexer_name) if lexer: colored = self._color_with_pygments(codeblock, lexer, **formatter_opts) return "\n\n%s\n\n" % colored codeblock = self._encode_code(codeblock) pre_class_str = self._html_class_str_from_tag("pre") code_class_str = self._html_class_str_from_tag("code") return "\n\n<pre%s><code%s>%s\n</code></pre>\n\n" % ( pre_class_str, code_class_str, codeblock) def _html_class_str_from_tag(self, tag): """Get the appropriate ' class="..."' string (note the leading space), if any, for the given tag. """ if "html-classes" not in self.extras: return "" try: html_classes_from_tag = self.extras["html-classes"] except TypeError: return "" else: if tag in html_classes_from_tag: return ' class="%s"' % html_classes_from_tag[tag] return "" def _do_code_blocks(self, text): """Process Markdown `<pre><code>` blocks.""" code_block_re = re.compile(r''' (?:\n\n|\A\n?) ( # $1 = the code block -- one or more lines, starting with a space/tab (?: (?:[ ]{%d} | \t) # Lines must start with a tab or a tab-width of spaces .*\n+ )+ ) ((?=^[ ]{0,%d}\S)|\Z) # Lookahead for non-space at line-start, or end of doc ''' % (self.tab_width, self.tab_width), re.M | re.X) return code_block_re.sub(self._code_block_sub, text) _fenced_code_block_re = re.compile(r''' (?:\n\n|\A\n?) ^```([\w+-]+)?[ \t]*\n # opening fence, $1 = optional lang (.*?) # $2 = code block content ^```[ \t]*\n # closing fence ''', re.M | re.X | re.S) def _fenced_code_block_sub(self, match): return self._code_block_sub(match, is_fenced_code_block=True); def _do_fenced_code_blocks(self, text): """Process ```-fenced unindented code blocks ('fenced-code-blocks' extra).""" return self._fenced_code_block_re.sub(self._fenced_code_block_sub, text) # Rules for a code span: # - backslash escapes are not interpreted in a code span # - to include one or or a run of more backticks the delimiters must # be a longer run of backticks # - cannot start or end a code span with a backtick; pad with a # space and that space will be removed in the emitted HTML # See `test/tm-cases/escapes.text` for a number of edge-case # examples. _code_span_re = re.compile(r''' (?<!\\) (`+) # \1 = Opening run of ` (?!`) # See Note A test/tm-cases/escapes.text (.+?) # \2 = The code block (?<!`) \1 # Matching closer (?!`) ''', re.X | re.S) def _code_span_sub(self, match): c = match.group(2).strip(" \t") c = self._encode_code(c) return "<code>%s</code>" % c def _do_code_spans(self, text): # * Backtick quotes are used for <code></code> spans. # # * You can use multiple backticks as the delimiters if you want to # include literal backticks in the code span. So, this input: # # Just type ``foo `bar` baz`` at the prompt. # # Will translate to: # # <p>Just type <code>foo `bar` baz</code> at the prompt.</p> # # There's no arbitrary limit to the number of backticks you # can use as delimters. If you need three consecutive backticks # in your code, use four for delimiters, etc. # # * You can use spaces to get literal backticks at the edges: # # ... type `` `bar` `` ... # # Turns to: # # ... type <code>`bar`</code> ... return self._code_span_re.sub(self._code_span_sub, text) def _encode_code(self, text): """Encode/escape certain characters inside Markdown code runs. The point is that in code, these characters are literals, and lose their special Markdown meanings. """ replacements = [ # Encode all ampersands; HTML entities are not # entities within a Markdown code span. ('&', '&amp;'), # Do the angle bracket song and dance: ('<', '&lt;'), ('>', '&gt;'), ] for before, after in replacements: text = text.replace(before, after) hashed = _hash_text(text) self._escape_table[text] = hashed return hashed _strong_re = re.compile(r"(\*\*|__)(?=\S)(.+?[*_]*)(?<=\S)\1", re.S) _em_re = re.compile(r"(\*|_)(?=\S)(.+?)(?<=\S)\1", re.S) _code_friendly_strong_re = re.compile(r"\*\*(?=\S)(.+?[*_]*)(?<=\S)\*\*", re.S) _code_friendly_em_re = re.compile(r"\*(?=\S)(.+?)(?<=\S)\*", re.S) def _do_italics_and_bold(self, text): # <strong> must go first: if "code-friendly" in self.extras: text = self._code_friendly_strong_re.sub(r"<strong>\1</strong>", text) text = self._code_friendly_em_re.sub(r"<em>\1</em>", text) else: text = self._strong_re.sub(r"<strong>\2</strong>", text) text = self._em_re.sub(r"<em>\2</em>", text) return text # "smarty-pants" extra: Very liberal in interpreting a single prime as an # apostrophe; e.g. ignores the fact that "round", "bout", "twer", and # "twixt" can be written without an initial apostrophe. This is fine because # using scare quotes (single quotation marks) is rare. _apostrophe_year_re = re.compile(r"'(\d\d)(?=(\s|,|;|\.|\?|!|$))") _contractions = ["tis", "twas", "twer", "neath", "o", "n", "round", "bout", "twixt", "nuff", "fraid", "sup"] def _do_smart_contractions(self, text): text = self._apostrophe_year_re.sub(r"&#8217;\1", text) for c in self._contractions: text = text.replace("'%s" % c, "&#8217;%s" % c) text = text.replace("'%s" % c.capitalize(), "&#8217;%s" % c.capitalize()) return text # Substitute double-quotes before single-quotes. _opening_single_quote_re = re.compile(r"(?<!\S)'(?=\S)") _opening_double_quote_re = re.compile(r'(?<!\S)"(?=\S)') _closing_single_quote_re = re.compile(r"(?<=\S)'") _closing_double_quote_re = re.compile(r'(?<=\S)"(?=(\s|,|;|\.|\?|!|$))') def _do_smart_punctuation(self, text): """Fancifies 'single quotes', "double quotes", and apostrophes. Converts --, ---, and ... into en dashes, em dashes, and ellipses. Inspiration is: <http://daringfireball.net/projects/smartypants/> See "test/tm-cases/smarty_pants.text" for a full discussion of the support here and <http://code.google.com/p/python-markdown2/issues/detail?id=42> for a discussion of some diversion from the original SmartyPants. """ if "'" in text: # guard for perf text = self._do_smart_contractions(text) text = self._opening_single_quote_re.sub("&#8216;", text) text = self._closing_single_quote_re.sub("&#8217;", text) if '"' in text: # guard for perf text = self._opening_double_quote_re.sub("&#8220;", text) text = self._closing_double_quote_re.sub("&#8221;", text) text = text.replace("---", "&#8212;") text = text.replace("--", "&#8211;") text = text.replace("...", "&#8230;") text = text.replace(" . . . ", "&#8230;") text = text.replace(". . .", "&#8230;") return text _block_quote_re = re.compile(r''' ( # Wrap whole match in \1 ( ^[ \t]*>[ \t]? # '>' at the start of a line .+\n # rest of the first line (.+\n)* # subsequent consecutive lines \n* # blanks )+ ) ''', re.M | re.X) _bq_one_level_re = re.compile('^[ \t]*>[ \t]?', re.M); _html_pre_block_re = re.compile(r'(\s*<pre>.+?</pre>)', re.S) def _dedent_two_spaces_sub(self, match): return re.sub(r'(?m)^ ', '', match.group(1)) def _block_quote_sub(self, match): bq = match.group(1) bq = self._bq_one_level_re.sub('', bq) # trim one level of quoting bq = self._ws_only_line_re.sub('', bq) # trim whitespace-only lines bq = self._run_block_gamut(bq) # recurse bq = re.sub('(?m)^', ' ', bq) # These leading spaces screw with <pre> content, so we need to fix that: bq = self._html_pre_block_re.sub(self._dedent_two_spaces_sub, bq) return "<blockquote>\n%s\n</blockquote>\n\n" % bq def _do_block_quotes(self, text): if '>' not in text: return text return self._block_quote_re.sub(self._block_quote_sub, text) def _form_paragraphs(self, text): # Strip leading and trailing lines: text = text.strip('\n') # Wrap <p> tags. grafs = [] for i, graf in enumerate(re.split(r"\n{2,}", text)): if graf in self.html_blocks: # Unhashify HTML blocks grafs.append(self.html_blocks[graf]) else: cuddled_list = None if "cuddled-lists" in self.extras: # Need to put back trailing '\n' for `_list_item_re` # match at the end of the paragraph. li = self._list_item_re.search(graf + '\n') # Two of the same list marker in this paragraph: a likely # candidate for a list cuddled to preceding paragraph # text (issue 33). Note the `[-1]` is a quick way to # consider numeric bullets (e.g. "1." and "2.") to be # equal. if (li and len(li.group(2)) <= 3 and li.group("next_marker") and li.group("marker")[-1] == li.group("next_marker")[-1]): start = li.start() cuddled_list = self._do_lists(graf[start:]).rstrip("\n") assert cuddled_list.startswith("<ul>") or cuddled_list.startswith("<ol>") graf = graf[:start] # Wrap <p> tags. graf = self._run_span_gamut(graf) grafs.append("<p>" + graf.lstrip(" \t") + "</p>") if cuddled_list: grafs.append(cuddled_list) return "\n\n".join(grafs) def _add_footnotes(self, text): if self.footnotes: footer = [ '<div class="footnotes">', '<hr' + self.empty_element_suffix, '<ol>', ] for i, id in enumerate(self.footnote_ids): if i != 0: footer.append('') footer.append('<li id="fn-%s">' % id) footer.append(self._run_block_gamut(self.footnotes[id])) backlink = ('<a href="#fnref-%s" ' 'class="footnoteBackLink" ' 'title="Jump back to footnote %d in the text.">' '&#8617;</a>' % (id, i+1)) if footer[-1].endswith("</p>"): footer[-1] = footer[-1][:-len("</p>")] \ + '&nbsp;' + backlink + "</p>" else: footer.append("\n<p>%s</p>" % backlink) footer.append('</li>') footer.append('</ol>') footer.append('</div>') return text + '\n\n' + '\n'.join(footer) else: return text # Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin: # http://bumppo.net/projects/amputator/ _ampersand_re = re.compile(r'&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)') _naked_lt_re = re.compile(r'<(?![a-z/?\$!])', re.I) _naked_gt_re = re.compile(r'''(?<![a-z0-9?!/'"-])>''', re.I) def _encode_amps_and_angles(self, text): # Smart processing for ampersands and angle brackets that need # to be encoded. text = self._ampersand_re.sub('&amp;', text) # Encode naked <'s text = self._naked_lt_re.sub('&lt;', text) # Encode naked >'s # Note: Other markdown implementations (e.g. Markdown.pl, PHP # Markdown) don't do this. text = self._naked_gt_re.sub('&gt;', text) return text def _encode_backslash_escapes(self, text): for ch, escape in list(self._escape_table.items()): text = text.replace("\\"+ch, escape) return text _auto_link_re = re.compile(r'<((https?|ftp):[^\'">\s]+)>', re.I) def _auto_link_sub(self, match): g1 = match.group(1) return '<a href="%s">%s</a>' % (g1, g1) _auto_email_link_re = re.compile(r""" < (?:mailto:)? ( [-.\w]+ \@ [-\w]+(\.[-\w]+)*\.[a-z]+ ) > """, re.I | re.X | re.U) def _auto_email_link_sub(self, match): return self._encode_email_address( self._unescape_special_chars(match.group(1))) def _do_auto_links(self, text): text = self._auto_link_re.sub(self._auto_link_sub, text) text = self._auto_email_link_re.sub(self._auto_email_link_sub, text) return text def _encode_email_address(self, addr): # Input: an email address, e.g. "foo@example.com" # # Output: the email address as a mailto link, with each character # of the address encoded as either a decimal or hex entity, in # the hopes of foiling most address harvesting spam bots. E.g.: # # <a href="&#x6D;&#97;&#105;&#108;&#x74;&#111;:&#102;&#111;&#111;&#64;&#101; # x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;">&#102;&#111;&#111; # &#64;&#101;x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;</a> # # Based on a filter by Matthew Wickline, posted to the BBEdit-Talk # mailing list: <http://tinyurl.com/yu7ue> chars = [_xml_encode_email_char_at_random(ch) for ch in "mailto:" + addr] # Strip the mailto: from the visible part. addr = '<a href="%s">%s</a>' \ % (''.join(chars), ''.join(chars[7:])) return addr def _do_link_patterns(self, text): """Caveat emptor: there isn't much guarding against link patterns being formed inside other standard Markdown links, e.g. inside a [link def][like this]. Dev Notes: *Could* consider prefixing regexes with a negative lookbehind assertion to attempt to guard against this. """ link_from_hash = {} for regex, repl in self.link_patterns: replacements = [] for match in regex.finditer(text): if hasattr(repl, "__call__"): href = repl(match) else: href = match.expand(repl) replacements.append((match.span(), href)) for (start, end), href in reversed(replacements): escaped_href = ( href.replace('"', '&quot;') # b/c of attr quote # To avoid markdown <em> and <strong>: .replace('*', self._escape_table['*']) .replace('_', self._escape_table['_'])) link = '<a href="%s">%s</a>' % (escaped_href, text[start:end]) hash = _hash_text(link) link_from_hash[hash] = link text = text[:start] + hash + text[end:] for hash, link in list(link_from_hash.items()): text = text.replace(hash, link) return text def _unescape_special_chars(self, text): # Swap back in all the special characters we've hidden. for ch, hash in list(self._escape_table.items()): text = text.replace(hash, ch) return text def _outdent(self, text): # Remove one level of line-leading tabs or spaces return self._outdent_re.sub('', text) class MarkdownWithExtras(Markdown): """A markdowner class that enables most extras: - footnotes - code-color (only has effect if 'pygments' Python module on path) These are not included: - pyshell (specific to Python-related documenting) - code-friendly (because it *disables* part of the syntax) - link-patterns (because you need to specify some actual link-patterns anyway) """ extras = ["footnotes", "code-color"] #---- internal support functions class UnicodeWithAttrs(unicode): """A subclass of unicode used for the return value of conversion to possibly attach some attributes. E.g. the "toc_html" attribute when the "toc" extra is used. """ metadata = None _toc = None def toc_html(self): """Return the HTML for the current TOC. This expects the `_toc` attribute to have been set on this instance. """ if self._toc is None: return None def indent(): return ' ' * (len(h_stack) - 1) lines = [] h_stack = [0] # stack of header-level numbers for level, id, name in self._toc: if level > h_stack[-1]: lines.append("%s<ul>" % indent()) h_stack.append(level) elif level == h_stack[-1]: lines[-1] += "</li>" else: while level < h_stack[-1]: h_stack.pop() if not lines[-1].endswith("</li>"): lines[-1] += "</li>" lines.append("%s</ul></li>" % indent()) lines.append('%s<li><a href="#%s">%s</a>' % ( indent(), id, name)) while len(h_stack) > 1: h_stack.pop() if not lines[-1].endswith("</li>"): lines[-1] += "</li>" lines.append("%s</ul>" % indent()) return '\n'.join(lines) + '\n' toc_html = property(toc_html) ## {{{ http://code.activestate.com/recipes/577257/ (r1) import re char_map = {u'À': 'A', u'Á': 'A', u'Â': 'A', u'Ã': 'A', u'Ä': 'Ae', u'Å': 'A', u'Æ': 'A', u'Ā': 'A', u'Ą': 'A', u'Ă': 'A', u'Ç': 'C', u'Ć': 'C', u'Č': 'C', u'Ĉ': 'C', u'Ċ': 'C', u'Ď': 'D', u'Đ': 'D', u'È': 'E', u'É': 'E', u'Ê': 'E', u'Ë': 'E', u'Ē': 'E', u'Ę': 'E', u'Ě': 'E', u'Ĕ': 'E', u'Ė': 'E', u'Ĝ': 'G', u'Ğ': 'G', u'Ġ': 'G', u'Ģ': 'G', u'Ĥ': 'H', u'Ħ': 'H', u'Ì': 'I', u'Í': 'I', u'Î': 'I', u'Ï': 'I', u'Ī': 'I', u'Ĩ': 'I', u'Ĭ': 'I', u'Į': 'I', u'İ': 'I', u'IJ': 'IJ', u'Ĵ': 'J', u'Ķ': 'K', u'Ľ': 'K', u'Ĺ': 'K', u'Ļ': 'K', u'Ŀ': 'K', u'Ł': 'L', u'Ñ': 'N', u'Ń': 'N', u'Ň': 'N', u'Ņ': 'N', u'Ŋ': 'N', u'Ò': 'O', u'Ó': 'O', u'Ô': 'O', u'Õ': 'O', u'Ö': 'Oe', u'Ø': 'O', u'Ō': 'O', u'Ő': 'O', u'Ŏ': 'O', u'Œ': 'OE', u'Ŕ': 'R', u'Ř': 'R', u'Ŗ': 'R', u'Ś': 'S', u'Ş': 'S', u'Ŝ': 'S', u'Ș': 'S', u'Š': 'S', u'Ť': 'T', u'Ţ': 'T', u'Ŧ': 'T', u'Ț': 'T', u'Ù': 'U', u'Ú': 'U', u'Û': 'U', u'Ü': 'Ue', u'Ū': 'U', u'Ů': 'U', u'Ű': 'U', u'Ŭ': 'U', u'Ũ': 'U', u'Ų': 'U', u'Ŵ': 'W', u'Ŷ': 'Y', u'Ÿ': 'Y', u'Ý': 'Y', u'Ź': 'Z', u'Ż': 'Z', u'Ž': 'Z', u'à': 'a', u'á': 'a', u'â': 'a', u'ã': 'a', u'ä': 'ae', u'ā': 'a', u'ą': 'a', u'ă': 'a', u'å': 'a', u'æ': 'ae', u'ç': 'c', u'ć': 'c', u'č': 'c', u'ĉ': 'c', u'ċ': 'c', u'ď': 'd', u'đ': 'd', u'è': 'e', u'é': 'e', u'ê': 'e', u'ë': 'e', u'ē': 'e', u'ę': 'e', u'ě': 'e', u'ĕ': 'e', u'ė': 'e', u'ƒ': 'f', u'ĝ': 'g', u'ğ': 'g', u'ġ': 'g', u'ģ': 'g', u'ĥ': 'h', u'ħ': 'h', u'ì': 'i', u'í': 'i', u'î': 'i', u'ï': 'i', u'ī': 'i', u'ĩ': 'i', u'ĭ': 'i', u'į': 'i', u'ı': 'i', u'ij': 'ij', u'ĵ': 'j', u'ķ': 'k', u'ĸ': 'k', u'ł': 'l', u'ľ': 'l', u'ĺ': 'l', u'ļ': 'l', u'ŀ': 'l', u'ñ': 'n', u'ń': 'n', u'ň': 'n', u'ņ': 'n', u'ʼn': 'n', u'ŋ': 'n', u'ò': 'o', u'ó': 'o', u'ô': 'o', u'õ': 'o', u'ö': 'oe', u'ø': 'o', u'ō': 'o', u'ő': 'o', u'ŏ': 'o', u'œ': 'oe', u'ŕ': 'r', u'ř': 'r', u'ŗ': 'r', u'ś': 's', u'š': 's', u'ť': 't', u'ù': 'u', u'ú': 'u', u'û': 'u', u'ü': 'ue', u'ū': 'u', u'ů': 'u', u'ű': 'u', u'ŭ': 'u', u'ũ': 'u', u'ų': 'u', u'ŵ': 'w', u'ÿ': 'y', u'ý': 'y', u'ŷ': 'y', u'ż': 'z', u'ź': 'z', u'ž': 'z', u'ß': 'ss', u'ſ': 'ss', u'Α': 'A', u'Ά': 'A', u'Ἀ': 'A', u'Ἁ': 'A', u'Ἂ': 'A', u'Ἃ': 'A', u'Ἄ': 'A', u'Ἅ': 'A', u'Ἆ': 'A', u'Ἇ': 'A', u'ᾈ': 'A', u'ᾉ': 'A', u'ᾊ': 'A', u'ᾋ': 'A', u'ᾌ': 'A', u'ᾍ': 'A', u'ᾎ': 'A', u'ᾏ': 'A', u'Ᾰ': 'A', u'Ᾱ': 'A', u'Ὰ': 'A', u'Ά': 'A', u'ᾼ': 'A', u'Β': 'B', u'Γ': 'G', u'Δ': 'D', u'Ε': 'E', u'Έ': 'E', u'Ἐ': 'E', u'Ἑ': 'E', u'Ἒ': 'E', u'Ἓ': 'E', u'Ἔ': 'E', u'Ἕ': 'E', u'Έ': 'E', u'Ὲ': 'E', u'Ζ': 'Z', u'Η': 'I', u'Ή': 'I', u'Ἠ': 'I', u'Ἡ': 'I', u'Ἢ': 'I', u'Ἣ': 'I', u'Ἤ': 'I', u'Ἥ': 'I', u'Ἦ': 'I', u'Ἧ': 'I', u'ᾘ': 'I', u'ᾙ': 'I', u'ᾚ': 'I', u'ᾛ': 'I', u'ᾜ': 'I', u'ᾝ': 'I', u'ᾞ': 'I', u'ᾟ': 'I', u'Ὴ': 'I', u'Ή': 'I', u'ῌ': 'I', u'Θ': 'TH', u'Ι': 'I', u'Ί': 'I', u'Ϊ': 'I', u'Ἰ': 'I', u'Ἱ': 'I', u'Ἲ': 'I', u'Ἳ': 'I', u'Ἴ': 'I', u'Ἵ': 'I', u'Ἶ': 'I', u'Ἷ': 'I', u'Ῐ': 'I', u'Ῑ': 'I', u'Ὶ': 'I', u'Ί': 'I', u'Κ': 'K', u'Λ': 'L', u'Μ': 'M', u'Ν': 'N', u'Ξ': 'KS', u'Ο': 'O', u'Ό': 'O', u'Ὀ': 'O', u'Ὁ': 'O', u'Ὂ': 'O', u'Ὃ': 'O', u'Ὄ': 'O', u'Ὅ': 'O', u'Ὸ': 'O', u'Ό': 'O', u'Π': 'P', u'Ρ': 'R', u'Ῥ': 'R', u'Σ': 'S', u'Τ': 'T', u'Υ': 'Y', u'Ύ': 'Y', u'Ϋ': 'Y', u'Ὑ': 'Y', u'Ὓ': 'Y', u'Ὕ': 'Y', u'Ὗ': 'Y', u'Ῠ': 'Y', u'Ῡ': 'Y', u'Ὺ': 'Y', u'Ύ': 'Y', u'Φ': 'F', u'Χ': 'X', u'Ψ': 'PS', u'Ω': 'O', u'Ώ': 'O', u'Ὠ': 'O', u'Ὡ': 'O', u'Ὢ': 'O', u'Ὣ': 'O', u'Ὤ': 'O', u'Ὥ': 'O', u'Ὦ': 'O', u'Ὧ': 'O', u'ᾨ': 'O', u'ᾩ': 'O', u'ᾪ': 'O', u'ᾫ': 'O', u'ᾬ': 'O', u'ᾭ': 'O', u'ᾮ': 'O', u'ᾯ': 'O', u'Ὼ': 'O', u'Ώ': 'O', u'ῼ': 'O', u'α': 'a', u'ά': 'a', u'ἀ': 'a', u'ἁ': 'a', u'ἂ': 'a', u'ἃ': 'a', u'ἄ': 'a', u'ἅ': 'a', u'ἆ': 'a', u'ἇ': 'a', u'ᾀ': 'a', u'ᾁ': 'a', u'ᾂ': 'a', u'ᾃ': 'a', u'ᾄ': 'a', u'ᾅ': 'a', u'ᾆ': 'a', u'ᾇ': 'a', u'ὰ': 'a', u'ά': 'a', u'ᾰ': 'a', u'ᾱ': 'a', u'ᾲ': 'a', u'ᾳ': 'a', u'ᾴ': 'a', u'ᾶ': 'a', u'ᾷ': 'a', u'β': 'b', u'γ': 'g', u'δ': 'd', u'ε': 'e', u'έ': 'e', u'ἐ': 'e', u'ἑ': 'e', u'ἒ': 'e', u'ἓ': 'e', u'ἔ': 'e', u'ἕ': 'e', u'ὲ': 'e', u'έ': 'e', u'ζ': 'z', u'η': 'i', u'ή': 'i', u'ἠ': 'i', u'ἡ': 'i', u'ἢ': 'i', u'ἣ': 'i', u'ἤ': 'i', u'ἥ': 'i', u'ἦ': 'i', u'ἧ': 'i', u'ᾐ': 'i', u'ᾑ': 'i', u'ᾒ': 'i', u'ᾓ': 'i', u'ᾔ': 'i', u'ᾕ': 'i', u'ᾖ': 'i', u'ᾗ': 'i', u'ὴ': 'i', u'ή': 'i', u'ῂ': 'i', u'ῃ': 'i', u'ῄ': 'i', u'ῆ': 'i', u'ῇ': 'i', u'θ': 'th', u'ι': 'i', u'ί': 'i', u'ϊ': 'i', u'ΐ': 'i', u'ἰ': 'i', u'ἱ': 'i', u'ἲ': 'i', u'ἳ': 'i', u'ἴ': 'i', u'ἵ': 'i', u'ἶ': 'i', u'ἷ': 'i', u'ὶ': 'i', u'ί': 'i', u'ῐ': 'i', u'ῑ': 'i', u'ῒ': 'i', u'ΐ': 'i', u'ῖ': 'i', u'ῗ': 'i', u'κ': 'k', u'λ': 'l', u'μ': 'm', u'ν': 'n', u'ξ': 'ks', u'ο': 'o', u'ό': 'o', u'ὀ': 'o', u'ὁ': 'o', u'ὂ': 'o', u'ὃ': 'o', u'ὄ': 'o', u'ὅ': 'o', u'ὸ': 'o', u'ό': 'o', u'π': 'p', u'ρ': 'r', u'ῤ': 'r', u'ῥ': 'r', u'σ': 's', u'ς': 's', u'τ': 't', u'υ': 'y', u'ύ': 'y', u'ϋ': 'y', u'ΰ': 'y', u'ὐ': 'y', u'ὑ': 'y', u'ὒ': 'y', u'ὓ': 'y', u'ὔ': 'y', u'ὕ': 'y', u'ὖ': 'y', u'ὗ': 'y', u'ὺ': 'y', u'ύ': 'y', u'ῠ': 'y', u'ῡ': 'y', u'ῢ': 'y', u'ΰ': 'y', u'ῦ': 'y', u'ῧ': 'y', u'φ': 'f', u'χ': 'x', u'ψ': 'ps', u'ω': 'o', u'ώ': 'o', u'ὠ': 'o', u'ὡ': 'o', u'ὢ': 'o', u'ὣ': 'o', u'ὤ': 'o', u'ὥ': 'o', u'ὦ': 'o', u'ὧ': 'o', u'ᾠ': 'o', u'ᾡ': 'o', u'ᾢ': 'o', u'ᾣ': 'o', u'ᾤ': 'o', u'ᾥ': 'o', u'ᾦ': 'o', u'ᾧ': 'o', u'ὼ': 'o', u'ώ': 'o', u'ῲ': 'o', u'ῳ': 'o', u'ῴ': 'o', u'ῶ': 'o', u'ῷ': 'o', u'¨': '', u'΅': '', u'᾿': '', u'῾': '', u'῍': '', u'῝': '', u'῎': '', u'῞': '', u'῏': '', u'῟': '', u'῀': '', u'῁': '', u'΄': '', u'΅': '', u'`': '', u'῭': '', u'ͺ': '', u'᾽': '', u'А': 'A', u'Б': 'B', u'В': 'V', u'Г': 'G', u'Д': 'D', u'Е': 'E', u'Ё': 'YO', u'Ж': 'ZH', u'З': 'Z', u'И': 'I', u'Й': 'J', u'К': 'K', u'Л': 'L', u'М': 'M', u'Н': 'N', u'О': 'O', u'П': 'P', u'Р': 'R', u'С': 'S', u'Т': 'T', u'У': 'U', u'Ф': 'F', u'Х': 'H', u'Ц': 'TS', u'Ч': 'CH', u'Ш': 'SH', u'Щ': 'SCH', u'Ы': 'YI', u'Э': 'E', u'Ю': 'YU', u'Я': 'YA', u'а': 'A', u'б': 'B', u'в': 'V', u'г': 'G', u'д': 'D', u'е': 'E', u'ё': 'YO', u'ж': 'ZH', u'з': 'Z', u'и': 'I', u'й': 'J', u'к': 'K', u'л': 'L', u'м': 'M', u'н': 'N', u'о': 'O', u'п': 'P', u'р': 'R', u'с': 'S', u'т': 'T', u'у': 'U', u'ф': 'F', u'х': 'H', u'ц': 'TS', u'ч': 'CH', u'ш': 'SH', u'щ': 'SCH', u'ы': 'YI', u'э': 'E', u'ю': 'YU', u'я': 'YA', u'Ъ': '', u'ъ': '', u'Ь': '', u'ь': '', u'ð': 'd', u'Ð': 'D', u'þ': 'th', u'Þ': 'TH',u'ა': 'a', u'ბ': 'b', u'გ': 'g', u'დ': 'd', u'ე': 'e', u'ვ': 'v', u'ზ': 'z', u'თ': 't', u'ი': 'i', u'კ': 'k', u'ლ': 'l', u'მ': 'm', u'ნ': 'n', u'ო': 'o', u'პ': 'p', u'ჟ': 'zh', u'რ': 'r', u'ს': 's', u'ტ': 't', u'უ': 'u', u'ფ': 'p', u'ქ': 'k', u'ღ': 'gh', u'ყ': 'q', u'შ': 'sh', u'ჩ': 'ch', u'ც': 'ts', u'ძ': 'dz', u'წ': 'ts', u'ჭ': 'ch', u'ხ': 'kh', u'ჯ': 'j', u'ჰ': 'h' } def replace_char(m): char = m.group() if char_map.has_key(char): return char_map[char] else: return char _punct_re = re.compile(r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.]+') def _slugify(text, delim=u'-'): """Generates an ASCII-only slug.""" result = [] for word in _punct_re.split(text.lower()): word = word.encode('utf-8') if word: result.append(word) slugified = delim.join([i.decode('utf-8') for i in result]) return re.sub('[^a-zA-Z0-9\\s\\-]{1}', replace_char, slugified).lower() ## end of http://code.activestate.com/recipes/577257/ }}} # From http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52549 def _curry(*args, **kwargs): function, args = args[0], args[1:] def result(*rest, **kwrest): combined = kwargs.copy() combined.update(kwrest) return function(*args + rest, **combined) return result # Recipe: regex_from_encoded_pattern (1.0) def _regex_from_encoded_pattern(s): """'foo' -> re.compile(re.escape('foo')) '/foo/' -> re.compile('foo') '/foo/i' -> re.compile('foo', re.I) """ if s.startswith('/') and s.rfind('/') != 0: # Parse it: /PATTERN/FLAGS idx = s.rfind('/') pattern, flags_str = s[1:idx], s[idx+1:] flag_from_char = { "i": re.IGNORECASE, "l": re.LOCALE, "s": re.DOTALL, "m": re.MULTILINE, "u": re.UNICODE, } flags = 0 for char in flags_str: try: flags |= flag_from_char[char] except KeyError: raise ValueError("unsupported regex flag: '%s' in '%s' " "(must be one of '%s')" % (char, s, ''.join(list(flag_from_char.keys())))) return re.compile(s[1:idx], flags) else: # not an encoded regex return re.compile(re.escape(s)) # Recipe: dedent (0.1.2) def _dedentlines(lines, tabsize=8, skip_first_line=False): """_dedentlines(lines, tabsize=8, skip_first_line=False) -> dedented lines "lines" is a list of lines to dedent. "tabsize" is the tab width to use for indent width calculations. "skip_first_line" is a boolean indicating if the first line should be skipped for calculating the indent width and for dedenting. This is sometimes useful for docstrings and similar. Same as dedent() except operates on a sequence of lines. Note: the lines list is modified **in-place**. """ DEBUG = False if DEBUG: print("dedent: dedent(..., tabsize=%d, skip_first_line=%r)"\ % (tabsize, skip_first_line)) indents = [] margin = None for i, line in enumerate(lines): if i == 0 and skip_first_line: continue indent = 0 for ch in line: if ch == ' ': indent += 1 elif ch == '\t': indent += tabsize - (indent % tabsize) elif ch in '\r\n': continue # skip all-whitespace lines else: break else: continue # skip all-whitespace lines if DEBUG: print("dedent: indent=%d: %r" % (indent, line)) if margin is None: margin = indent else: margin = min(margin, indent) if DEBUG: print("dedent: margin=%r" % margin) if margin is not None and margin > 0: for i, line in enumerate(lines): if i == 0 and skip_first_line: continue removed = 0 for j, ch in enumerate(line): if ch == ' ': removed += 1 elif ch == '\t': removed += tabsize - (removed % tabsize) elif ch in '\r\n': if DEBUG: print("dedent: %r: EOL -> strip up to EOL" % line) lines[i] = lines[i][j:] break else: raise ValueError("unexpected non-whitespace char %r in " "line %r while removing %d-space margin" % (ch, line, margin)) if DEBUG: print("dedent: %r: %r -> removed %d/%d"\ % (line, ch, removed, margin)) if removed == margin: lines[i] = lines[i][j+1:] break elif removed > margin: lines[i] = ' '*(removed-margin) + lines[i][j+1:] break else: if removed: lines[i] = lines[i][removed:] return lines class _memoized(object): """Decorator that caches a function's return value each time it is called. If called later with the same arguments, the cached value is returned, and not re-evaluated. http://wiki.python.org/moin/PythonDecoratorLibrary """ def __init__(self, func): self.func = func self.cache = {} def __call__(self, *args): try: return self.cache[args] except KeyError: self.cache[args] = value = self.func(*args) return value except TypeError: # uncachable -- for instance, passing a list as an argument. # Better to not cache than to blow up entirely. return self.func(*args) def __repr__(self): """Return the function's docstring.""" return self.func.__doc__ def _xml_oneliner_re_from_tab_width(tab_width): """Standalone XML processing instruction regex.""" return re.compile(r""" (?: (?<=\n\n) # Starting after a blank line | # or \A\n? # the beginning of the doc ) ( # save in $1 [ ]{0,%d} (?: <\?\w+\b\s+.*?\?> # XML processing instruction | <\w+:\w+\b\s+.*?/> # namespaced single tag ) [ \t]* (?=\n{2,}|\Z) # followed by a blank line or end of document ) """ % (tab_width - 1), re.X) _xml_oneliner_re_from_tab_width = _memoized(_xml_oneliner_re_from_tab_width) def _hr_tag_re_from_tab_width(tab_width): return re.compile(r""" (?: (?<=\n\n) # Starting after a blank line | # or \A\n? # the beginning of the doc ) ( # save in \1 [ ]{0,%d} <(hr) # start tag = \2 \b # word break ([^<>])*? # /?> # the matching end tag [ \t]* (?=\n{2,}|\Z) # followed by a blank line or end of document ) """ % (tab_width - 1), re.X) _hr_tag_re_from_tab_width = _memoized(_hr_tag_re_from_tab_width) def _xml_escape_attr(attr, skip_single_quote=True): """Escape the given string for use in an HTML/XML tag attribute. By default this doesn't bother with escaping `'` to `&#39;`, presuming that the tag attribute is surrounded by double quotes. """ escaped = (attr .replace('&', '&amp;') .replace('"', '&quot;') .replace('<', '&lt;') .replace('>', '&gt;')) if not skip_single_quote: escaped = escaped.replace("'", "&#39;") return escaped def _xml_encode_email_char_at_random(ch): r = random() # Roughly 10% raw, 45% hex, 45% dec. # '@' *must* be encoded. I [John Gruber] insist. # Issue 26: '_' must be encoded. if r > 0.9 and ch not in "@_": return ch elif r < 0.45: # The [1:] is to drop leading '0': 0x63 -> x63 return '&#%s;' % hex(ord(ch))[1:] else: return '&#%s;' % ord(ch) #---- mainline class _NoReflowFormatter(optparse.IndentedHelpFormatter): """An optparse formatter that does NOT reflow the description.""" def format_description(self, description): return description or "" def _test(): import doctest doctest.testmod() def main(argv=None): if argv is None: argv = sys.argv if not logging.root.handlers: logging.basicConfig() usage = "usage: %prog [PATHS...]" version = "%prog "+__version__ parser = optparse.OptionParser(prog="markdown2", usage=usage, version=version, description=cmdln_desc, formatter=_NoReflowFormatter()) parser.add_option("-v", "--verbose", dest="log_level", action="store_const", const=logging.DEBUG, help="more verbose output") parser.add_option("--encoding", help="specify encoding of text content") parser.add_option("--html4tags", action="store_true", default=False, help="use HTML 4 style for empty element tags") parser.add_option("-s", "--safe", metavar="MODE", dest="safe_mode", help="sanitize literal HTML: 'escape' escapes " "HTML meta chars, 'replace' replaces with an " "[HTML_REMOVED] note") parser.add_option("-x", "--extras", action="append", help="Turn on specific extra features (not part of " "the core Markdown spec). See above.") parser.add_option("--use-file-vars", help="Look for and use Emacs-style 'markdown-extras' " "file var to turn on extras. See " "<https://github.com/trentm/python-markdown2/wiki/Extras>") parser.add_option("--link-patterns-file", help="path to a link pattern file") parser.add_option("--self-test", action="store_true", help="run internal self-tests (some doctests)") parser.add_option("--compare", action="store_true", help="run against Markdown.pl as well (for testing)") parser.set_defaults(log_level=logging.INFO, compare=False, encoding="utf-8", safe_mode=None, use_file_vars=False) opts, paths = parser.parse_args() log.setLevel(opts.log_level) if opts.self_test: return _test() if opts.extras: extras = {} for s in opts.extras: splitter = re.compile("[,;: ]+") for e in splitter.split(s): if '=' in e: ename, earg = e.split('=', 1) try: earg = int(earg) except ValueError: pass else: ename, earg = e, None extras[ename] = earg else: extras = None if opts.link_patterns_file: link_patterns = [] f = open(opts.link_patterns_file) try: for i, line in enumerate(f.readlines()): if not line.strip(): continue if line.lstrip().startswith("#"): continue try: pat, href = line.rstrip().rsplit(None, 1) except ValueError: raise MarkdownError("%s:%d: invalid link pattern line: %r" % (opts.link_patterns_file, i+1, line)) link_patterns.append( (_regex_from_encoded_pattern(pat), href)) finally: f.close() else: link_patterns = None from os.path import join, dirname, abspath, exists markdown_pl = join(dirname(dirname(abspath(__file__))), "test", "Markdown.pl") if not paths: paths = ['-'] for path in paths: if path == '-': text = sys.stdin.read() else: fp = codecs.open(path, 'r', opts.encoding) text = fp.read() fp.close() if opts.compare: from subprocess import Popen, PIPE print("==== Markdown.pl ====") p = Popen('perl %s' % markdown_pl, shell=True, stdin=PIPE, stdout=PIPE, close_fds=True) p.stdin.write(text.encode('utf-8')) p.stdin.close() perl_html = p.stdout.read().decode('utf-8') if py3: sys.stdout.write(perl_html) else: sys.stdout.write(perl_html.encode( sys.stdout.encoding or "utf-8", 'xmlcharrefreplace')) print("==== markdown2.py ====") html = markdown(text, html4tags=opts.html4tags, safe_mode=opts.safe_mode, extras=extras, link_patterns=link_patterns, use_file_vars=opts.use_file_vars) if py3: sys.stdout.write(html) else: sys.stdout.write(html.encode( sys.stdout.encoding or "utf-8", 'xmlcharrefreplace')) if extras and "toc" in extras: log.debug("toc_html: " + html.toc_html.encode(sys.stdout.encoding or "utf-8", 'xmlcharrefreplace')) if opts.compare: test_dir = join(dirname(dirname(abspath(__file__))), "test") if exists(join(test_dir, "test_markdown2.py")): sys.path.insert(0, test_dir) from test_markdown2 import norm_html_from_html norm_html = norm_html_from_html(html) norm_perl_html = norm_html_from_html(perl_html) else: norm_html = html norm_perl_html = perl_html print("==== match? %r ====" % (norm_perl_html == norm_html)) template_html = u'''<!DOCTYPE html> <!-- Backdoc is a tool for backbone-like documentation generation. Backdoc main goal is to help to generate one page documentation from one markdown source file. https://github.com/chibisov/backdoc --> <html lang="ru"> <head> <meta charset="UTF-8"/> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> <meta name="HandheldFriendly" content="true" /> <title><!-- title --></title> <!-- Bootstrap --> <style type="text/css"> /*! * Bootstrap v3.0.0 * * Copyright 2013 Twitter, Inc * Licensed under the Apache License v2.0 * http://www.apache.org/licenses/LICENSE-2.0 * * Designed and built with all the love in the world by @mdo and @fat. *//*! normalize.css v2.1.0 | MIT License | git.io/normalize */ article,aside,details,figcaption,figure,footer,header,hgroup,main,nav,section,summary{display:block}audio,canvas,video{display:inline-block}audio:not([controls]){display:none;height:0}[hidden]{display:none}html{font-family:sans-serif;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%}body{margin:0}a:focus{outline:thin dotted}a:active,a:hover{outline:0}h1{margin:.67em 0;font-size:2em}abbr[title]{border-bottom:1px dotted}b,strong{font-weight:bold}dfn{font-style:italic}hr{height:0;-moz-box-sizing:content-box;box-sizing:content-box}mark{color:#000;background:#ff0}code,kbd,pre,samp{font-family:monospace,serif;font-size:1em}pre{white-space:pre-wrap}q{quotes:"\201C" "\201D" "\2018" "\2019"}small{font-size:80%}sub,sup{position:relative;font-size:75%;line-height:0;vertical-align:baseline}sup{top:-0.5em}sub{bottom:-0.25em}img{border:0}svg:not(:root){overflow:hidden}figure{margin:0}fieldset{padding:.35em .625em .75em;margin:0 2px;border:1px solid #c0c0c0}legend{padding:0;border:0}button,input,select,textarea{margin:0;font-family:inherit;font-size:100%}button,input{line-height:normal}button,select{text-transform:none}button,html input[type="button"],input[type="reset"],input[type="submit"]{cursor:pointer;-webkit-appearance:button}button[disabled],html input[disabled]{cursor:default}input[type="checkbox"],input[type="radio"]{padding:0;box-sizing:border-box}input[type="search"]{-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;-webkit-appearance:textfield}input[type="search"]::-webkit-search-cancel-button,input[type="search"]::-webkit-search-decoration{-webkit-appearance:none}button::-moz-focus-inner,input::-moz-focus-inner{padding:0;border:0}textarea{overflow:auto;vertical-align:top}table{border-collapse:collapse;border-spacing:0}@media print{*{color:#000!important;text-shadow:none!important;background:transparent!important;box-shadow:none!important}a,a:visited{text-decoration:underline}a[href]:after{content:" (" attr(href) ")"}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100%!important}@page{margin:2cm .5cm}p,h2,h3{orphans:3;widows:3}h2,h3{page-break-after:avoid}.navbar{display:none}.table td,.table th{background-color:#fff!important}.btn>.caret,.dropup>.btn>.caret{border-top-color:#000!important}.label{border:1px solid #000}.table{border-collapse:collapse!important}.table-bordered th,.table-bordered td{border:1px solid #ddd!important}}*{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}html{font-size:62.5%;-webkit-tap-highlight-color:rgba(0,0,0,0)}body{font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px;line-height:1.428571429;color:#333;background-color:#fff}input,button,select,textarea{font-family:inherit;font-size:inherit;line-height:inherit}a{color:#428bca;text-decoration:none}a:hover,a:focus{color:#2a6496;text-decoration:underline}a:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}img{vertical-align:middle}.img-responsive{display:inline-block;height:auto;max-width:100%}.img-rounded{border-radius:6px}.img-circle{border-radius:500px}hr{margin-top:20px;margin-bottom:20px;border:0;border-top:1px solid #eee}p{margin:0 0 10px}.lead{margin-bottom:20px;font-size:16.099999999999998px;font-weight:200;line-height:1.4}@media(min-width:768px){.lead{font-size:21px}}small{font-size:85%}cite{font-style:normal}.text-muted{color:#999}.text-primary{color:#428bca}.text-warning{color:#c09853}.text-danger{color:#b94a48}.text-success{color:#468847}.text-info{color:#3a87ad}.text-left{text-align:left}.text-right{text-align:right}.text-center{text-align:center}h1,h2,h3,h4,h5,h6,.h1,.h2,.h3,.h4,.h5,.h6{font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-weight:500;line-height:1.1}h1 small,h2 small,h3 small,h4 small,h5 small,h6 small,.h1 small,.h2 small,.h3 small,.h4 small,.h5 small,.h6 small{font-weight:normal;line-height:1;color:#999}h1,h2,h3{margin-top:20px;margin-bottom:10px}h4,h5,h6{margin-top:10px;margin-bottom:10px}h1,.h1{font-size:38px}h2,.h2{font-size:32px}h3,.h3{font-size:24px}h4,.h4{font-size:18px}h5,.h5{font-size:14px}h6,.h6{font-size:12px}h1 small,.h1 small{font-size:24px}h2 small,.h2 small{font-size:18px}h3 small,.h3 small,h4 small,.h4 small{font-size:14px}.page-header{padding-bottom:9px;margin:40px 0 20px;border-bottom:1px solid #eee}ul,ol{margin-top:0;margin-bottom:10px}ul ul,ol ul,ul ol,ol ol{margin-bottom:0}.list-unstyled{padding-left:0;list-style:none}.list-inline{padding-left:0;list-style:none}.list-inline>li{display:inline-block;padding-right:5px;padding-left:5px}dl{margin-bottom:20px}dt,dd{line-height:1.428571429}dt{font-weight:bold}dd{margin-left:0}.dl-horizontal dt{float:left;width:160px;overflow:hidden;clear:left;text-align:right;text-overflow:ellipsis;white-space:nowrap}.dl-horizontal dd{margin-left:180px}.dl-horizontal dd:before,.dl-horizontal dd:after{display:table;content:" "}.dl-horizontal dd:after{clear:both}.dl-horizontal dd:before,.dl-horizontal dd:after{display:table;content:" "}.dl-horizontal dd:after{clear:both}abbr[title],abbr[data-original-title]{cursor:help;border-bottom:1px dotted #999}abbr.initialism{font-size:90%;text-transform:uppercase}blockquote{padding:10px 20px;margin:0 0 20px;border-left:5px solid #eee}blockquote p{font-size:17.5px;font-weight:300;line-height:1.25}blockquote p:last-child{margin-bottom:0}blockquote small{display:block;line-height:1.428571429;color:#999}blockquote small:before{content:'\2014 \00A0'}blockquote.pull-right{float:right;padding-right:15px;padding-left:0;border-right:5px solid #eee;border-left:0}blockquote.pull-right p,blockquote.pull-right small{text-align:right}blockquote.pull-right small:before{content:''}blockquote.pull-right small:after{content:'\00A0 \2014'}q:before,q:after,blockquote:before,blockquote:after{content:""}address{display:block;margin-bottom:20px;font-style:normal;line-height:1.428571429}code,pre{font-family:Monaco,Menlo,Consolas,"Courier New",monospace}code{padding:2px 4px;font-size:90%;color:#c7254e;white-space:nowrap;background-color:#f9f2f4;border-radius:4px}pre{display:block;padding:9.5px;margin:0 0 10px;font-size:13px;line-height:1.428571429;color:#333;word-break:break-all;word-wrap:break-word;background-color:#f5f5f5;border:1px solid #ccc;border-radius:4px}pre.prettyprint{margin-bottom:20px}pre code{padding:0;color:inherit;white-space:pre-wrap;background-color:transparent;border:0}.pre-scrollable{max-height:340px;overflow-y:scroll}.container{margin-right:auto;margin-left:auto}.container:before,.container:after{display:table;content:" "}.container:after{clear:both}.container:before,.container:after{display:table;content:" "}.container:after{clear:both}.row:before,.row:after{display:table;content:" "}.row:after{clear:both}.row:before,.row:after{display:table;content:" "}.row:after{clear:both}@media(min-width:768px){.row{margin-right:-15px;margin-left:-15px}}.row .row{margin-right:-15px;margin-left:-15px}.col-1,.col-2,.col-3,.col-4,.col-5,.col-6,.col-7,.col-8,.col-9,.col-10,.col-11,.col-12,.col-sm-1,.col-sm-2,.col-sm-3,.col-sm-4,.col-sm-5,.col-sm-6,.col-sm-7,.col-sm-8,.col-sm-9,.col-sm-10,.col-sm-11,.col-sm-12,.col-lg-1,.col-lg-2,.col-lg-3,.col-lg-4,.col-lg-5,.col-lg-6,.col-lg-7,.col-lg-8,.col-lg-9,.col-lg-10,.col-lg-11,.col-lg-12{position:relative;min-height:1px;padding-right:15px;padding-left:15px}.col-1,.col-2,.col-3,.col-4,.col-5,.col-6,.col-7,.col-8,.col-9,.col-10,.col-11,.col-12{float:left}.col-1{width:8.333333333333332%}.col-2{width:16.666666666666664%}.col-3{width:25%}.col-4{width:33.33333333333333%}.col-5{width:41.66666666666667%}.col-6{width:50%}.col-7{width:58.333333333333336%}.col-8{width:66.66666666666666%}.col-9{width:75%}.col-10{width:83.33333333333334%}.col-11{width:91.66666666666666%}.col-12{width:100%}@media(min-width:768px){.container{max-width:728px}.col-sm-1,.col-sm-2,.col-sm-3,.col-sm-4,.col-sm-5,.col-sm-6,.col-sm-7,.col-sm-8,.col-sm-9,.col-sm-10,.col-sm-11,.col-sm-12{float:left}.col-sm-1{width:8.333333333333332%}.col-sm-2{width:16.666666666666664%}.col-sm-3{width:25%}.col-sm-4{width:33.33333333333333%}.col-sm-5{width:41.66666666666667%}.col-sm-6{width:50%}.col-sm-7{width:58.333333333333336%}.col-sm-8{width:66.66666666666666%}.col-sm-9{width:75%}.col-sm-10{width:83.33333333333334%}.col-sm-11{width:91.66666666666666%}.col-sm-12{width:100%}.col-push-1{left:8.333333333333332%}.col-push-2{left:16.666666666666664%}.col-push-3{left:25%}.col-push-4{left:33.33333333333333%}.col-push-5{left:41.66666666666667%}.col-push-6{left:50%}.col-push-7{left:58.333333333333336%}.col-push-8{left:66.66666666666666%}.col-push-9{left:75%}.col-push-10{left:83.33333333333334%}.col-push-11{left:91.66666666666666%}.col-pull-1{right:8.333333333333332%}.col-pull-2{right:16.666666666666664%}.col-pull-3{right:25%}.col-pull-4{right:33.33333333333333%}.col-pull-5{right:41.66666666666667%}.col-pull-6{right:50%}.col-pull-7{right:58.333333333333336%}.col-pull-8{right:66.66666666666666%}.col-pull-9{right:75%}.col-pull-10{right:83.33333333333334%}.col-pull-11{right:91.66666666666666%}}@media(min-width:992px){.container{max-width:940px}.col-lg-1,.col-lg-2,.col-lg-3,.col-lg-4,.col-lg-5,.col-lg-6,.col-lg-7,.col-lg-8,.col-lg-9,.col-lg-10,.col-lg-11,.col-lg-12{float:left}.col-lg-1{width:8.333333333333332%}.col-lg-2{width:16.666666666666664%}.col-lg-3{width:25%}.col-lg-4{width:33.33333333333333%}.col-lg-5{width:41.66666666666667%}.col-lg-6{width:50%}.col-lg-7{width:58.333333333333336%}.col-lg-8{width:66.66666666666666%}.col-lg-9{width:75%}.col-lg-10{width:83.33333333333334%}.col-lg-11{width:91.66666666666666%}.col-lg-12{width:100%}.col-offset-1{margin-left:8.333333333333332%}.col-offset-2{margin-left:16.666666666666664%}.col-offset-3{margin-left:25%}.col-offset-4{margin-left:33.33333333333333%}.col-offset-5{margin-left:41.66666666666667%}.col-offset-6{margin-left:50%}.col-offset-7{margin-left:58.333333333333336%}.col-offset-8{margin-left:66.66666666666666%}.col-offset-9{margin-left:75%}.col-offset-10{margin-left:83.33333333333334%}.col-offset-11{margin-left:91.66666666666666%}}@media(min-width:1200px){.container{max-width:1170px}}table{max-width:100%;background-color:transparent}th{text-align:left}.table{width:100%;margin-bottom:20px}.table thead>tr>th,.table tbody>tr>th,.table tfoot>tr>th,.table thead>tr>td,.table tbody>tr>td,.table tfoot>tr>td{padding:8px;line-height:1.428571429;vertical-align:top;border-top:1px solid #ddd}.table thead>tr>th{vertical-align:bottom}.table caption+thead tr:first-child th,.table colgroup+thead tr:first-child th,.table thead:first-child tr:first-child th,.table caption+thead tr:first-child td,.table colgroup+thead tr:first-child td,.table thead:first-child tr:first-child td{border-top:0}.table tbody+tbody{border-top:2px solid #ddd}.table .table{background-color:#fff}.table-condensed thead>tr>th,.table-condensed tbody>tr>th,.table-condensed tfoot>tr>th,.table-condensed thead>tr>td,.table-condensed tbody>tr>td,.table-condensed tfoot>tr>td{padding:5px}.table-bordered{border:1px solid #ddd}.table-bordered>thead>tr>th,.table-bordered>tbody>tr>th,.table-bordered>tfoot>tr>th,.table-bordered>thead>tr>td,.table-bordered>tbody>tr>td,.table-bordered>tfoot>tr>td{border:1px solid #ddd}.table-striped>tbody>tr:nth-child(odd)>td,.table-striped>tbody>tr:nth-child(odd)>th{background-color:#f9f9f9}.table-hover>tbody>tr:hover>td,.table-hover>tbody>tr:hover>th{background-color:#f5f5f5}table col[class^="col-"]{display:table-column;float:none}table td[class^="col-"],table th[class^="col-"]{display:table-cell;float:none}.table>thead>tr>td.active,.table>tbody>tr>td.active,.table>tfoot>tr>td.active,.table>thead>tr>th.active,.table>tbody>tr>th.active,.table>tfoot>tr>th.active,.table>thead>tr.active>td,.table>tbody>tr.active>td,.table>tfoot>tr.active>td,.table>thead>tr.active>th,.table>tbody>tr.active>th,.table>tfoot>tr.active>th{background-color:#f5f5f5}.table>thead>tr>td.success,.table>tbody>tr>td.success,.table>tfoot>tr>td.success,.table>thead>tr>th.success,.table>tbody>tr>th.success,.table>tfoot>tr>th.success,.table>thead>tr.success>td,.table>tbody>tr.success>td,.table>tfoot>tr.success>td,.table>thead>tr.success>th,.table>tbody>tr.success>th,.table>tfoot>tr.success>th{background-color:#dff0d8;border-color:#d6e9c6}.table>thead>tr>td.danger,.table>tbody>tr>td.danger,.table>tfoot>tr>td.danger,.table>thead>tr>th.danger,.table>tbody>tr>th.danger,.table>tfoot>tr>th.danger,.table>thead>tr.danger>td,.table>tbody>tr.danger>td,.table>tfoot>tr.danger>td,.table>thead>tr.danger>th,.table>tbody>tr.danger>th,.table>tfoot>tr.danger>th{background-color:#f2dede;border-color:#eed3d7}.table>thead>tr>td.warning,.table>tbody>tr>td.warning,.table>tfoot>tr>td.warning,.table>thead>tr>th.warning,.table>tbody>tr>th.warning,.table>tfoot>tr>th.warning,.table>thead>tr.warning>td,.table>tbody>tr.warning>td,.table>tfoot>tr.warning>td,.table>thead>tr.warning>th,.table>tbody>tr.warning>th,.table>tfoot>tr.warning>th{background-color:#fcf8e3;border-color:#fbeed5}.table-hover>tbody>tr>td.success:hover,.table-hover>tbody>tr>th.success:hover,.table-hover>tbody>tr.success:hover>td{background-color:#d0e9c6;border-color:#c9e2b3}.table-hover>tbody>tr>td.danger:hover,.table-hover>tbody>tr>th.danger:hover,.table-hover>tbody>tr.danger:hover>td{background-color:#ebcccc;border-color:#e6c1c7}.table-hover>tbody>tr>td.warning:hover,.table-hover>tbody>tr>th.warning:hover,.table-hover>tbody>tr.warning:hover>td{background-color:#faf2cc;border-color:#f8e5be}fieldset{padding:0;margin:0;border:0}legend{display:block;width:100%;padding:0;margin-bottom:20px;font-size:21px;line-height:inherit;color:#333;border:0;border-bottom:1px solid #e5e5e5}label{display:inline-block;margin-bottom:5px;font-weight:bold}input[type="search"]{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}input[type="radio"],input[type="checkbox"]{margin:4px 0 0;margin-top:1px \9;line-height:normal}input[type="file"]{display:block}select[multiple],select[size]{height:auto}select optgroup{font-family:inherit;font-size:inherit;font-style:inherit}input[type="file"]:focus,input[type="radio"]:focus,input[type="checkbox"]:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}input[type="number"]::-webkit-outer-spin-button,input[type="number"]::-webkit-inner-spin-button{height:auto}.form-control:-moz-placeholder{color:#999}.form-control::-moz-placeholder{color:#999}.form-control:-ms-input-placeholder{color:#999}.form-control::-webkit-input-placeholder{color:#999}.form-control{display:block;width:100%;height:38px;padding:8px 12px;font-size:14px;line-height:1.428571429;color:#555;vertical-align:middle;background-color:#fff;border:1px solid #ccc;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);-webkit-transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s;transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s}.form-control:focus{border-color:rgba(82,168,236,0.8);outline:0;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6)}.form-control[disabled],.form-control[readonly],fieldset[disabled] .form-control{cursor:not-allowed;background-color:#eee}textarea.form-control{height:auto}.form-group{margin-bottom:15px}.radio,.checkbox{display:block;min-height:20px;padding-left:20px;margin-top:10px;margin-bottom:10px;vertical-align:middle}.radio label,.checkbox label{display:inline;margin-bottom:0;font-weight:normal;cursor:pointer}.radio input[type="radio"],.radio-inline input[type="radio"],.checkbox input[type="checkbox"],.checkbox-inline input[type="checkbox"]{float:left;margin-left:-20px}.radio+.radio,.checkbox+.checkbox{margin-top:-5px}.radio-inline,.checkbox-inline{display:inline-block;padding-left:20px;margin-bottom:0;font-weight:normal;vertical-align:middle;cursor:pointer}.radio-inline+.radio-inline,.checkbox-inline+.checkbox-inline{margin-top:0;margin-left:10px}.form-control.input-large{height:56px;padding:14px 16px;font-size:18px;border-radius:6px}.form-control.input-small{height:30px;padding:5px 10px;font-size:12px;border-radius:3px}select.input-large{height:56px;line-height:56px}select.input-small{height:30px;line-height:30px}.has-warning .help-block,.has-warning .control-label{color:#c09853}.has-warning .form-control{padding-right:32px;border-color:#c09853;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075)}.has-warning .form-control:focus{border-color:#a47e3c;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #dbc59e;box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #dbc59e}.has-warning .input-group-addon{color:#c09853;background-color:#fcf8e3;border-color:#c09853}.has-error .help-block,.has-error .control-label{color:#b94a48}.has-error .form-control{padding-right:32px;border-color:#b94a48;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075)}.has-error .form-control:focus{border-color:#953b39;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #d59392;box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #d59392}.has-error .input-group-addon{color:#b94a48;background-color:#f2dede;border-color:#b94a48}.has-success .help-block,.has-success .control-label{color:#468847}.has-success .form-control{padding-right:32px;border-color:#468847;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075)}.has-success .form-control:focus{border-color:#356635;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7aba7b;box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7aba7b}.has-success .input-group-addon{color:#468847;background-color:#dff0d8;border-color:#468847}.help-block{display:block;margin-top:5px;margin-bottom:10px;color:#737373}.input-group{display:table;border-collapse:separate}.input-group.col{float:none;padding-right:0;padding-left:0}.input-group .form-control{width:100%;margin-bottom:0}.input-group-addon,.input-group-btn,.input-group .form-control{display:table-cell}.input-group-addon:not(:first-child):not(:last-child),.input-group-btn:not(:first-child):not(:last-child),.input-group .form-control:not(:first-child):not(:last-child){border-radius:0}.input-group-addon,.input-group-btn{width:1%;white-space:nowrap;vertical-align:middle}.input-group-addon{padding:8px 12px;font-size:14px;font-weight:normal;line-height:1.428571429;text-align:center;background-color:#eee;border:1px solid #ccc;border-radius:4px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.input-group-addon.input-small{padding:5px 10px;font-size:12px;border-radius:3px}.input-group-addon.input-large{padding:14px 16px;font-size:18px;border-radius:6px}.input-group .form-control:first-child,.input-group-addon:first-child,.input-group-btn:first-child>.btn,.input-group-btn:first-child>.dropdown-toggle,.input-group-btn:last-child>.btn:not(:last-child):not(.dropdown-toggle){border-top-right-radius:0;border-bottom-right-radius:0}.input-group-addon:first-child{border-right:0}.input-group .form-control:last-child,.input-group-addon:last-child,.input-group-btn:last-child>.btn,.input-group-btn:last-child>.dropdown-toggle,.input-group-btn:first-child>.btn:not(:first-child){border-bottom-left-radius:0;border-top-left-radius:0}.input-group-addon:last-child{border-left:0}.input-group-btn{position:relative;white-space:nowrap}.input-group-btn>.btn{position:relative}.input-group-btn>.btn+.btn{margin-left:-4px}.input-group-btn>.btn:hover,.input-group-btn>.btn:active{z-index:2}.form-inline .form-control,.form-inline .radio,.form-inline .checkbox{display:inline-block}.form-inline .radio,.form-inline .checkbox{margin-top:0;margin-bottom:0}.form-horizontal .control-label{padding-top:6px}.form-horizontal .form-group:before,.form-horizontal .form-group:after{display:table;content:" "}.form-horizontal .form-group:after{clear:both}.form-horizontal .form-group:before,.form-horizontal .form-group:after{display:table;content:" "}.form-horizontal .form-group:after{clear:both}@media(min-width:768px){.form-horizontal .form-group{margin-right:-15px;margin-left:-15px}}.form-horizontal .form-group .row{margin-right:-15px;margin-left:-15px}@media(min-width:768px){.form-horizontal .control-label{text-align:right}}.btn{display:inline-block;padding:8px 12px;margin-bottom:0;font-size:14px;font-weight:500;line-height:1.428571429;text-align:center;white-space:nowrap;vertical-align:middle;cursor:pointer;border:1px solid transparent;border-radius:4px}.btn:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn:hover,.btn:focus{color:#fff;text-decoration:none}.btn:active,.btn.active{outline:0;-webkit-box-shadow:inset 0 3px 5px rgba(0,0,0,0.125);box-shadow:inset 0 3px 5px rgba(0,0,0,0.125)}.btn.disabled,.btn[disabled],fieldset[disabled] .btn{pointer-events:none;cursor:default;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;box-shadow:none}.btn-default{color:#fff;background-color:#474949;border-color:#474949}.btn-default:hover,.btn-default:focus,.btn-default:active,.btn-default.active{background-color:#3a3c3c;border-color:#2e2f2f}.btn-default.disabled,.btn-default[disabled],fieldset[disabled] .btn-default,.btn-default.disabled:hover,.btn-default[disabled]:hover,fieldset[disabled] .btn-default:hover,.btn-default.disabled:focus,.btn-default[disabled]:focus,fieldset[disabled] .btn-default:focus,.btn-default.disabled:active,.btn-default[disabled]:active,fieldset[disabled] .btn-default:active,.btn-default.disabled.active,.btn-default[disabled].active,fieldset[disabled] .btn-default.active{background-color:#474949;border-color:#474949}.btn-primary{color:#fff;background-color:#428bca;border-color:#428bca}.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active{background-color:#357ebd;border-color:#3071a9}.btn-primary.disabled,.btn-primary[disabled],fieldset[disabled] .btn-primary,.btn-primary.disabled:hover,.btn-primary[disabled]:hover,fieldset[disabled] .btn-primary:hover,.btn-primary.disabled:focus,.btn-primary[disabled]:focus,fieldset[disabled] .btn-primary:focus,.btn-primary.disabled:active,.btn-primary[disabled]:active,fieldset[disabled] .btn-primary:active,.btn-primary.disabled.active,.btn-primary[disabled].active,fieldset[disabled] .btn-primary.active{background-color:#428bca;border-color:#428bca}.btn-warning{color:#fff;background-color:#f0ad4e;border-color:#f0ad4e}.btn-warning:hover,.btn-warning:focus,.btn-warning:active,.btn-warning.active{background-color:#eea236;border-color:#ec971f}.btn-warning.disabled,.btn-warning[disabled],fieldset[disabled] .btn-warning,.btn-warning.disabled:hover,.btn-warning[disabled]:hover,fieldset[disabled] .btn-warning:hover,.btn-warning.disabled:focus,.btn-warning[disabled]:focus,fieldset[disabled] .btn-warning:focus,.btn-warning.disabled:active,.btn-warning[disabled]:active,fieldset[disabled] .btn-warning:active,.btn-warning.disabled.active,.btn-warning[disabled].active,fieldset[disabled] .btn-warning.active{background-color:#f0ad4e;border-color:#f0ad4e}.btn-danger{color:#fff;background-color:#d9534f;border-color:#d9534f}.btn-danger:hover,.btn-danger:focus,.btn-danger:active,.btn-danger.active{background-color:#d43f3a;border-color:#c9302c}.btn-danger.disabled,.btn-danger[disabled],fieldset[disabled] .btn-danger,.btn-danger.disabled:hover,.btn-danger[disabled]:hover,fieldset[disabled] .btn-danger:hover,.btn-danger.disabled:focus,.btn-danger[disabled]:focus,fieldset[disabled] .btn-danger:focus,.btn-danger.disabled:active,.btn-danger[disabled]:active,fieldset[disabled] .btn-danger:active,.btn-danger.disabled.active,.btn-danger[disabled].active,fieldset[disabled] .btn-danger.active{background-color:#d9534f;border-color:#d9534f}.btn-success{color:#fff;background-color:#5cb85c;border-color:#5cb85c}.btn-success:hover,.btn-success:focus,.btn-success:active,.btn-success.active{background-color:#4cae4c;border-color:#449d44}.btn-success.disabled,.btn-success[disabled],fieldset[disabled] .btn-success,.btn-success.disabled:hover,.btn-success[disabled]:hover,fieldset[disabled] .btn-success:hover,.btn-success.disabled:focus,.btn-success[disabled]:focus,fieldset[disabled] .btn-success:focus,.btn-success.disabled:active,.btn-success[disabled]:active,fieldset[disabled] .btn-success:active,.btn-success.disabled.active,.btn-success[disabled].active,fieldset[disabled] .btn-success.active{background-color:#5cb85c;border-color:#5cb85c}.btn-info{color:#fff;background-color:#5bc0de;border-color:#5bc0de}.btn-info:hover,.btn-info:focus,.btn-info:active,.btn-info.active{background-color:#46b8da;border-color:#31b0d5}.btn-info.disabled,.btn-info[disabled],fieldset[disabled] .btn-info,.btn-info.disabled:hover,.btn-info[disabled]:hover,fieldset[disabled] .btn-info:hover,.btn-info.disabled:focus,.btn-info[disabled]:focus,fieldset[disabled] .btn-info:focus,.btn-info.disabled:active,.btn-info[disabled]:active,fieldset[disabled] .btn-info:active,.btn-info.disabled.active,.btn-info[disabled].active,fieldset[disabled] .btn-info.active{background-color:#5bc0de;border-color:#5bc0de}.btn-link{font-weight:normal;color:#428bca;cursor:pointer;border-radius:0}.btn-link,.btn-link:active,.btn-link[disabled],fieldset[disabled] .btn-link{background-color:transparent;-webkit-box-shadow:none;box-shadow:none}.btn-link,.btn-link:hover,.btn-link:focus,.btn-link:active{border-color:transparent}.btn-link:hover,.btn-link:focus{color:#2a6496;text-decoration:underline;background-color:transparent}.btn-link[disabled]:hover,fieldset[disabled] .btn-link:hover,.btn-link[disabled]:focus,fieldset[disabled] .btn-link:focus{color:#333;text-decoration:none}.btn-large{padding:14px 16px;font-size:18px;border-radius:6px}.btn-small{padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}.btn-block{display:block;width:100%;padding-right:0;padding-left:0}.btn-block+.btn-block{margin-top:5px}input[type="submit"].btn-block,input[type="reset"].btn-block,input[type="button"].btn-block{width:100%}.fade{opacity:0;-webkit-transition:opacity .15s linear;transition:opacity .15s linear}.fade.in{opacity:1}.collapse{display:none}.collapse.in{display:block}.collapsing{position:relative;height:0;overflow:hidden;-webkit-transition:height .35s ease;transition:height .35s ease}.caret{display:inline-block;width:0;height:0;margin-left:2px;vertical-align:middle;border-top:4px solid #000;border-right:4px solid transparent;border-left:4px solid transparent;content:""}.dropdown-menu{position:absolute;top:100%;left:0;z-index:1000;display:none;float:left;min-width:160px;padding:5px 0;margin:2px 0 0;list-style:none;background-color:#fff;border:1px solid #ccc;border:1px solid rgba(0,0,0,0.15);border-radius:4px;-webkit-box-shadow:0 6px 12px rgba(0,0,0,0.175);box-shadow:0 6px 12px rgba(0,0,0,0.175);background-clip:padding-box}.dropdown-menu.pull-right{right:0;left:auto}.dropdown-menu .divider{height:1px;margin:9px 0;overflow:hidden;background-color:#e5e5e5}.dropdown-menu>li>a{display:block;padding:3px 20px;clear:both;font-weight:normal;line-height:1.428571429;color:#333;white-space:nowrap}.dropdown-menu>li>a:hover,.dropdown-menu>li>a:focus{color:#fff;text-decoration:none;background-color:#357ebd;background-image:-webkit-gradient(linear,left 0,left 100%,from(#428bca),to(#357ebd));background-image:-webkit-linear-gradient(top,#428bca,0%,#357ebd,100%);background-image:-moz-linear-gradient(top,#428bca 0,#357ebd 100%);background-image:linear-gradient(to bottom,#428bca 0,#357ebd 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff428bca',endColorstr='#ff357ebd',GradientType=0)}.dropdown-menu>.active>a,.dropdown-menu>.active>a:hover,.dropdown-menu>.active>a:focus{color:#fff;text-decoration:none;background-color:#357ebd;background-image:-webkit-gradient(linear,left 0,left 100%,from(#428bca),to(#357ebd));background-image:-webkit-linear-gradient(top,#428bca,0%,#357ebd,100%);background-image:-moz-linear-gradient(top,#428bca 0,#357ebd 100%);background-image:linear-gradient(to bottom,#428bca 0,#357ebd 100%);background-repeat:repeat-x;outline:0;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff428bca',endColorstr='#ff357ebd',GradientType=0)}.dropdown-menu>.disabled>a,.dropdown-menu>.disabled>a:hover,.dropdown-menu>.disabled>a:focus{color:#999}.dropdown-menu>.disabled>a:hover,.dropdown-menu>.disabled>a:focus{text-decoration:none;cursor:not-allowed;background-color:transparent;background-image:none;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.open>.dropdown-menu{display:block}.open>a{outline:0}.dropdown-header{display:block;padding:3px 20px;font-size:12px;line-height:1.428571429;color:#999}.dropdown-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:990}.pull-right>.dropdown-menu{right:0;left:auto}.dropup .caret,.navbar-fixed-bottom .dropdown .caret{border-top:0;border-bottom:4px solid #000;content:""}.dropup .dropdown-menu,.navbar-fixed-bottom .dropdown .dropdown-menu{top:auto;bottom:100%;margin-bottom:1px}.list-group{padding-left:0;margin-bottom:20px;background-color:#fff}.list-group-item{position:relative;display:block;padding:10px 30px 10px 15px;margin-bottom:-1px;border:1px solid #ddd}.list-group-item:first-child{border-top-right-radius:4px;border-top-left-radius:4px}.list-group-item:last-child{margin-bottom:0;border-bottom-right-radius:4px;border-bottom-left-radius:4px}.list-group-item>.badge{float:right;margin-right:-15px}.list-group-item-heading{margin-top:0;margin-bottom:5px}.list-group-item-text{margin-bottom:0;line-height:1.3}a.list-group-item .list-group-item-heading{color:#333}a.list-group-item .list-group-item-text{color:#555}a.list-group-item:hover,a.list-group-item:focus{text-decoration:none;background-color:#f5f5f5}a.list-group-item.active{z-index:2;color:#fff;background-color:#428bca;border-color:#428bca}a.list-group-item.active .list-group-item-heading{color:inherit}a.list-group-item.active .list-group-item-text{color:#e1edf7}.panel{padding:15px;margin-bottom:20px;background-color:#fff;border:1px solid #ddd;border-radius:4px;-webkit-box-shadow:0 1px 1px rgba(0,0,0,0.05);box-shadow:0 1px 1px rgba(0,0,0,0.05)}.panel-heading{padding:10px 15px;margin:-15px -15px 15px;background-color:#f5f5f5;border-bottom:1px solid #ddd;border-top-right-radius:3px;border-top-left-radius:3px}.panel-title{margin-top:0;margin-bottom:0;font-size:17.5px;font-weight:500}.panel-footer{padding:10px 15px;margin:15px -15px -15px;background-color:#f5f5f5;border-top:1px solid #ddd;border-bottom-right-radius:3px;border-bottom-left-radius:3px}.panel-primary{border-color:#428bca}.panel-primary .panel-heading{color:#fff;background-color:#428bca;border-color:#428bca}.panel-success{border-color:#d6e9c6}.panel-success .panel-heading{color:#468847;background-color:#dff0d8;border-color:#d6e9c6}.panel-warning{border-color:#fbeed5}.panel-warning .panel-heading{color:#c09853;background-color:#fcf8e3;border-color:#fbeed5}.panel-danger{border-color:#eed3d7}.panel-danger .panel-heading{color:#b94a48;background-color:#f2dede;border-color:#eed3d7}.panel-info{border-color:#bce8f1}.panel-info .panel-heading{color:#3a87ad;background-color:#d9edf7;border-color:#bce8f1}.list-group-flush{margin:15px -15px -15px}.list-group-flush .list-group-item{border-width:1px 0}.list-group-flush .list-group-item:first-child{border-top-right-radius:0;border-top-left-radius:0}.list-group-flush .list-group-item:last-child{border-bottom:0}.well{min-height:20px;padding:19px;margin-bottom:20px;background-color:#f5f5f5;border:1px solid #e3e3e3;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.05);box-shadow:inset 0 1px 1px rgba(0,0,0,0.05)}.well blockquote{border-color:#ddd;border-color:rgba(0,0,0,0.15)}.well-large{padding:24px;border-radius:6px}.well-small{padding:9px;border-radius:3px}.close{float:right;font-size:21px;font-weight:bold;line-height:1;color:#000;text-shadow:0 1px 0 #fff;opacity:.2;filter:alpha(opacity=20)}.close:hover,.close:focus{color:#000;text-decoration:none;cursor:pointer;opacity:.5;filter:alpha(opacity=50)}button.close{padding:0;cursor:pointer;background:transparent;border:0;-webkit-appearance:none}.nav{padding-left:0;margin-bottom:0;list-style:none}.nav:before,.nav:after{display:table;content:" "}.nav:after{clear:both}.nav:before,.nav:after{display:table;content:" "}.nav:after{clear:both}.nav>li{position:relative;display:block}.nav>li>a{position:relative;display:block;padding:10px 15px}.nav>li>a:hover,.nav>li>a:focus{text-decoration:none;background-color:#eee}.nav>li.disabled>a{color:#999}.nav>li.disabled>a:hover,.nav>li.disabled>a:focus{color:#999;text-decoration:none;cursor:not-allowed;background-color:transparent}.nav>li+.nav-header{margin-top:9px}.nav.open>a,.nav.open>a:hover,.nav.open>a:focus{color:#fff;background-color:#428bca;border-color:#428bca}.nav.open>a .caret,.nav.open>a:hover .caret,.nav.open>a:focus .caret{border-top-color:#fff;border-bottom-color:#fff}.nav>.pull-right{float:right}.nav .nav-divider{height:1px;margin:9px 0;overflow:hidden;background-color:#e5e5e5}.nav-tabs{border-bottom:1px solid #ddd}.nav-tabs>li{float:left;margin-bottom:-1px}.nav-tabs>li>a{margin-right:2px;line-height:1.428571429;border:1px solid transparent;border-radius:4px 4px 0 0}.nav-tabs>li>a:hover{border-color:#eee}.nav-tabs>li.active>a,.nav-tabs>li.active>a:hover,.nav-tabs>li.active>a:focus{color:#555;cursor:default;background-color:#fff;border:1px solid #ddd;border-bottom-color:transparent}.nav-tabs.nav-justified{width:100%;border-bottom:0}.nav-tabs.nav-justified>li{display:table-cell;float:none;width:1%}.nav-tabs.nav-justified>li>a{text-align:center}.nav-tabs.nav-justified>li>a{margin-right:0;border-bottom:1px solid #ddd}.nav-tabs.nav-justified>.active>a{border-bottom-color:#fff}.nav-pills>li{float:left}.nav-pills>li>a{border-radius:5px}.nav-pills>li+li{margin-left:2px}.nav-pills>li.active>a,.nav-pills>li.active>a:hover,.nav-pills>li.active>a:focus{color:#fff;background-color:#428bca}.nav-stacked>li{float:none}.nav-stacked>li+li>a{margin-top:2px;margin-left:0}.nav-justified{width:100%}.nav-justified>li{display:table-cell;float:none;width:1%}.nav-justified>li>a{text-align:center}.nav-tabs-justified{border-bottom:0}.nav-tabs-justified>li>a{margin-right:0;border-bottom:1px solid #ddd}.nav-tabs-justified>.active>a{border-bottom-color:#fff}.tabbable:before,.tabbable:after{display:table;content:" "}.tabbable:after{clear:both}.tabbable:before,.tabbable:after{display:table;content:" "}.tabbable:after{clear:both}.tab-content>.tab-pane,.pill-content>.pill-pane{display:none}.tab-content>.active,.pill-content>.active{display:block}.nav .caret{border-top-color:#428bca;border-bottom-color:#428bca}.nav a:hover .caret{border-top-color:#2a6496;border-bottom-color:#2a6496}.nav-tabs .dropdown-menu{margin-top:-1px;border-top-right-radius:0;border-top-left-radius:0}.navbar{position:relative;min-height:50px;padding-right:15px;padding-left:15px;margin-bottom:20px;background-color:#eee;border-radius:4px}.navbar:before,.navbar:after{display:table;content:" "}.navbar:after{clear:both}.navbar:before,.navbar:after{display:table;content:" "}.navbar:after{clear:both}.navbar-nav{margin-top:10px;margin-bottom:15px}.navbar-nav>li>a{padding-top:15px;padding-bottom:15px;line-height:20px;color:#777;border-radius:4px}.navbar-nav>li>a:hover,.navbar-nav>li>a:focus{color:#333;background-color:transparent}.navbar-nav>.active>a,.navbar-nav>.active>a:hover,.navbar-nav>.active>a:focus{color:#555;background-color:#d5d5d5}.navbar-nav>.disabled>a,.navbar-nav>.disabled>a:hover,.navbar-nav>.disabled>a:focus{color:#ccc;background-color:transparent}.navbar-nav.pull-right{width:100%}.navbar-static-top{border-radius:0}.navbar-fixed-top,.navbar-fixed-bottom{position:fixed;right:0;left:0;z-index:1030;border-radius:0}.navbar-fixed-top{top:0}.navbar-fixed-bottom{bottom:0;margin-bottom:0}.navbar-brand{display:block;max-width:200px;padding:15px 15px;margin-right:auto;margin-left:auto;font-size:18px;font-weight:500;line-height:20px;color:#777;text-align:center}.navbar-brand:hover,.navbar-brand:focus{color:#5e5e5e;text-decoration:none;background-color:transparent}.navbar-toggle{position:absolute;top:9px;right:10px;width:48px;height:32px;padding:8px 12px;background-color:transparent;border:1px solid #ddd;border-radius:4px}.navbar-toggle:hover,.navbar-toggle:focus{background-color:#ddd}.navbar-toggle .icon-bar{display:block;width:22px;height:2px;background-color:#ccc;border-radius:1px}.navbar-toggle .icon-bar+.icon-bar{margin-top:4px}.navbar-form{margin-top:6px;margin-bottom:6px}.navbar-form .form-control,.navbar-form .radio,.navbar-form .checkbox{display:inline-block}.navbar-form .radio,.navbar-form .checkbox{margin-top:0;margin-bottom:0}.navbar-nav>li>.dropdown-menu{margin-top:0;border-top-right-radius:0;border-top-left-radius:0}.navbar-fixed-bottom .navbar-nav>li>.dropdown-menu{border-bottom-right-radius:0;border-bottom-left-radius:0}.navbar-nav>.dropdown>a:hover .caret,.navbar-nav>.dropdown>a:focus .caret{border-top-color:#333;border-bottom-color:#333}.navbar-nav>.open>a,.navbar-nav>.open>a:hover,.navbar-nav>.open>a:focus{color:#555;background-color:#d5d5d5}.navbar-nav>.open>a .caret,.navbar-nav>.open>a:hover .caret,.navbar-nav>.open>a:focus .caret{border-top-color:#555;border-bottom-color:#555}.navbar-nav>.dropdown>a .caret{border-top-color:#777;border-bottom-color:#777}.navbar-nav.pull-right>li>.dropdown-menu,.navbar-nav>li>.dropdown-menu.pull-right{right:0;left:auto}.navbar-inverse{background-color:#222}.navbar-inverse .navbar-brand{color:#999}.navbar-inverse .navbar-brand:hover,.navbar-inverse .navbar-brand:focus{color:#fff;background-color:transparent}.navbar-inverse .navbar-text{color:#999}.navbar-inverse .navbar-nav>li>a{color:#999}.navbar-inverse .navbar-nav>li>a:hover,.navbar-inverse .navbar-nav>li>a:focus{color:#fff;background-color:transparent}.navbar-inverse .navbar-nav>.active>a,.navbar-inverse .navbar-nav>.active>a:hover,.navbar-inverse .navbar-nav>.active>a:focus{color:#fff;background-color:#080808}.navbar-inverse .navbar-nav>.disabled>a,.navbar-inverse .navbar-nav>.disabled>a:hover,.navbar-inverse .navbar-nav>.disabled>a:focus{color:#444;background-color:transparent}.navbar-inverse .navbar-toggle{border-color:#333}.navbar-inverse .navbar-toggle:hover,.navbar-inverse .navbar-toggle:focus{background-color:#333}.navbar-inverse .navbar-toggle .icon-bar{background-color:#fff}.navbar-inverse .navbar-nav>.open>a,.navbar-inverse .navbar-nav>.open>a:hover,.navbar-inverse .navbar-nav>.open>a:focus{color:#fff;background-color:#080808}.navbar-inverse .navbar-nav>.dropdown>a:hover .caret{border-top-color:#fff;border-bottom-color:#fff}.navbar-inverse .navbar-nav>.dropdown>a .caret{border-top-color:#999;border-bottom-color:#999}.navbar-inverse .navbar-nav>.open>a .caret,.navbar-inverse .navbar-nav>.open>a:hover .caret,.navbar-inverse .navbar-nav>.open>a:focus .caret{border-top-color:#fff;border-bottom-color:#fff}@media screen and (min-width:768px){.navbar-brand{float:left;margin-right:5px;margin-left:-15px}.navbar-nav{float:left;margin-top:0;margin-bottom:0}.navbar-nav>li{float:left}.navbar-nav>li>a{border-radius:0}.navbar-nav.pull-right{float:right;width:auto}.navbar-toggle{position:relative;top:auto;left:auto;display:none}.nav-collapse.collapse{display:block!important;height:auto!important;overflow:visible!important}}.navbar-btn{margin-top:6px}.navbar-text{margin-top:15px;margin-bottom:15px}.navbar-link{color:#777}.navbar-link:hover{color:#333}.navbar-inverse .navbar-link{color:#999}.navbar-inverse .navbar-link:hover{color:#fff}.btn .caret{border-top-color:#fff}.dropup .btn .caret{border-bottom-color:#fff}.btn-group,.btn-group-vertical{position:relative;display:inline-block;vertical-align:middle}.btn-group>.btn,.btn-group-vertical>.btn{position:relative;float:left}.btn-group>.btn:hover,.btn-group-vertical>.btn:hover,.btn-group>.btn:active,.btn-group-vertical>.btn:active{z-index:2}.btn-group .btn+.btn{margin-left:-1px}.btn-toolbar:before,.btn-toolbar:after{display:table;content:" "}.btn-toolbar:after{clear:both}.btn-toolbar:before,.btn-toolbar:after{display:table;content:" "}.btn-toolbar:after{clear:both}.btn-toolbar .btn-group{float:left}.btn-toolbar>.btn+.btn,.btn-toolbar>.btn-group+.btn,.btn-toolbar>.btn+.btn-group,.btn-toolbar>.btn-group+.btn-group{margin-left:5px}.btn-group>.btn:not(:first-child):not(:last-child):not(.dropdown-toggle){border-radius:0}.btn-group>.btn:first-child{margin-left:0}.btn-group>.btn:first-child:not(:last-child):not(.dropdown-toggle){border-top-right-radius:0;border-bottom-right-radius:0}.btn-group>.btn:last-child:not(:first-child),.btn-group>.dropdown-toggle:not(:first-child){border-bottom-left-radius:0;border-top-left-radius:0}.btn-group>.btn-group{float:left}.btn-group>.btn-group:not(:first-child):not(:last-child)>.btn{border-radius:0}.btn-group>.btn-group:first-child>.btn:last-child,.btn-group>.btn-group:first-child>.dropdown-toggle{border-top-right-radius:0;border-bottom-right-radius:0}.btn-group>.btn-group:last-child>.btn:first-child{border-bottom-left-radius:0;border-top-left-radius:0}.btn-group .dropdown-toggle:active,.btn-group.open .dropdown-toggle{outline:0}.btn-group>.btn+.dropdown-toggle{padding-right:8px;padding-left:8px}.btn-group>.btn-large+.dropdown-toggle{padding-right:12px;padding-left:12px}.btn-group.open .dropdown-toggle{-webkit-box-shadow:inset 0 3px 5px rgba(0,0,0,0.125);box-shadow:inset 0 3px 5px rgba(0,0,0,0.125)}.btn .caret{margin-left:0}.btn-large .caret{border-width:5px}.dropup .btn-large .caret{border-bottom-width:5px}.btn-group-vertical>.btn{display:block;float:none;width:100%;max-width:100%}.btn-group-vertical>.btn+.btn{margin-top:-1px}.btn-group-vertical .btn:not(:first-child):not(:last-child){border-radius:0}.btn-group-vertical .btn:first-child{border-bottom-right-radius:0;border-bottom-left-radius:0}.btn-group-vertical .btn:last-child{border-top-right-radius:0;border-top-left-radius:0}.btn-group-justified{display:table;width:100%}.btn-group-justified .btn{display:table-cell;float:none;width:1%}.btn-group[data-toggle="buttons"]>.btn>input[type="radio"],.btn-group[data-toggle="buttons"]>.btn>input[type="checkbox"]{display:none}.breadcrumb{padding:8px 15px;margin-bottom:20px;list-style:none;background-color:#f5f5f5;border-radius:4px}.breadcrumb>li{display:inline-block}.breadcrumb>li+li:before{padding:0 5px;color:#ccc;content:"/\00a0"}.breadcrumb>.active{color:#999}.pagination{display:inline-block;padding-left:0;margin:20px 0;border-radius:4px}.pagination>li{display:inline}.pagination>li>a,.pagination>li>span{float:left;padding:4px 12px;line-height:1.428571429;text-decoration:none;background-color:#fff;border:1px solid #ddd;border-left-width:0}.pagination>li:first-child>a,.pagination>li:first-child>span{border-left-width:1px;border-bottom-left-radius:4px;border-top-left-radius:4px}.pagination>li:last-child>a,.pagination>li:last-child>span{border-top-right-radius:4px;border-bottom-right-radius:4px}.pagination>li>a:hover,.pagination>li>a:focus,.pagination>.active>a,.pagination>.active>span{background-color:#f5f5f5}.pagination>.active>a,.pagination>.active>span{color:#999;cursor:default}.pagination>.disabled>span,.pagination>.disabled>a,.pagination>.disabled>a:hover,.pagination>.disabled>a:focus{color:#999;cursor:not-allowed;background-color:#fff}.pagination-large>li>a,.pagination-large>li>span{padding:14px 16px;font-size:18px}.pagination-large>li:first-child>a,.pagination-large>li:first-child>span{border-bottom-left-radius:6px;border-top-left-radius:6px}.pagination-large>li:last-child>a,.pagination-large>li:last-child>span{border-top-right-radius:6px;border-bottom-right-radius:6px}.pagination-small>li>a,.pagination-small>li>span{padding:5px 10px;font-size:12px}.pagination-small>li:first-child>a,.pagination-small>li:first-child>span{border-bottom-left-radius:3px;border-top-left-radius:3px}.pagination-small>li:last-child>a,.pagination-small>li:last-child>span{border-top-right-radius:3px;border-bottom-right-radius:3px}.pager{padding-left:0;margin:20px 0;text-align:center;list-style:none}.pager:before,.pager:after{display:table;content:" "}.pager:after{clear:both}.pager:before,.pager:after{display:table;content:" "}.pager:after{clear:both}.pager li{display:inline}.pager li>a,.pager li>span{display:inline-block;padding:5px 14px;background-color:#fff;border:1px solid #ddd;border-radius:15px}.pager li>a:hover,.pager li>a:focus{text-decoration:none;background-color:#f5f5f5}.pager .next>a,.pager .next>span{float:right}.pager .previous>a,.pager .previous>span{float:left}.pager .disabled>a,.pager .disabled>a:hover,.pager .disabled>a:focus,.pager .disabled>span{color:#999;cursor:not-allowed;background-color:#fff}.modal-open{overflow:hidden}.modal{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1040;display:none;overflow:auto;overflow-y:scroll}.modal.fade .modal-dialog{-webkit-transform:translate(0,-25%);-ms-transform:translate(0,-25%);transform:translate(0,-25%);-webkit-transition:-webkit-transform .3s ease-out;-moz-transition:-moz-transform .3s ease-out;-o-transition:-o-transform .3s ease-out;transition:transform .3s ease-out}.modal.fade.in .modal-dialog{-webkit-transform:translate(0,0);-ms-transform:translate(0,0);transform:translate(0,0)}.modal-dialog{position:relative;top:0;right:0;left:0;z-index:1050;width:auto;padding:10px}.modal-content{position:relative;background-color:#fff;border:1px solid #999;border:1px solid rgba(0,0,0,0.2);border-radius:6px;outline:0;-webkit-box-shadow:0 3px 9px rgba(0,0,0,0.5);box-shadow:0 3px 9px rgba(0,0,0,0.5);background-clip:padding-box}.modal-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1030;background-color:#000}.modal-backdrop.fade{opacity:0;filter:alpha(opacity=0)}.modal-backdrop.fade.in{opacity:.5;filter:alpha(opacity=50)}.modal-header{min-height:16.428571429px;padding:15px;border-bottom:1px solid #e5e5e5}.modal-header .close{margin-top:-2px}.modal-title{margin:0;line-height:1.428571429}.modal-body{position:relative;padding:20px}.modal-footer{padding:19px 20px 20px;margin-top:15px;text-align:right;border-top:1px solid #e5e5e5}.modal-footer:before,.modal-footer:after{display:table;content:" "}.modal-footer:after{clear:both}.modal-footer:before,.modal-footer:after{display:table;content:" "}.modal-footer:after{clear:both}.modal-footer .btn+.btn{margin-bottom:0;margin-left:5px}.modal-footer .btn-group .btn+.btn{margin-left:-1px}.modal-footer .btn-block+.btn-block{margin-left:0}@media screen and (min-width:768px){.modal-dialog{right:auto;left:50%;width:560px;padding-top:30px;padding-bottom:30px;margin-left:-280px}.modal-content{-webkit-box-shadow:0 5px 15px rgba(0,0,0,0.5);box-shadow:0 5px 15px rgba(0,0,0,0.5)}}.tooltip{position:absolute;z-index:1030;display:block;font-size:12px;line-height:1.4;opacity:0;filter:alpha(opacity=0);visibility:visible}.tooltip.in{opacity:1;filter:alpha(opacity=100)}.tooltip.top{padding:5px 0;margin-top:-3px}.tooltip.right{padding:0 5px;margin-left:3px}.tooltip.bottom{padding:5px 0;margin-top:3px}.tooltip.left{padding:0 5px;margin-left:-3px}.tooltip-inner{max-width:200px;padding:3px 8px;color:#fff;text-align:center;text-decoration:none;background-color:rgba(0,0,0,0.9);border-radius:4px}.tooltip-arrow{position:absolute;width:0;height:0;border-color:transparent;border-style:solid}.tooltip.top .tooltip-arrow{bottom:0;left:50%;margin-left:-5px;border-top-color:rgba(0,0,0,0.9);border-width:5px 5px 0}.tooltip.top-left .tooltip-arrow{bottom:0;left:5px;border-top-color:rgba(0,0,0,0.9);border-width:5px 5px 0}.tooltip.top-right .tooltip-arrow{right:5px;bottom:0;border-top-color:rgba(0,0,0,0.9);border-width:5px 5px 0}.tooltip.right .tooltip-arrow{top:50%;left:0;margin-top:-5px;border-right-color:rgba(0,0,0,0.9);border-width:5px 5px 5px 0}.tooltip.left .tooltip-arrow{top:50%;right:0;margin-top:-5px;border-left-color:rgba(0,0,0,0.9);border-width:5px 0 5px 5px}.tooltip.bottom .tooltip-arrow{top:0;left:50%;margin-left:-5px;border-bottom-color:rgba(0,0,0,0.9);border-width:0 5px 5px}.tooltip.bottom-left .tooltip-arrow{top:0;left:5px;border-bottom-color:rgba(0,0,0,0.9);border-width:0 5px 5px}.tooltip.bottom-right .tooltip-arrow{top:0;right:5px;border-bottom-color:rgba(0,0,0,0.9);border-width:0 5px 5px}.popover{position:absolute;top:0;left:0;z-index:1010;display:none;max-width:276px;padding:1px;text-align:left;white-space:normal;background-color:#fff;border:1px solid #ccc;border:1px solid rgba(0,0,0,0.2);border-radius:6px;-webkit-box-shadow:0 5px 10px rgba(0,0,0,0.2);box-shadow:0 5px 10px rgba(0,0,0,0.2);background-clip:padding-box;-webkit-bg-clip:padding-box;-moz-bg-clip:padding}.popover.top{margin-top:-10px}.popover.right{margin-left:10px}.popover.bottom{margin-top:10px}.popover.left{margin-left:-10px}.popover-title{padding:8px 14px;margin:0;font-size:14px;font-weight:normal;line-height:18px;background-color:#f7f7f7;border-bottom:1px solid #ebebeb;border-radius:5px 5px 0 0}.popover-content{padding:9px 14px}.popover .arrow,.popover .arrow:after{position:absolute;display:block;width:0;height:0;border-color:transparent;border-style:solid}.popover .arrow{border-width:11px}.popover .arrow:after{border-width:10px;content:""}.popover.top .arrow{bottom:-11px;left:50%;margin-left:-11px;border-top-color:#999;border-top-color:rgba(0,0,0,0.25);border-bottom-width:0}.popover.top .arrow:after{bottom:1px;margin-left:-10px;border-top-color:#fff;border-bottom-width:0;content:" "}.popover.right .arrow{top:50%;left:-11px;margin-top:-11px;border-right-color:#999;border-right-color:rgba(0,0,0,0.25);border-left-width:0}.popover.right .arrow:after{bottom:-10px;left:1px;border-right-color:#fff;border-left-width:0;content:" "}.popover.bottom .arrow{top:-11px;left:50%;margin-left:-11px;border-bottom-color:#999;border-bottom-color:rgba(0,0,0,0.25);border-top-width:0}.popover.bottom .arrow:after{top:1px;margin-left:-10px;border-bottom-color:#fff;border-top-width:0;content:" "}.popover.left .arrow{top:50%;right:-11px;margin-top:-11px;border-left-color:#999;border-left-color:rgba(0,0,0,0.25);border-right-width:0}.popover.left .arrow:after{right:1px;bottom:-10px;border-left-color:#fff;border-right-width:0;content:" "}.alert{padding:10px 35px 10px 15px;margin-bottom:20px;color:#c09853;background-color:#fcf8e3;border:1px solid #fbeed5;border-radius:4px}.alert h4{margin-top:0;color:inherit}.alert hr{border-top-color:#f8e5be}.alert .alert-link{font-weight:500;color:#a47e3c}.alert .close{position:relative;top:-2px;right:-21px;color:inherit}.alert-success{color:#468847;background-color:#dff0d8;border-color:#d6e9c6}.alert-success hr{border-top-color:#c9e2b3}.alert-success .alert-link{color:#356635}.alert-danger{color:#b94a48;background-color:#f2dede;border-color:#eed3d7}.alert-danger hr{border-top-color:#e6c1c7}.alert-danger .alert-link{color:#953b39}.alert-info{color:#3a87ad;background-color:#d9edf7;border-color:#bce8f1}.alert-info hr{border-top-color:#a6e1ec}.alert-info .alert-link{color:#2d6987}.alert-block{padding-top:15px;padding-bottom:15px}.alert-block>p,.alert-block>ul{margin-bottom:0}.alert-block p+p{margin-top:5px}.thumbnail,.img-thumbnail{padding:4px;line-height:1.428571429;background-color:#fff;border:1px solid #ddd;border-radius:4px;-webkit-transition:all .2s ease-in-out;transition:all .2s ease-in-out}.thumbnail{display:block}.thumbnail>img,.img-thumbnail{display:inline-block;height:auto;max-width:100%}a.thumbnail:hover,a.thumbnail:focus{border-color:#428bca}.thumbnail>img{margin-right:auto;margin-left:auto}.thumbnail .caption{padding:9px;color:#333}.media,.media-body{overflow:hidden;zoom:1}.media,.media .media{margin-top:15px}.media:first-child{margin-top:0}.media-object{display:block}.media-heading{margin:0 0 5px}.media>.pull-left{margin-right:10px}.media>.pull-right{margin-left:10px}.media-list{padding-left:0;list-style:none}.label{display:inline;padding:.25em .6em;font-size:75%;font-weight:500;line-height:1;color:#fff;text-align:center;white-space:nowrap;vertical-align:middle;background-color:#999;border-radius:.25em}.label[href]:hover,.label[href]:focus{color:#fff;text-decoration:none;cursor:pointer;background-color:#808080}.label-danger{background-color:#d9534f}.label-danger[href]:hover,.label-danger[href]:focus{background-color:#c9302c}.label-success{background-color:#5cb85c}.label-success[href]:hover,.label-success[href]:focus{background-color:#449d44}.label-warning{background-color:#f0ad4e}.label-warning[href]:hover,.label-warning[href]:focus{background-color:#ec971f}.label-info{background-color:#5bc0de}.label-info[href]:hover,.label-info[href]:focus{background-color:#31b0d5}.badge{display:inline-block;min-width:10px;padding:3px 7px;font-size:12px;font-weight:bold;line-height:1;color:#fff;text-align:center;white-space:nowrap;vertical-align:middle;background-color:#999;border-radius:10px}.badge:empty{display:none}a.badge:hover,a.badge:focus{color:#fff;text-decoration:none;cursor:pointer}.btn .badge{position:relative;top:-1px}a.list-group-item.active>.badge,.nav-pills>.active>a>.badge{color:#428bca;background-color:#fff}.nav-pills>li>a>.badge{margin-left:3px}@-webkit-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@-moz-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@-ms-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@-o-keyframes progress-bar-stripes{from{background-position:0 0}to{background-position:40px 0}}@keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}.progress{height:20px;margin-bottom:20px;overflow:hidden;background-color:#f5f5f5;border-radius:4px;-webkit-box-shadow:inset 0 1px 2px rgba(0,0,0,0.1);box-shadow:inset 0 1px 2px rgba(0,0,0,0.1)}.progress-bar{float:left;width:0;height:100%;font-size:12px;color:#fff;text-align:center;background-color:#428bca;-webkit-box-shadow:inset 0 -1px 0 rgba(0,0,0,0.15);box-shadow:inset 0 -1px 0 rgba(0,0,0,0.15);-webkit-transition:width .6s ease;transition:width .6s ease}.progress-striped .progress-bar{background-color:#428bca;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-size:40px 40px}.progress.active .progress-bar{-webkit-animation:progress-bar-stripes 2s linear infinite;-moz-animation:progress-bar-stripes 2s linear infinite;-ms-animation:progress-bar-stripes 2s linear infinite;-o-animation:progress-bar-stripes 2s linear infinite;animation:progress-bar-stripes 2s linear infinite}.progress-bar-danger{background-color:#d9534f}.progress-striped .progress-bar-danger{background-color:#d9534f;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.progress-bar-success{background-color:#5cb85c}.progress-striped .progress-bar-success{background-color:#5cb85c;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.progress-bar-warning{background-color:#f0ad4e}.progress-striped .progress-bar-warning{background-color:#f0ad4e;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.progress-bar-info{background-color:#5bc0de}.progress-striped .progress-bar-info{background-color:#5bc0de;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.accordion{margin-bottom:20px}.accordion-group{margin-bottom:2px;border:1px solid #e5e5e5;border-radius:4px}.accordion-heading{border-bottom:0}.accordion-heading .accordion-toggle{display:block;padding:8px 15px;cursor:pointer}.accordion-inner{padding:9px 15px;border-top:1px solid #e5e5e5}.carousel{position:relative}.carousel-inner{position:relative;width:100%;overflow:hidden}.carousel-inner>.item{position:relative;display:none;-webkit-transition:.6s ease-in-out left;transition:.6s ease-in-out left}.carousel-inner>.item>img,.carousel-inner>.item>a>img{display:inline-block;height:auto;max-width:100%;line-height:1}.carousel-inner>.active,.carousel-inner>.next,.carousel-inner>.prev{display:block}.carousel-inner>.active{left:0}.carousel-inner>.next,.carousel-inner>.prev{position:absolute;top:0;width:100%}.carousel-inner>.next{left:100%}.carousel-inner>.prev{left:-100%}.carousel-inner>.next.left,.carousel-inner>.prev.right{left:0}.carousel-inner>.active.left{left:-100%}.carousel-inner>.active.right{left:100%}.carousel-control{position:absolute;top:0;bottom:0;left:0;width:15%;font-size:20px;color:#fff;text-align:center;text-shadow:0 1px 2px rgba(0,0,0,0.6);opacity:.5;filter:alpha(opacity=50)}.carousel-control.left{background-color:rgba(0,0,0,0.0001);background-color:transparent;background-image:-webkit-gradient(linear,0 top,100% top,from(rgba(0,0,0,0.5)),to(rgba(0,0,0,0.0001)));background-image:-webkit-linear-gradient(left,color-stop(rgba(0,0,0,0.5) 0),color-stop(rgba(0,0,0,0.0001) 100%));background-image:-moz-linear-gradient(left,rgba(0,0,0,0.5) 0,rgba(0,0,0,0.0001) 100%);background-image:linear-gradient(to right,rgba(0,0,0,0.5) 0,rgba(0,0,0,0.0001) 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#80000000',endColorstr='#00000000',GradientType=1)}.carousel-control.right{right:0;left:auto;background-color:rgba(0,0,0,0.5);background-color:transparent;background-image:-webkit-gradient(linear,0 top,100% top,from(rgba(0,0,0,0.0001)),to(rgba(0,0,0,0.5)));background-image:-webkit-linear-gradient(left,color-stop(rgba(0,0,0,0.0001) 0),color-stop(rgba(0,0,0,0.5) 100%));background-image:-moz-linear-gradient(left,rgba(0,0,0,0.0001) 0,rgba(0,0,0,0.5) 100%);background-image:linear-gradient(to right,rgba(0,0,0,0.0001) 0,rgba(0,0,0,0.5) 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#00000000',endColorstr='#80000000',GradientType=1)}.carousel-control:hover,.carousel-control:focus{color:#fff;text-decoration:none;opacity:.9;filter:alpha(opacity=90)}.carousel-control .glyphicon,.carousel-control .icon-prev,.carousel-control .icon-next{position:absolute;top:50%;left:50%;z-index:5;display:inline-block;width:20px;height:20px;margin-top:-10px;margin-left:-10px;font-family:serif}.carousel-control .icon-prev:before{content:'\2039'}.carousel-control .icon-next:before{content:'\203a'}.carousel-indicators{position:absolute;bottom:10px;left:50%;z-index:15;width:120px;padding-left:0;margin-left:-60px;text-align:center;list-style:none}.carousel-indicators li{display:inline-block;width:10px;height:10px;margin:1px;text-indent:-999px;cursor:pointer;border:1px solid #fff;border-radius:10px}.carousel-indicators .active{width:12px;height:12px;margin:0;background-color:#fff}.carousel-caption{position:absolute;right:15%;bottom:20px;left:15%;z-index:10;padding-top:20px;padding-bottom:20px;color:#fff;text-align:center;text-shadow:0 1px 2px rgba(0,0,0,0.6)}.carousel-caption .btn{text-shadow:none}@media screen and (min-width:768px){.carousel-control .glyphicon,.carousel-control .icon-prev,.carousel-control .icon-next{width:30px;height:30px;margin-top:-15px;margin-left:-15px;font-size:30px}.carousel-caption{right:20%;left:20%;padding-bottom:30px}.carousel-indicators{bottom:20px}}.jumbotron{padding:30px;margin-bottom:30px;font-size:21px;font-weight:200;line-height:2.1428571435;color:inherit;background-color:#eee}.jumbotron h1{line-height:1;color:inherit}.jumbotron p{line-height:1.4}@media screen and (min-width:768px){.jumbotron{padding:50px 60px;border-radius:6px}.jumbotron h1{font-size:63px}}.clearfix:before,.clearfix:after{display:table;content:" "}.clearfix:after{clear:both}.pull-right{float:right}.pull-left{float:left}.hide{display:none!important}.show{display:block!important}.invisible{visibility:hidden}.text-hide{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0}.affix{position:fixed}@-ms-viewport{width:device-width}@media screen and (max-width:400px){@-ms-viewport{width:320px}}.hidden{display:none!important;visibility:hidden!important}.visible-sm{display:block!important}tr.visible-sm{display:table-row!important}th.visible-sm,td.visible-sm{display:table-cell!important}.visible-md{display:none!important}tr.visible-md{display:none!important}th.visible-md,td.visible-md{display:none!important}.visible-lg{display:none!important}tr.visible-lg{display:none!important}th.visible-lg,td.visible-lg{display:none!important}.hidden-sm{display:none!important}tr.hidden-sm{display:none!important}th.hidden-sm,td.hidden-sm{display:none!important}.hidden-md{display:block!important}tr.hidden-md{display:table-row!important}th.hidden-md,td.hidden-md{display:table-cell!important}.hidden-lg{display:block!important}tr.hidden-lg{display:table-row!important}th.hidden-lg,td.hidden-lg{display:table-cell!important}@media(min-width:768px) and (max-width:991px){.visible-sm{display:none!important}tr.visible-sm{display:none!important}th.visible-sm,td.visible-sm{display:none!important}.visible-md{display:block!important}tr.visible-md{display:table-row!important}th.visible-md,td.visible-md{display:table-cell!important}.visible-lg{display:none!important}tr.visible-lg{display:none!important}th.visible-lg,td.visible-lg{display:none!important}.hidden-sm{display:block!important}tr.hidden-sm{display:table-row!important}th.hidden-sm,td.hidden-sm{display:table-cell!important}.hidden-md{display:none!important}tr.hidden-md{display:none!important}th.hidden-md,td.hidden-md{display:none!important}.hidden-lg{display:block!important}tr.hidden-lg{display:table-row!important}th.hidden-lg,td.hidden-lg{display:table-cell!important}}@media(min-width:992px){.visible-sm{display:none!important}tr.visible-sm{display:none!important}th.visible-sm,td.visible-sm{display:none!important}.visible-md{display:none!important}tr.visible-md{display:none!important}th.visible-md,td.visible-md{display:none!important}.visible-lg{display:block!important}tr.visible-lg{display:table-row!important}th.visible-lg,td.visible-lg{display:table-cell!important}.hidden-sm{display:block!important}tr.hidden-sm{display:table-row!important}th.hidden-sm,td.hidden-sm{display:table-cell!important}.hidden-md{display:block!important}tr.hidden-md{display:table-row!important}th.hidden-md,td.hidden-md{display:table-cell!important}.hidden-lg{display:none!important}tr.hidden-lg{display:none!important}th.hidden-lg,td.hidden-lg{display:none!important}}.visible-print{display:none!important}tr.visible-print{display:none!important}th.visible-print,td.visible-print{display:none!important}@media print{.visible-print{display:block!important}tr.visible-print{display:table-row!important}th.visible-print,td.visible-print{display:table-cell!important}.hidden-print{display:none!important}tr.hidden-print{display:none!important}th.hidden-print,td.hidden-print{display:none!important}} </style> <!-- zepto --> <script type="text/javascript"> /* Zepto v1.1.2 - zepto event ajax form ie - zeptojs.com/license */ var Zepto=function(){function G(a){return a==null?String(a):z[A.call(a)]||"object"}function H(a){return G(a)=="function"}function I(a){return a!=null&&a==a.window}function J(a){return a!=null&&a.nodeType==a.DOCUMENT_NODE}function K(a){return G(a)=="object"}function L(a){return K(a)&&!I(a)&&Object.getPrototypeOf(a)==Object.prototype}function M(a){return a instanceof Array}function N(a){return typeof a.length=="number"}function O(a){return g.call(a,function(a){return a!=null})}function P(a){return a.length>0?c.fn.concat.apply([],a):a}function Q(a){return a.replace(/::/g,"/").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/_/g,"-").toLowerCase()}function R(a){return a in j?j[a]:j[a]=new RegExp("(^|\\s)"+a+"(\\s|$)")}function S(a,b){return typeof b=="number"&&!k[Q(a)]?b+"px":b}function T(a){var b,c;return i[a]||(b=h.createElement(a),h.body.appendChild(b),c=getComputedStyle(b,"").getPropertyValue("display"),b.parentNode.removeChild(b),c=="none"&&(c="block"),i[a]=c),i[a]}function U(a){return"children"in a?f.call(a.children):c.map(a.childNodes,function(a){if(a.nodeType==1)return a})}function V(c,d,e){for(b in d)e&&(L(d[b])||M(d[b]))?(L(d[b])&&!L(c[b])&&(c[b]={}),M(d[b])&&!M(c[b])&&(c[b]=[]),V(c[b],d[b],e)):d[b]!==a&&(c[b]=d[b])}function W(a,b){return b==null?c(a):c(a).filter(b)}function X(a,b,c,d){return H(b)?b.call(a,c,d):b}function Y(a,b,c){c==null?a.removeAttribute(b):a.setAttribute(b,c)}function Z(b,c){var d=b.className,e=d&&d.baseVal!==a;if(c===a)return e?d.baseVal:d;e?d.baseVal=c:b.className=c}function $(a){var b;try{return a?a=="true"||(a=="false"?!1:a=="null"?null:!/^0/.test(a)&&!isNaN(b=Number(a))?b:/^[\[\{]/.test(a)?c.parseJSON(a):a):a}catch(d){return a}}function _(a,b){b(a);for(var c in a.childNodes)_(a.childNodes[c],b)}var a,b,c,d,e=[],f=e.slice,g=e.filter,h=window.document,i={},j={},k={"column-count":1,columns:1,"font-weight":1,"line-height":1,opacity:1,"z-index":1,zoom:1},l=/^\s*<(\w+|!)[^>]*>/,m=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,n=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,o=/^(?:body|html)$/i,p=/([A-Z])/g,q=["val","css","html","text","data","width","height","offset"],r=["after","prepend","before","append"],s=h.createElement("table"),t=h.createElement("tr"),u={tr:h.createElement("tbody"),tbody:s,thead:s,tfoot:s,td:t,th:t,"*":h.createElement("div")},v=/complete|loaded|interactive/,w=/^\.([\w-]+)$/,x=/^#([\w-]*)$/,y=/^[\w-]*$/,z={},A=z.toString,B={},C,D,E=h.createElement("div"),F={tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"};return B.matches=function(a,b){if(!b||!a||a.nodeType!==1)return!1;var c=a.webkitMatchesSelector||a.mozMatchesSelector||a.oMatchesSelector||a.matchesSelector;if(c)return c.call(a,b);var d,e=a.parentNode,f=!e;return f&&(e=E).appendChild(a),d=~B.qsa(e,b).indexOf(a),f&&E.removeChild(a),d},C=function(a){return a.replace(/-+(.)?/g,function(a,b){return b?b.toUpperCase():""})},D=function(a){return g.call(a,function(b,c){return a.indexOf(b)==c})},B.fragment=function(b,d,e){var g,i,j;return m.test(b)&&(g=c(h.createElement(RegExp.$1))),g||(b.replace&&(b=b.replace(n,"<$1></$2>")),d===a&&(d=l.test(b)&&RegExp.$1),d in u||(d="*"),j=u[d],j.innerHTML=""+b,g=c.each(f.call(j.childNodes),function(){j.removeChild(this)})),L(e)&&(i=c(g),c.each(e,function(a,b){q.indexOf(a)>-1?i[a](b):i.attr(a,b)})),g},B.Z=function(a,b){return a=a||[],a.__proto__=c.fn,a.selector=b||"",a},B.isZ=function(a){return a instanceof B.Z},B.init=function(b,d){var e;if(!b)return B.Z();if(typeof b=="string"){b=b.trim();if(b[0]=="<"&&l.test(b))e=B.fragment(b,RegExp.$1,d),b=null;else{if(d!==a)return c(d).find(b);e=B.qsa(h,b)}}else{if(H(b))return c(h).ready(b);if(B.isZ(b))return b;if(M(b))e=O(b);else if(K(b))e=[b],b=null;else if(l.test(b))e=B.fragment(b.trim(),RegExp.$1,d),b=null;else{if(d!==a)return c(d).find(b);e=B.qsa(h,b)}}return B.Z(e,b)},c=function(a,b){return B.init(a,b)},c.extend=function(a){var b,c=f.call(arguments,1);return typeof a=="boolean"&&(b=a,a=c.shift()),c.forEach(function(c){V(a,c,b)}),a},B.qsa=function(a,b){var c,d=b[0]=="#",e=!d&&b[0]==".",g=d||e?b.slice(1):b,h=y.test(g);return J(a)&&h&&d?(c=a.getElementById(g))?[c]:[]:a.nodeType!==1&&a.nodeType!==9?[]:f.call(h&&!d?e?a.getElementsByClassName(g):a.getElementsByTagName(b):a.querySelectorAll(b))},c.contains=function(a,b){return a!==b&&a.contains(b)},c.type=G,c.isFunction=H,c.isWindow=I,c.isArray=M,c.isPlainObject=L,c.isEmptyObject=function(a){var b;for(b in a)return!1;return!0},c.inArray=function(a,b,c){return e.indexOf.call(b,a,c)},c.camelCase=C,c.trim=function(a){return a==null?"":String.prototype.trim.call(a)},c.uuid=0,c.support={},c.expr={},c.map=function(a,b){var c,d=[],e,f;if(N(a))for(e=0;e<a.length;e++)c=b(a[e],e),c!=null&&d.push(c);else for(f in a)c=b(a[f],f),c!=null&&d.push(c);return P(d)},c.each=function(a,b){var c,d;if(N(a)){for(c=0;c<a.length;c++)if(b.call(a[c],c,a[c])===!1)return a}else for(d in a)if(b.call(a[d],d,a[d])===!1)return a;return a},c.grep=function(a,b){return g.call(a,b)},window.JSON&&(c.parseJSON=JSON.parse),c.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){z["[object "+b+"]"]=b.toLowerCase()}),c.fn={forEach:e.forEach,reduce:e.reduce,push:e.push,sort:e.sort,indexOf:e.indexOf,concat:e.concat,map:function(a){return c(c.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return c(f.apply(this,arguments))},ready:function(a){return v.test(h.readyState)&&h.body?a(c):h.addEventListener("DOMContentLoaded",function(){a(c)},!1),this},get:function(b){return b===a?f.call(this):this[b>=0?b:b+this.length]},toArray:function(){return this.get()},size:function(){return this.length},remove:function(){return this.each(function(){this.parentNode!=null&&this.parentNode.removeChild(this)})},each:function(a){return e.every.call(this,function(b,c){return a.call(b,c,b)!==!1}),this},filter:function(a){return H(a)?this.not(this.not(a)):c(g.call(this,function(b){return B.matches(b,a)}))},add:function(a,b){return c(D(this.concat(c(a,b))))},is:function(a){return this.length>0&&B.matches(this[0],a)},not:function(b){var d=[];if(H(b)&&b.call!==a)this.each(function(a){b.call(this,a)||d.push(this)});else{var e=typeof b=="string"?this.filter(b):N(b)&&H(b.item)?f.call(b):c(b);this.forEach(function(a){e.indexOf(a)<0&&d.push(a)})}return c(d)},has:function(a){return this.filter(function(){return K(a)?c.contains(this,a):c(this).find(a).size()})},eq:function(a){return a===-1?this.slice(a):this.slice(a,+a+1)},first:function(){var a=this[0];return a&&!K(a)?a:c(a)},last:function(){var a=this[this.length-1];return a&&!K(a)?a:c(a)},find:function(a){var b,d=this;return typeof a=="object"?b=c(a).filter(function(){var a=this;return e.some.call(d,function(b){return c.contains(b,a)})}):this.length==1?b=c(B.qsa(this[0],a)):b=this.map(function(){return B.qsa(this,a)}),b},closest:function(a,b){var d=this[0],e=!1;typeof a=="object"&&(e=c(a));while(d&&!(e?e.indexOf(d)>=0:B.matches(d,a)))d=d!==b&&!J(d)&&d.parentNode;return c(d)},parents:function(a){var b=[],d=this;while(d.length>0)d=c.map(d,function(a){if((a=a.parentNode)&&!J(a)&&b.indexOf(a)<0)return b.push(a),a});return W(b,a)},parent:function(a){return W(D(this.pluck("parentNode")),a)},children:function(a){return W(this.map(function(){return U(this)}),a)},contents:function(){return this.map(function(){return f.call(this.childNodes)})},siblings:function(a){return W(this.map(function(a,b){return g.call(U(b.parentNode),function(a){return a!==b})}),a)},empty:function(){return this.each(function(){this.innerHTML=""})},pluck:function(a){return c.map(this,function(b){return b[a]})},show:function(){return this.each(function(){this.style.display=="none"&&(this.style.display=""),getComputedStyle(this,"").getPropertyValue("display")=="none"&&(this.style.display=T(this.nodeName))})},replaceWith:function(a){return this.before(a).remove()},wrap:function(a){var b=H(a);if(this[0]&&!b)var d=c(a).get(0),e=d.parentNode||this.length>1;return this.each(function(f){c(this).wrapAll(b?a.call(this,f):e?d.cloneNode(!0):d)})},wrapAll:function(a){if(this[0]){c(this[0]).before(a=c(a));var b;while((b=a.children()).length)a=b.first();c(a).append(this)}return this},wrapInner:function(a){var b=H(a);return this.each(function(d){var e=c(this),f=e.contents(),g=b?a.call(this,d):a;f.length?f.wrapAll(g):e.append(g)})},unwrap:function(){return this.parent().each(function(){c(this).replaceWith(c(this).children())}),this},clone:function(){return this.map(function(){return this.cloneNode(!0)})},hide:function(){return this.css("display","none")},toggle:function(b){return this.each(function(){var d=c(this);(b===a?d.css("display")=="none":b)?d.show():d.hide()})},prev:function(a){return c(this.pluck("previousElementSibling")).filter(a||"*")},next:function(a){return c(this.pluck("nextElementSibling")).filter(a||"*")},html:function(a){return arguments.length===0?this.length>0?this[0].innerHTML:null:this.each(function(b){var d=this.innerHTML;c(this).empty().append(X(this,a,b,d))})},text:function(b){return arguments.length===0?this.length>0?this[0].textContent:null:this.each(function(){this.textContent=b===a?"":""+b})},attr:function(c,d){var e;return typeof c=="string"&&d===a?this.length==0||this[0].nodeType!==1?a:c=="value"&&this[0].nodeName=="INPUT"?this.val():!(e=this[0].getAttribute(c))&&c in this[0]?this[0][c]:e:this.each(function(a){if(this.nodeType!==1)return;if(K(c))for(b in c)Y(this,b,c[b]);else Y(this,c,X(this,d,a,this.getAttribute(c)))})},removeAttr:function(a){return this.each(function(){this.nodeType===1&&Y(this,a)})},prop:function(b,c){return b=F[b]||b,c===a?this[0]&&this[0][b]:this.each(function(a){this[b]=X(this,c,a,this[b])})},data:function(b,c){var d=this.attr("data-"+b.replace(p,"-$1").toLowerCase(),c);return d!==null?$(d):a},val:function(a){return arguments.length===0?this[0]&&(this[0].multiple?c(this[0]).find("option").filter(function(){return this.selected}).pluck("value"):this[0].value):this.each(function(b){this.value=X(this,a,b,this.value)})},offset:function(a){if(a)return this.each(function(b){var d=c(this),e=X(this,a,b,d.offset()),f=d.offsetParent().offset(),g={top:e.top-f.top,left:e.left-f.left};d.css("position")=="static"&&(g.position="relative"),d.css(g)});if(this.length==0)return null;var b=this[0].getBoundingClientRect();return{left:b.left+window.pageXOffset,top:b.top+window.pageYOffset,width:Math.round(b.width),height:Math.round(b.height)}},css:function(a,d){if(arguments.length<2){var e=this[0],f=getComputedStyle(e,"");if(!e)return;if(typeof a=="string")return e.style[C(a)]||f.getPropertyValue(a);if(M(a)){var g={};return c.each(M(a)?a:[a],function(a,b){g[b]=e.style[C(b)]||f.getPropertyValue(b)}),g}}var h="";if(G(a)=="string")!d&&d!==0?this.each(function(){this.style.removeProperty(Q(a))}):h=Q(a)+":"+S(a,d);else for(b in a)!a[b]&&a[b]!==0?this.each(function(){this.style.removeProperty(Q(b))}):h+=Q(b)+":"+S(b,a[b])+";";return this.each(function(){this.style.cssText+=";"+h})},index:function(a){return a?this.indexOf(c(a)[0]):this.parent().children().indexOf(this[0])},hasClass:function(a){return a?e.some.call(this,function(a){return this.test(Z(a))},R(a)):!1},addClass:function(a){return a?this.each(function(b){d=[];var e=Z(this),f=X(this,a,b,e);f.split(/\s+/g).forEach(function(a){c(this).hasClass(a)||d.push(a)},this),d.length&&Z(this,e+(e?" ":"")+d.join(" "))}):this},removeClass:function(b){return this.each(function(c){if(b===a)return Z(this,"");d=Z(this),X(this,b,c,d).split(/\s+/g).forEach(function(a){d=d.replace(R(a)," ")}),Z(this,d.trim())})},toggleClass:function(b,d){return b?this.each(function(e){var f=c(this),g=X(this,b,e,Z(this));g.split(/\s+/g).forEach(function(b){(d===a?!f.hasClass(b):d)?f.addClass(b):f.removeClass(b)})}):this},scrollTop:function(b){if(!this.length)return;var c="scrollTop"in this[0];return b===a?c?this[0].scrollTop:this[0].pageYOffset:this.each(c?function(){this.scrollTop=b}:function(){this.scrollTo(this.scrollX,b)})},scrollLeft:function(b){if(!this.length)return;var c="scrollLeft"in this[0];return b===a?c?this[0].scrollLeft:this[0].pageXOffset:this.each(c?function(){this.scrollLeft=b}:function(){this.scrollTo(b,this.scrollY)})},position:function(){if(!this.length)return;var a=this[0],b=this.offsetParent(),d=this.offset(),e=o.test(b[0].nodeName)?{top:0,left:0}:b.offset();return d.top-=parseFloat(c(a).css("margin-top"))||0,d.left-=parseFloat(c(a).css("margin-left"))||0,e.top+=parseFloat(c(b[0]).css("border-top-width"))||0,e.left+=parseFloat(c(b[0]).css("border-left-width"))||0,{top:d.top-e.top,left:d.left-e.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||h.body;while(a&&!o.test(a.nodeName)&&c(a).css("position")=="static")a=a.offsetParent;return a})}},c.fn.detach=c.fn.remove,["width","height"].forEach(function(b){var d=b.replace(/./,function(a){return a[0].toUpperCase()});c.fn[b]=function(e){var f,g=this[0];return e===a?I(g)?g["inner"+d]:J(g)?g.documentElement["scroll"+d]:(f=this.offset())&&f[b]:this.each(function(a){g=c(this),g.css(b,X(this,e,a,g[b]()))})}}),r.forEach(function(a,b){var d=b%2;c.fn[a]=function(){var a,e=c.map(arguments,function(b){return a=G(b),a=="object"||a=="array"||b==null?b:B.fragment(b)}),f,g=this.length>1;return e.length<1?this:this.each(function(a,h){f=d?h:h.parentNode,h=b==0?h.nextSibling:b==1?h.firstChild:b==2?h:null,e.forEach(function(a){if(g)a=a.cloneNode(!0);else if(!f)return c(a).remove();_(f.insertBefore(a,h),function(a){a.nodeName!=null&&a.nodeName.toUpperCase()==="SCRIPT"&&(!a.type||a.type==="text/javascript")&&!a.src&&window.eval.call(window,a.innerHTML)})})})},c.fn[d?a+"To":"insert"+(b?"Before":"After")]=function(b){return c(b)[a](this),this}}),B.Z.prototype=c.fn,B.uniq=D,B.deserializeValue=$,c.zepto=B,c}();window.Zepto=Zepto,window.$===undefined&&(window.$=Zepto),function(a){function m(a){return a._zid||(a._zid=c++)}function n(a,b,c,d){b=o(b);if(b.ns)var e=p(b.ns);return(h[m(a)]||[]).filter(function(a){return a&&(!b.e||a.e==b.e)&&(!b.ns||e.test(a.ns))&&(!c||m(a.fn)===m(c))&&(!d||a.sel==d)})}function o(a){var b=(""+a).split(".");return{e:b[0],ns:b.slice(1).sort().join(" ")}}function p(a){return new RegExp("(?:^| )"+a.replace(" "," .* ?")+"(?: |$)")}function q(a,b){return a.del&&!j&&a.e in k||!!b}function r(a){return l[a]||j&&k[a]||a}function s(b,c,e,f,g,i,j){var k=m(b),n=h[k]||(h[k]=[]);c.split(/\s/).forEach(function(c){if(c=="ready")return a(document).ready(e);var h=o(c);h.fn=e,h.sel=g,h.e in l&&(e=function(b){var c=b.relatedTarget;if(!c||c!==this&&!a.contains(this,c))return h.fn.apply(this,arguments)}),h.del=i;var k=i||e;h.proxy=function(a){a=y(a);if(a.isImmediatePropagationStopped())return;a.data=f;var c=k.apply(b,a._args==d?[a]:[a].concat(a._args));return c===!1&&(a.preventDefault(),a.stopPropagation()),c},h.i=n.length,n.push(h),"addEventListener"in b&&b.addEventListener(r(h.e),h.proxy,q(h,j))})}function t(a,b,c,d,e){var f=m(a);(b||"").split(/\s/).forEach(function(b){n(a,b,c,d).forEach(function(b){delete h[f][b.i],"removeEventListener"in a&&a.removeEventListener(r(b.e),b.proxy,q(b,e))})})}function y(b,c){if(c||!b.isDefaultPrevented){c||(c=b),a.each(x,function(a,d){var e=c[a];b[a]=function(){return this[d]=u,e&&e.apply(c,arguments)},b[d]=v});if(c.defaultPrevented!==d?c.defaultPrevented:"returnValue"in c?c.returnValue===!1:c.getPreventDefault&&c.getPreventDefault())b.isDefaultPrevented=u}return b}function z(a){var b,c={originalEvent:a};for(b in a)!w.test(b)&&a[b]!==d&&(c[b]=a[b]);return y(c,a)}var b=a.zepto.qsa,c=1,d,e=Array.prototype.slice,f=a.isFunction,g=function(a){return typeof a=="string"},h={},i={},j="onfocusin"in window,k={focus:"focusin",blur:"focusout"},l={mouseenter:"mouseover",mouseleave:"mouseout"};i.click=i.mousedown=i.mouseup=i.mousemove="MouseEvents",a.event={add:s,remove:t},a.proxy=function(b,c){if(f(b)){var d=function(){return b.apply(c,arguments)};return d._zid=m(b),d}if(g(c))return a.proxy(b[c],b);throw new TypeError("expected function")},a.fn.bind=function(a,b,c){return this.on(a,b,c)},a.fn.unbind=function(a,b){return this.off(a,b)},a.fn.one=function(a,b,c,d){return this.on(a,b,c,d,1)};var u=function(){return!0},v=function(){return!1},w=/^([A-Z]|returnValue$|layer[XY]$)/,x={preventDefault:"isDefaultPrevented",stopImmediatePropagation:"isImmediatePropagationStopped",stopPropagation:"isPropagationStopped"};a.fn.delegate=function(a,b,c){return this.on(b,a,c)},a.fn.undelegate=function(a,b,c){return this.off(b,a,c)},a.fn.live=function(b,c){return a(document.body).delegate(this.selector,b,c),this},a.fn.die=function(b,c){return a(document.body).undelegate(this.selector,b,c),this},a.fn.on=function(b,c,h,i,j){var k,l,m=this;if(b&&!g(b))return a.each(b,function(a,b){m.on(a,c,h,b,j)}),m;!g(c)&&!f(i)&&i!==!1&&(i=h,h=c,c=d);if(f(h)||h===!1)i=h,h=d;return i===!1&&(i=v),m.each(function(d,f){j&&(k=function(a){return t(f,a.type,i),i.apply(this,arguments)}),c&&(l=function(b){var d,g=a(b.target).closest(c,f).get(0);if(g&&g!==f)return d=a.extend(z(b),{currentTarget:g,liveFired:f}),(k||i).apply(g,[d].concat(e.call(arguments,1)))}),s(f,b,i,h,c,l||k)})},a.fn.off=function(b,c,e){var h=this;return b&&!g(b)?(a.each(b,function(a,b){h.off(a,c,b)}),h):(!g(c)&&!f(e)&&e!==!1&&(e=c,c=d),e===!1&&(e=v),h.each(function(){t(this,b,e,c)}))},a.fn.trigger=function(b,c){return b=g(b)||a.isPlainObject(b)?a.Event(b):y(b),b._args=c,this.each(function(){"dispatchEvent"in this?this.dispatchEvent(b):a(this).triggerHandler(b,c)})},a.fn.triggerHandler=function(b,c){var d,e;return this.each(function(f,h){d=z(g(b)?a.Event(b):b),d._args=c,d.target=h,a.each(n(h,b.type||b),function(a,b){e=b.proxy(d);if(d.isImmediatePropagationStopped())return!1})}),e},"focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select keydown keypress keyup error".split(" ").forEach(function(b){a.fn[b]=function(a){return a?this.bind(b,a):this.trigger(b)}}),["focus","blur"].forEach(function(b){a.fn[b]=function(a){return a?this.bind(b,a):this.each(function(){try{this[b]()}catch(a){}}),this}}),a.Event=function(a,b){g(a)||(b=a,a=b.type);var c=document.createEvent(i[a]||"Events"),d=!0;if(b)for(var e in b)e=="bubbles"?d=!!b[e]:c[e]=b[e];return c.initEvent(a,d,!0),y(c)}}(Zepto),function($){function triggerAndReturn(a,b,c){var d=$.Event(b);return $(a).trigger(d,c),!d.isDefaultPrevented()}function triggerGlobal(a,b,c,d){if(a.global)return triggerAndReturn(b||document,c,d)}function ajaxStart(a){a.global&&$.active++===0&&triggerGlobal(a,null,"ajaxStart")}function ajaxStop(a){a.global&&!--$.active&&triggerGlobal(a,null,"ajaxStop")}function ajaxBeforeSend(a,b){var c=b.context;if(b.beforeSend.call(c,a,b)===!1||triggerGlobal(b,c,"ajaxBeforeSend",[a,b])===!1)return!1;triggerGlobal(b,c,"ajaxSend",[a,b])}function ajaxSuccess(a,b,c,d){var e=c.context,f="success";c.success.call(e,a,f,b),d&&d.resolveWith(e,[a,f,b]),triggerGlobal(c,e,"ajaxSuccess",[b,c,a]),ajaxComplete(f,b,c)}function ajaxError(a,b,c,d,e){var f=d.context;d.error.call(f,c,b,a),e&&e.rejectWith(f,[c,b,a]),triggerGlobal(d,f,"ajaxError",[c,d,a||b]),ajaxComplete(b,c,d)}function ajaxComplete(a,b,c){var d=c.context;c.complete.call(d,b,a),triggerGlobal(c,d,"ajaxComplete",[b,c]),ajaxStop(c)}function empty(){}function mimeToDataType(a){return a&&(a=a.split(";",2)[0]),a&&(a==htmlType?"html":a==jsonType?"json":scriptTypeRE.test(a)?"script":xmlTypeRE.test(a)&&"xml")||"text"}function appendQuery(a,b){return b==""?a:(a+"&"+b).replace(/[&?]{1,2}/,"?")}function serializeData(a){a.processData&&a.data&&$.type(a.data)!="string"&&(a.data=$.param(a.data,a.traditional)),a.data&&(!a.type||a.type.toUpperCase()=="GET")&&(a.url=appendQuery(a.url,a.data),a.data=undefined)}function parseArguments(a,b,c,d){var e=!$.isFunction(b);return{url:a,data:e?b:undefined,success:e?$.isFunction(c)?c:undefined:b,dataType:e?d||c:c}}function serialize(a,b,c,d){var e,f=$.isArray(b),g=$.isPlainObject(b);$.each(b,function(b,h){e=$.type(h),d&&(b=c?d:d+"["+(g||e=="object"||e=="array"?b:"")+"]"),!d&&f?a.add(h.name,h.value):e=="array"||!c&&e=="object"?serialize(a,h,c,b):a.add(b,h)})}var jsonpID=0,document=window.document,key,name,rscript=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,scriptTypeRE=/^(?:text|application)\/javascript/i,xmlTypeRE=/^(?:text|application)\/xml/i,jsonType="application/json",htmlType="text/html",blankRE=/^\s*$/;$.active=0,$.ajaxJSONP=function(a,b){if("type"in a){var c=a.jsonpCallback,d=($.isFunction(c)?c():c)||"jsonp"+ ++jsonpID,e=document.createElement("script"),f=window[d],g,h=function(a){$(e).triggerHandler("error",a||"abort")},i={abort:h},j;return b&&b.promise(i),$(e).on("load error",function(c,h){clearTimeout(j),$(e).off().remove(),c.type=="error"||!g?ajaxError(null,h||"error",i,a,b):ajaxSuccess(g[0],i,a,b),window[d]=f,g&&$.isFunction(f)&&f(g[0]),f=g=undefined}),ajaxBeforeSend(i,a)===!1?(h("abort"),i):(window[d]=function(){g=arguments},e.src=a.url.replace(/=\?/,"="+d),document.head.appendChild(e),a.timeout>0&&(j=setTimeout(function(){h("timeout")},a.timeout)),i)}return $.ajax(a)},$.ajaxSettings={type:"GET",beforeSend:empty,success:empty,error:empty,complete:empty,context:null,global:!0,xhr:function(){return new window.XMLHttpRequest},accepts:{script:"text/javascript, application/javascript, application/x-javascript",json:jsonType,xml:"application/xml, text/xml",html:htmlType,text:"text/plain"},crossDomain:!1,timeout:0,processData:!0,cache:!0},$.ajax=function(options){var settings=$.extend({},options||{}),deferred=$.Deferred&&$.Deferred();for(key in $.ajaxSettings)settings[key]===undefined&&(settings[key]=$.ajaxSettings[key]);ajaxStart(settings),settings.crossDomain||(settings.crossDomain=/^([\w-]+:)?\/\/([^\/]+)/.test(settings.url)&&RegExp.$2!=window.location.host),settings.url||(settings.url=window.location.toString()),serializeData(settings),settings.cache===!1&&(settings.url=appendQuery(settings.url,"_="+Date.now()));var dataType=settings.dataType,hasPlaceholder=/=\?/.test(settings.url);if(dataType=="jsonp"||hasPlaceholder)return hasPlaceholder||(settings.url=appendQuery(settings.url,settings.jsonp?settings.jsonp+"=?":settings.jsonp===!1?"":"callback=?")),$.ajaxJSONP(settings,deferred);var mime=settings.accepts[dataType],headers={},setHeader=function(a,b){headers[a.toLowerCase()]=[a,b]},protocol=/^([\w-]+:)\/\//.test(settings.url)?RegExp.$1:window.location.protocol,xhr=settings.xhr(),nativeSetHeader=xhr.setRequestHeader,abortTimeout;deferred&&deferred.promise(xhr),settings.crossDomain||setHeader("X-Requested-With","XMLHttpRequest"),setHeader("Accept",mime||"*/*");if(mime=settings.mimeType||mime)mime.indexOf(",")>-1&&(mime=mime.split(",",2)[0]),xhr.overrideMimeType&&xhr.overrideMimeType(mime);(settings.contentType||settings.contentType!==!1&&settings.data&&settings.type.toUpperCase()!="GET")&&setHeader("Content-Type",settings.contentType||"application/x-www-form-urlencoded");if(settings.headers)for(name in settings.headers)setHeader(name,settings.headers[name]);xhr.setRequestHeader=setHeader,xhr.onreadystatechange=function(){if(xhr.readyState==4){xhr.onreadystatechange=empty,clearTimeout(abortTimeout);var result,error=!1;if(xhr.status>=200&&xhr.status<300||xhr.status==304||xhr.status==0&&protocol=="file:"){dataType=dataType||mimeToDataType(settings.mimeType||xhr.getResponseHeader("content-type")),result=xhr.responseText;try{dataType=="script"?(1,eval)(result):dataType=="xml"?result=xhr.responseXML:dataType=="json"&&(result=blankRE.test(result)?null:$.parseJSON(result))}catch(e){error=e}error?ajaxError(error,"parsererror",xhr,settings,deferred):ajaxSuccess(result,xhr,settings,deferred)}else ajaxError(xhr.statusText||null,xhr.status?"error":"abort",xhr,settings,deferred)}};if(ajaxBeforeSend(xhr,settings)===!1)return xhr.abort(),ajaxError(null,"abort",xhr,settings,deferred),xhr;if(settings.xhrFields)for(name in settings.xhrFields)xhr[name]=settings.xhrFields[name];var async="async"in settings?settings.async:!0;xhr.open(settings.type,settings.url,async,settings.username,settings.password);for(name in headers)nativeSetHeader.apply(xhr,headers[name]);return settings.timeout>0&&(abortTimeout=setTimeout(function(){xhr.onreadystatechange=empty,xhr.abort(),ajaxError(null,"timeout",xhr,settings,deferred)},settings.timeout)),xhr.send(settings.data?settings.data:null),xhr},$.get=function(a,b,c,d){return $.ajax(parseArguments.apply(null,arguments))},$.post=function(a,b,c,d){var e=parseArguments.apply(null,arguments);return e.type="POST",$.ajax(e)},$.getJSON=function(a,b,c){var d=parseArguments.apply(null,arguments);return d.dataType="json",$.ajax(d)},$.fn.load=function(a,b,c){if(!this.length)return this;var d=this,e=a.split(/\s/),f,g=parseArguments(a,b,c),h=g.success;return e.length>1&&(g.url=e[0],f=e[1]),g.success=function(a){d.html(f?$("<div>").html(a.replace(rscript,"")).find(f):a),h&&h.apply(d,arguments)},$.ajax(g),this};var escape=encodeURIComponent;$.param=function(a,b){var c=[];return c.add=function(a,b){this.push(escape(a)+"="+escape(b))},serialize(c,a,b),c.join("&").replace(/%20/g,"+")}}(Zepto),function(a){a.fn.serializeArray=function(){var b=[],c;return a([].slice.call(this.get(0).elements)).each(function(){c=a(this);var d=c.attr("type");this.nodeName.toLowerCase()!="fieldset"&&!this.disabled&&d!="submit"&&d!="reset"&&d!="button"&&(d!="radio"&&d!="checkbox"||this.checked)&&b.push({name:c.attr("name"),value:c.val()})}),b},a.fn.serialize=function(){var a=[];return this.serializeArray().forEach(function(b){a.push(encodeURIComponent(b.name)+"="+encodeURIComponent(b.value))}),a.join("&")},a.fn.submit=function(b){if(b)this.bind("submit",b);else if(this.length){var c=a.Event("submit");this.eq(0).trigger(c),c.isDefaultPrevented()||this.get(0).submit()}return this}}(Zepto),function(a){"__proto__"in{}||a.extend(a.zepto,{Z:function(b,c){return b=b||[],a.extend(b,a.fn),b.selector=c||"",b.__Z=!0,b},isZ:function(b){return a.type(b)==="array"&&"__Z"in b}});try{getComputedStyle(undefined)}catch(b){var c=getComputedStyle;window.getComputedStyle=function(a){try{return c(a)}catch(b){return null}}}}(Zepto) </script> <style type="text/css"> body { background: #F9F9F9; font-size: 14px; line-height: 22px; font-family: Helvetica Neue, Helvetica, Arial; } a { color: #000; text-decoration: underline; } li ul, li ol{ margin: 0; } .anchor { cursor: pointer; } .anchor .anchor_char{ visibility: hidden; padding-left: 0.2em; font-size: 0.9em; opacity: 0.5; } .anchor:hover .anchor_char{ visibility: visible; } .sidebar{ background: #FFF; position: fixed; z-index: 10; top: 0; left: 0; bottom: 0; width: 230px; overflow-y: auto; overflow-x: hidden; padding: 15px 0 30px 30px; border-right: 1px solid #bbb; font-family: "Lucida Grande", "Lucida Sans Unicode", Helvetica, Arial, sans-serif !important; } .sidebar ul{ margin: 0; list-style: none; padding: 0; } .sidebar ul a:hover { text-decoration: underline; color: #333; } .sidebar > ul > li { margin-top: 15px; } .sidebar > ul > li > a { font-weight: bold; } .sidebar ul ul { margin-top: 5px; font-size: 11px; line-height: 14px; } .sidebar ul ul li:before { content: "- "; } .sidebar ul ul li { margin-bottom: 3px; } .sidebar ul ul li a { text-decoration: none; } .toggle_sidebar_button{ display: none; position: fixed; z-index: 11; top: 0; width: 44px; height: 44px; background: #000; background: rgba(0,0,0,0.7); margin-left: 230px; } .toggle_sidebar_button:hover { background: rgba(0,0,0,1); cursor: pointer; } .toggle_sidebar_button .line{ height: 2px; width: 21px; margin-left: 11px; margin-top: 5px; background: #FFF; } .toggle_sidebar_button .line:first-child { margin-top: 15px; } .main_container { width: 100%; padding-left: 260px; margin: 30px; margin-left: 0px; padding-right: 30px; } .main_container p, ul{ margin: 25px 0; } .main_container ul { list-style: circle; font-size: 13px; line-height: 18px; padding-left: 15px; } pre { font-size: 12px; border: 4px solid #bbb; border-top: 0; border-bottom: 0; margin: 0px 0 25px; padding-top: 0px; padding-bottom: 0px; font-family: Monaco, Consolas, "Lucida Console", monospace; line-height: 18px; font-style: normal; background: none; border-radius: 0px; overflow-x: scroll; word-wrap: normal; white-space: pre; } .main_container { width: 840px; } .main_container p, ul, pre { width: 100%; } code { padding: 0px 3px; color: #333; background: #fff; border: 1px solid #ddd; zoom: 1; white-space: nowrap; border-radius: 0; font-family: Monaco, Consolas, "Lucida Console", monospace; font-size: 12px; line-height: 18px; font-style: normal; } em { font-size: 12px; line-height: 18px; } @media (max-width: 820px) { .sidebar { display: none; } .main_container { padding: 0px; width: 100%; } .main_container > *{ padding-left: 10px; padding-right: 10px; } .main_container > ul, .main_container > ol { padding-left: 27px; } .force_show_sidebar .main_container { display: none; } .force_show_sidebar .sidebar { width: 100%; } .force_show_sidebar .sidebar a{ font-size: 1.5em; line-height: 1.5em; } .force_show_sidebar .toggle_sidebar_button { right: 0; } .force_show_sidebar .toggle_sidebar_button .line:first-child, .force_show_sidebar .toggle_sidebar_button .line:last-child { visibility: hidden; } .toggle_sidebar_button { margin-left: 0px; display: block; } pre { font-size: 12px; border: 1px solid #bbb; border-left: 0; border-right: 0; padding: 9px; background: #FFF; } code { word-wrap: break-word; white-space: normal; } } .force_show_sidebar .sidebar { display: block; } .force_show_sidebar .main_container { padding-left: 260px; } .force_show_sidebar .toggle_sidebar_button{ margin-left: 230px; } </style> <script type="text/javascript"> $(function(){ $('.toggle_sidebar_button').on('click', function(){ $('body').toggleClass('force_show_sidebar'); }); // hide sidebar on every click in menu (if small screen) $('.sidebar').find('a').on('click', function(){ $('body').removeClass('force_show_sidebar'); }); // add anchors $.each($('.main_container').find('h1,h2,h3,h4,h5,h6'), function(key, item){ if ($(item).attr('id')) { $(item).addClass('anchor'); $(item).append($('<span class="anchor_char">¶</span>')) $(item).on('click', function(){ window.location = '#' + $(item).attr('id'); }) } }); // remove <code> tag inside of <pre> $.each($('pre > code'), function(key, item){ $(item).parent().html($(item).html()) }) }) </script> </head> <body> <a class="toggle_sidebar_button"> <div class="line"></div> <div class="line"></div> <div class="line"></div> </a> <div class="sidebar"> <!-- toc --> </div> <div class="main_container"> <!-- main_content --> </div> </body> </html>''' def force_text(text): if isinstance(text, unicode): return text else: return text.decode('utf-8') class BackDoc(object): def __init__(self, markdown_converter, template_html, stdin, stdout): self.markdown_converter = markdown_converter self.template_html = force_text(template_html) self.stdin = stdin self.stdout = stdout self.parser = self.get_parser() def run(self, argv): kwargs = self.get_kwargs(argv) self.stdout.write(self.get_result_html(**kwargs)) def get_kwargs(self, argv): parsed = dict(self.parser.parse_args(argv)._get_kwargs()) return self.prepare_kwargs_from_parsed_data(parsed) def prepare_kwargs_from_parsed_data(self, parsed): kwargs = {} kwargs['title'] = force_text(parsed.get('title') or 'Documentation') if parsed.get('source'): kwargs['markdown_src'] = open(parsed['source'], 'r').read() else: kwargs['markdown_src'] = self.stdin.read() kwargs['markdown_src'] = force_text(kwargs['markdown_src'] or '') return kwargs def get_result_html(self, title, markdown_src): response = self.get_converted_to_html_response(markdown_src) return ( self.template_html.replace('<!-- title -->', title) .replace('<!-- toc -->', response.toc_html and force_text(response.toc_html) or '') .replace('<!-- main_content -->', force_text(response)) ) def get_converted_to_html_response(self, markdown_src): return self.markdown_converter.convert(markdown_src) def get_parser(self): parser = argparse.ArgumentParser() parser.add_argument( '-t', '--title', help='Documentation title header', required=False, ) parser.add_argument( '-s', '--source', help='Markdown source file path', required=False, ) return parser if __name__ == '__main__': BackDoc( markdown_converter=Markdown(extras=['toc']), template_html=template_html, stdin=sys.stdin, stdout=sys.stdout ).run(argv=sys.argv[1:])
chibisov/drf-extensions
docs/backdoc.py
_xml_escape_attr
python
def _xml_escape_attr(attr, skip_single_quote=True): escaped = (attr .replace('&', '&amp;') .replace('"', '&quot;') .replace('<', '&lt;') .replace('>', '&gt;')) if not skip_single_quote: escaped = escaped.replace("'", "&#39;") return escaped
Escape the given string for use in an HTML/XML tag attribute. By default this doesn't bother with escaping `'` to `&#39;`, presuming that the tag attribute is surrounded by double quotes.
train
https://github.com/chibisov/drf-extensions/blob/1d28a4b28890eab5cd19e93e042f8590c8c2fb8b/docs/backdoc.py#L2164-L2177
null
# -*- coding: utf-8 -*- #!/usr/bin/env python """ Backdoc is a tool for backbone-like documentation generation. Backdoc main goal is to help to generate one page documentation from one markdown source file. https://github.com/chibisov/backdoc """ import sys import argparse # -*- coding: utf-8 -*- #!/usr/bin/env python # Copyright (c) 2012 Trent Mick. # Copyright (c) 2007-2008 ActiveState Corp. # License: MIT (http://www.opensource.org/licenses/mit-license.php) r"""A fast and complete Python implementation of Markdown. [from http://daringfireball.net/projects/markdown/] > Markdown is a text-to-HTML filter; it translates an easy-to-read / > easy-to-write structured text format into HTML. Markdown's text > format is most similar to that of plain text email, and supports > features such as headers, *emphasis*, code blocks, blockquotes, and > links. > > Markdown's syntax is designed not as a generic markup language, but > specifically to serve as a front-end to (X)HTML. You can use span-level > HTML tags anywhere in a Markdown document, and you can use block level > HTML tags (like <div> and <table> as well). Module usage: >>> import markdown2 >>> markdown2.markdown("*boo!*") # or use `html = markdown_path(PATH)` u'<p><em>boo!</em></p>\n' >>> markdowner = Markdown() >>> markdowner.convert("*boo!*") u'<p><em>boo!</em></p>\n' >>> markdowner.convert("**boom!**") u'<p><strong>boom!</strong></p>\n' This implementation of Markdown implements the full "core" syntax plus a number of extras (e.g., code syntax coloring, footnotes) as described on <https://github.com/trentm/python-markdown2/wiki/Extras>. """ cmdln_desc = """A fast and complete Python implementation of Markdown, a text-to-HTML conversion tool for web writers. Supported extra syntax options (see -x|--extras option below and see <https://github.com/trentm/python-markdown2/wiki/Extras> for details): * code-friendly: Disable _ and __ for em and strong. * cuddled-lists: Allow lists to be cuddled to the preceding paragraph. * fenced-code-blocks: Allows a code block to not have to be indented by fencing it with '```' on a line before and after. Based on <http://github.github.com/github-flavored-markdown/> with support for syntax highlighting. * footnotes: Support footnotes as in use on daringfireball.net and implemented in other Markdown processors (tho not in Markdown.pl v1.0.1). * header-ids: Adds "id" attributes to headers. The id value is a slug of the header text. * html-classes: Takes a dict mapping html tag names (lowercase) to a string to use for a "class" tag attribute. Currently only supports "pre" and "code" tags. Add an issue if you require this for other tags. * markdown-in-html: Allow the use of `markdown="1"` in a block HTML tag to have markdown processing be done on its contents. Similar to <http://michelf.com/projects/php-markdown/extra/#markdown-attr> but with some limitations. * metadata: Extract metadata from a leading '---'-fenced block. See <https://github.com/trentm/python-markdown2/issues/77> for details. * nofollow: Add `rel="nofollow"` to add `<a>` tags with an href. See <http://en.wikipedia.org/wiki/Nofollow>. * pyshell: Treats unindented Python interactive shell sessions as <code> blocks. * link-patterns: Auto-link given regex patterns in text (e.g. bug number references, revision number references). * smarty-pants: Replaces ' and " with curly quotation marks or curly apostrophes. Replaces --, ---, ..., and . . . with en dashes, em dashes, and ellipses. * toc: The returned HTML string gets a new "toc_html" attribute which is a Table of Contents for the document. (experimental) * xml: Passes one-liner processing instructions and namespaced XML tags. * wiki-tables: Google Code Wiki-style tables. See <http://code.google.com/p/support/wiki/WikiSyntax#Tables>. """ # Dev Notes: # - Python's regex syntax doesn't have '\z', so I'm using '\Z'. I'm # not yet sure if there implications with this. Compare 'pydoc sre' # and 'perldoc perlre'. __version_info__ = (2, 1, 1) __version__ = '.'.join(map(str, __version_info__)) __author__ = "Trent Mick" import os import sys from pprint import pprint import re import logging try: from hashlib import md5 except ImportError: from md5 import md5 import optparse from random import random, randint import codecs #---- Python version compat try: from urllib.parse import quote # python3 except ImportError: from urllib import quote # python2 if sys.version_info[:2] < (2,4): from sets import Set as set def reversed(sequence): for i in sequence[::-1]: yield i # Use `bytes` for byte strings and `unicode` for unicode strings (str in Py3). if sys.version_info[0] <= 2: py3 = False try: bytes except NameError: bytes = str base_string_type = basestring elif sys.version_info[0] >= 3: py3 = True unicode = str base_string_type = str #---- globals DEBUG = False log = logging.getLogger("markdown") DEFAULT_TAB_WIDTH = 4 SECRET_SALT = bytes(randint(0, 1000000)) def _hash_text(s): return 'md5-' + md5(SECRET_SALT + s.encode("utf-8")).hexdigest() # Table of hash values for escaped characters: g_escape_table = dict([(ch, _hash_text(ch)) for ch in '\\`*_{}[]()>#+-.!']) #---- exceptions class MarkdownError(Exception): pass #---- public api def markdown_path(path, encoding="utf-8", html4tags=False, tab_width=DEFAULT_TAB_WIDTH, safe_mode=None, extras=None, link_patterns=None, use_file_vars=False): fp = codecs.open(path, 'r', encoding) text = fp.read() fp.close() return Markdown(html4tags=html4tags, tab_width=tab_width, safe_mode=safe_mode, extras=extras, link_patterns=link_patterns, use_file_vars=use_file_vars).convert(text) def markdown(text, html4tags=False, tab_width=DEFAULT_TAB_WIDTH, safe_mode=None, extras=None, link_patterns=None, use_file_vars=False): return Markdown(html4tags=html4tags, tab_width=tab_width, safe_mode=safe_mode, extras=extras, link_patterns=link_patterns, use_file_vars=use_file_vars).convert(text) class Markdown(object): # The dict of "extras" to enable in processing -- a mapping of # extra name to argument for the extra. Most extras do not have an # argument, in which case the value is None. # # This can be set via (a) subclassing and (b) the constructor # "extras" argument. extras = None urls = None titles = None html_blocks = None html_spans = None html_removed_text = "[HTML_REMOVED]" # for compat with markdown.py # Used to track when we're inside an ordered or unordered list # (see _ProcessListItems() for details): list_level = 0 _ws_only_line_re = re.compile(r"^[ \t]+$", re.M) def __init__(self, html4tags=False, tab_width=4, safe_mode=None, extras=None, link_patterns=None, use_file_vars=False): if html4tags: self.empty_element_suffix = ">" else: self.empty_element_suffix = " />" self.tab_width = tab_width # For compatibility with earlier markdown2.py and with # markdown.py's safe_mode being a boolean, # safe_mode == True -> "replace" if safe_mode is True: self.safe_mode = "replace" else: self.safe_mode = safe_mode # Massaging and building the "extras" info. if self.extras is None: self.extras = {} elif not isinstance(self.extras, dict): self.extras = dict([(e, None) for e in self.extras]) if extras: if not isinstance(extras, dict): extras = dict([(e, None) for e in extras]) self.extras.update(extras) assert isinstance(self.extras, dict) if "toc" in self.extras and not "header-ids" in self.extras: self.extras["header-ids"] = None # "toc" implies "header-ids" self._instance_extras = self.extras.copy() self.link_patterns = link_patterns self.use_file_vars = use_file_vars self._outdent_re = re.compile(r'^(\t|[ ]{1,%d})' % tab_width, re.M) self._escape_table = g_escape_table.copy() if "smarty-pants" in self.extras: self._escape_table['"'] = _hash_text('"') self._escape_table["'"] = _hash_text("'") def reset(self): self.urls = {} self.titles = {} self.html_blocks = {} self.html_spans = {} self.list_level = 0 self.extras = self._instance_extras.copy() if "footnotes" in self.extras: self.footnotes = {} self.footnote_ids = [] if "header-ids" in self.extras: self._count_from_header_id = {} # no `defaultdict` in Python 2.4 if "metadata" in self.extras: self.metadata = {} # Per <https://developer.mozilla.org/en-US/docs/HTML/Element/a> "rel" # should only be used in <a> tags with an "href" attribute. _a_nofollow = re.compile(r"<(a)([^>]*href=)", re.IGNORECASE) def convert(self, text): """Convert the given text.""" # Main function. The order in which other subs are called here is # essential. Link and image substitutions need to happen before # _EscapeSpecialChars(), so that any *'s or _'s in the <a> # and <img> tags get encoded. # Clear the global hashes. If we don't clear these, you get conflicts # from other articles when generating a page which contains more than # one article (e.g. an index page that shows the N most recent # articles): self.reset() if not isinstance(text, unicode): #TODO: perhaps shouldn't presume UTF-8 for string input? text = unicode(text, 'utf-8') if self.use_file_vars: # Look for emacs-style file variable hints. emacs_vars = self._get_emacs_vars(text) if "markdown-extras" in emacs_vars: splitter = re.compile("[ ,]+") for e in splitter.split(emacs_vars["markdown-extras"]): if '=' in e: ename, earg = e.split('=', 1) try: earg = int(earg) except ValueError: pass else: ename, earg = e, None self.extras[ename] = earg # Standardize line endings: text = re.sub("\r\n|\r", "\n", text) # Make sure $text ends with a couple of newlines: text += "\n\n" # Convert all tabs to spaces. text = self._detab(text) # Strip any lines consisting only of spaces and tabs. # This makes subsequent regexen easier to write, because we can # match consecutive blank lines with /\n+/ instead of something # contorted like /[ \t]*\n+/ . text = self._ws_only_line_re.sub("", text) # strip metadata from head and extract if "metadata" in self.extras: text = self._extract_metadata(text) text = self.preprocess(text) if self.safe_mode: text = self._hash_html_spans(text) # Turn block-level HTML blocks into hash entries text = self._hash_html_blocks(text, raw=True) # Strip link definitions, store in hashes. if "footnotes" in self.extras: # Must do footnotes first because an unlucky footnote defn # looks like a link defn: # [^4]: this "looks like a link defn" text = self._strip_footnote_definitions(text) text = self._strip_link_definitions(text) text = self._run_block_gamut(text) if "footnotes" in self.extras: text = self._add_footnotes(text) text = self.postprocess(text) text = self._unescape_special_chars(text) if self.safe_mode: text = self._unhash_html_spans(text) if "nofollow" in self.extras: text = self._a_nofollow.sub(r'<\1 rel="nofollow"\2', text) text += "\n" rv = UnicodeWithAttrs(text) if "toc" in self.extras: rv._toc = self._toc if "metadata" in self.extras: rv.metadata = self.metadata return rv def postprocess(self, text): """A hook for subclasses to do some postprocessing of the html, if desired. This is called before unescaping of special chars and unhashing of raw HTML spans. """ return text def preprocess(self, text): """A hook for subclasses to do some preprocessing of the Markdown, if desired. This is called after basic formatting of the text, but prior to any extras, safe mode, etc. processing. """ return text # Is metadata if the content starts with '---'-fenced `key: value` # pairs. E.g. (indented for presentation): # --- # foo: bar # another-var: blah blah # --- _metadata_pat = re.compile("""^---[ \t]*\n((?:[ \t]*[^ \t:]+[ \t]*:[^\n]*\n)+)---[ \t]*\n""") def _extract_metadata(self, text): # fast test if not text.startswith("---"): return text match = self._metadata_pat.match(text) if not match: return text tail = text[len(match.group(0)):] metadata_str = match.group(1).strip() for line in metadata_str.split('\n'): key, value = line.split(':', 1) self.metadata[key.strip()] = value.strip() return tail _emacs_oneliner_vars_pat = re.compile(r"-\*-\s*([^\r\n]*?)\s*-\*-", re.UNICODE) # This regular expression is intended to match blocks like this: # PREFIX Local Variables: SUFFIX # PREFIX mode: Tcl SUFFIX # PREFIX End: SUFFIX # Some notes: # - "[ \t]" is used instead of "\s" to specifically exclude newlines # - "(\r\n|\n|\r)" is used instead of "$" because the sre engine does # not like anything other than Unix-style line terminators. _emacs_local_vars_pat = re.compile(r"""^ (?P<prefix>(?:[^\r\n|\n|\r])*?) [\ \t]*Local\ Variables:[\ \t]* (?P<suffix>.*?)(?:\r\n|\n|\r) (?P<content>.*?\1End:) """, re.IGNORECASE | re.MULTILINE | re.DOTALL | re.VERBOSE) def _get_emacs_vars(self, text): """Return a dictionary of emacs-style local variables. Parsing is done loosely according to this spec (and according to some in-practice deviations from this): http://www.gnu.org/software/emacs/manual/html_node/emacs/Specifying-File-Variables.html#Specifying-File-Variables """ emacs_vars = {} SIZE = pow(2, 13) # 8kB # Search near the start for a '-*-'-style one-liner of variables. head = text[:SIZE] if "-*-" in head: match = self._emacs_oneliner_vars_pat.search(head) if match: emacs_vars_str = match.group(1) assert '\n' not in emacs_vars_str emacs_var_strs = [s.strip() for s in emacs_vars_str.split(';') if s.strip()] if len(emacs_var_strs) == 1 and ':' not in emacs_var_strs[0]: # While not in the spec, this form is allowed by emacs: # -*- Tcl -*- # where the implied "variable" is "mode". This form # is only allowed if there are no other variables. emacs_vars["mode"] = emacs_var_strs[0].strip() else: for emacs_var_str in emacs_var_strs: try: variable, value = emacs_var_str.strip().split(':', 1) except ValueError: log.debug("emacs variables error: malformed -*- " "line: %r", emacs_var_str) continue # Lowercase the variable name because Emacs allows "Mode" # or "mode" or "MoDe", etc. emacs_vars[variable.lower()] = value.strip() tail = text[-SIZE:] if "Local Variables" in tail: match = self._emacs_local_vars_pat.search(tail) if match: prefix = match.group("prefix") suffix = match.group("suffix") lines = match.group("content").splitlines(0) #print "prefix=%r, suffix=%r, content=%r, lines: %s"\ # % (prefix, suffix, match.group("content"), lines) # Validate the Local Variables block: proper prefix and suffix # usage. for i, line in enumerate(lines): if not line.startswith(prefix): log.debug("emacs variables error: line '%s' " "does not use proper prefix '%s'" % (line, prefix)) return {} # Don't validate suffix on last line. Emacs doesn't care, # neither should we. if i != len(lines)-1 and not line.endswith(suffix): log.debug("emacs variables error: line '%s' " "does not use proper suffix '%s'" % (line, suffix)) return {} # Parse out one emacs var per line. continued_for = None for line in lines[:-1]: # no var on the last line ("PREFIX End:") if prefix: line = line[len(prefix):] # strip prefix if suffix: line = line[:-len(suffix)] # strip suffix line = line.strip() if continued_for: variable = continued_for if line.endswith('\\'): line = line[:-1].rstrip() else: continued_for = None emacs_vars[variable] += ' ' + line else: try: variable, value = line.split(':', 1) except ValueError: log.debug("local variables error: missing colon " "in local variables entry: '%s'" % line) continue # Do NOT lowercase the variable name, because Emacs only # allows "mode" (and not "Mode", "MoDe", etc.) in this block. value = value.strip() if value.endswith('\\'): value = value[:-1].rstrip() continued_for = variable else: continued_for = None emacs_vars[variable] = value # Unquote values. for var, val in list(emacs_vars.items()): if len(val) > 1 and (val.startswith('"') and val.endswith('"') or val.startswith('"') and val.endswith('"')): emacs_vars[var] = val[1:-1] return emacs_vars # Cribbed from a post by Bart Lateur: # <http://www.nntp.perl.org/group/perl.macperl.anyperl/154> _detab_re = re.compile(r'(.*?)\t', re.M) def _detab_sub(self, match): g1 = match.group(1) return g1 + (' ' * (self.tab_width - len(g1) % self.tab_width)) def _detab(self, text): r"""Remove (leading?) tabs from a file. >>> m = Markdown() >>> m._detab("\tfoo") ' foo' >>> m._detab(" \tfoo") ' foo' >>> m._detab("\t foo") ' foo' >>> m._detab(" foo") ' foo' >>> m._detab(" foo\n\tbar\tblam") ' foo\n bar blam' """ if '\t' not in text: return text return self._detab_re.subn(self._detab_sub, text)[0] # I broke out the html5 tags here and add them to _block_tags_a and # _block_tags_b. This way html5 tags are easy to keep track of. _html5tags = '|article|aside|header|hgroup|footer|nav|section|figure|figcaption' _block_tags_a = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del' _block_tags_a += _html5tags _strict_tag_block_re = re.compile(r""" ( # save in \1 ^ # start of line (with re.M) <(%s) # start tag = \2 \b # word break (.*\n)*? # any number of lines, minimally matching </\2> # the matching end tag [ \t]* # trailing spaces/tabs (?=\n+|\Z) # followed by a newline or end of document ) """ % _block_tags_a, re.X | re.M) _block_tags_b = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math' _block_tags_b += _html5tags _liberal_tag_block_re = re.compile(r""" ( # save in \1 ^ # start of line (with re.M) <(%s) # start tag = \2 \b # word break (.*\n)*? # any number of lines, minimally matching .*</\2> # the matching end tag [ \t]* # trailing spaces/tabs (?=\n+|\Z) # followed by a newline or end of document ) """ % _block_tags_b, re.X | re.M) _html_markdown_attr_re = re.compile( r'''\s+markdown=("1"|'1')''') def _hash_html_block_sub(self, match, raw=False): html = match.group(1) if raw and self.safe_mode: html = self._sanitize_html(html) elif 'markdown-in-html' in self.extras and 'markdown=' in html: first_line = html.split('\n', 1)[0] m = self._html_markdown_attr_re.search(first_line) if m: lines = html.split('\n') middle = '\n'.join(lines[1:-1]) last_line = lines[-1] first_line = first_line[:m.start()] + first_line[m.end():] f_key = _hash_text(first_line) self.html_blocks[f_key] = first_line l_key = _hash_text(last_line) self.html_blocks[l_key] = last_line return ''.join(["\n\n", f_key, "\n\n", middle, "\n\n", l_key, "\n\n"]) key = _hash_text(html) self.html_blocks[key] = html return "\n\n" + key + "\n\n" def _hash_html_blocks(self, text, raw=False): """Hashify HTML blocks We only want to do this for block-level HTML tags, such as headers, lists, and tables. That's because we still want to wrap <p>s around "paragraphs" that are wrapped in non-block-level tags, such as anchors, phrase emphasis, and spans. The list of tags we're looking for is hard-coded. @param raw {boolean} indicates if these are raw HTML blocks in the original source. It makes a difference in "safe" mode. """ if '<' not in text: return text # Pass `raw` value into our calls to self._hash_html_block_sub. hash_html_block_sub = _curry(self._hash_html_block_sub, raw=raw) # First, look for nested blocks, e.g.: # <div> # <div> # tags for inner block must be indented. # </div> # </div> # # The outermost tags must start at the left margin for this to match, and # the inner nested divs must be indented. # We need to do this before the next, more liberal match, because the next # match will start at the first `<div>` and stop at the first `</div>`. text = self._strict_tag_block_re.sub(hash_html_block_sub, text) # Now match more liberally, simply from `\n<tag>` to `</tag>\n` text = self._liberal_tag_block_re.sub(hash_html_block_sub, text) # Special case just for <hr />. It was easier to make a special # case than to make the other regex more complicated. if "<hr" in text: _hr_tag_re = _hr_tag_re_from_tab_width(self.tab_width) text = _hr_tag_re.sub(hash_html_block_sub, text) # Special case for standalone HTML comments: if "<!--" in text: start = 0 while True: # Delimiters for next comment block. try: start_idx = text.index("<!--", start) except ValueError: break try: end_idx = text.index("-->", start_idx) + 3 except ValueError: break # Start position for next comment block search. start = end_idx # Validate whitespace before comment. if start_idx: # - Up to `tab_width - 1` spaces before start_idx. for i in range(self.tab_width - 1): if text[start_idx - 1] != ' ': break start_idx -= 1 if start_idx == 0: break # - Must be preceded by 2 newlines or hit the start of # the document. if start_idx == 0: pass elif start_idx == 1 and text[0] == '\n': start_idx = 0 # to match minute detail of Markdown.pl regex elif text[start_idx-2:start_idx] == '\n\n': pass else: break # Validate whitespace after comment. # - Any number of spaces and tabs. while end_idx < len(text): if text[end_idx] not in ' \t': break end_idx += 1 # - Must be following by 2 newlines or hit end of text. if text[end_idx:end_idx+2] not in ('', '\n', '\n\n'): continue # Escape and hash (must match `_hash_html_block_sub`). html = text[start_idx:end_idx] if raw and self.safe_mode: html = self._sanitize_html(html) key = _hash_text(html) self.html_blocks[key] = html text = text[:start_idx] + "\n\n" + key + "\n\n" + text[end_idx:] if "xml" in self.extras: # Treat XML processing instructions and namespaced one-liner # tags as if they were block HTML tags. E.g., if standalone # (i.e. are their own paragraph), the following do not get # wrapped in a <p> tag: # <?foo bar?> # # <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="chapter_1.md"/> _xml_oneliner_re = _xml_oneliner_re_from_tab_width(self.tab_width) text = _xml_oneliner_re.sub(hash_html_block_sub, text) return text def _strip_link_definitions(self, text): # Strips link definitions from text, stores the URLs and titles in # hash references. less_than_tab = self.tab_width - 1 # Link defs are in the form: # [id]: url "optional title" _link_def_re = re.compile(r""" ^[ ]{0,%d}\[(.+)\]: # id = \1 [ \t]* \n? # maybe *one* newline [ \t]* <?(.+?)>? # url = \2 [ \t]* (?: \n? # maybe one newline [ \t]* (?<=\s) # lookbehind for whitespace ['"(] ([^\n]*) # title = \3 ['")] [ \t]* )? # title is optional (?:\n+|\Z) """ % less_than_tab, re.X | re.M | re.U) return _link_def_re.sub(self._extract_link_def_sub, text) def _extract_link_def_sub(self, match): id, url, title = match.groups() key = id.lower() # Link IDs are case-insensitive self.urls[key] = self._encode_amps_and_angles(url) if title: self.titles[key] = title return "" def _extract_footnote_def_sub(self, match): id, text = match.groups() text = _dedent(text, skip_first_line=not text.startswith('\n')).strip() normed_id = re.sub(r'\W', '-', id) # Ensure footnote text ends with a couple newlines (for some # block gamut matches). self.footnotes[normed_id] = text + "\n\n" return "" def _strip_footnote_definitions(self, text): """A footnote definition looks like this: [^note-id]: Text of the note. May include one or more indented paragraphs. Where, - The 'note-id' can be pretty much anything, though typically it is the number of the footnote. - The first paragraph may start on the next line, like so: [^note-id]: Text of the note. """ less_than_tab = self.tab_width - 1 footnote_def_re = re.compile(r''' ^[ ]{0,%d}\[\^(.+)\]: # id = \1 [ \t]* ( # footnote text = \2 # First line need not start with the spaces. (?:\s*.*\n+) (?: (?:[ ]{%d} | \t) # Subsequent lines must be indented. .*\n+ )* ) # Lookahead for non-space at line-start, or end of doc. (?:(?=^[ ]{0,%d}\S)|\Z) ''' % (less_than_tab, self.tab_width, self.tab_width), re.X | re.M) return footnote_def_re.sub(self._extract_footnote_def_sub, text) _hr_data = [ ('*', re.compile(r"^[ ]{0,3}\*(.*?)$", re.M)), ('-', re.compile(r"^[ ]{0,3}\-(.*?)$", re.M)), ('_', re.compile(r"^[ ]{0,3}\_(.*?)$", re.M)), ] def _run_block_gamut(self, text): # These are all the transformations that form block-level # tags like paragraphs, headers, and list items. if "fenced-code-blocks" in self.extras: text = self._do_fenced_code_blocks(text) text = self._do_headers(text) # Do Horizontal Rules: # On the number of spaces in horizontal rules: The spec is fuzzy: "If # you wish, you may use spaces between the hyphens or asterisks." # Markdown.pl 1.0.1's hr regexes limit the number of spaces between the # hr chars to one or two. We'll reproduce that limit here. hr = "\n<hr"+self.empty_element_suffix+"\n" for ch, regex in self._hr_data: if ch in text: for m in reversed(list(regex.finditer(text))): tail = m.group(1).rstrip() if not tail.strip(ch + ' ') and tail.count(" ") == 0: start, end = m.span() text = text[:start] + hr + text[end:] text = self._do_lists(text) if "pyshell" in self.extras: text = self._prepare_pyshell_blocks(text) if "wiki-tables" in self.extras: text = self._do_wiki_tables(text) text = self._do_code_blocks(text) text = self._do_block_quotes(text) # We already ran _HashHTMLBlocks() before, in Markdown(), but that # was to escape raw HTML in the original Markdown source. This time, # we're escaping the markup we've just created, so that we don't wrap # <p> tags around block-level tags. text = self._hash_html_blocks(text) text = self._form_paragraphs(text) return text def _pyshell_block_sub(self, match): lines = match.group(0).splitlines(0) _dedentlines(lines) indent = ' ' * self.tab_width s = ('\n' # separate from possible cuddled paragraph + indent + ('\n'+indent).join(lines) + '\n\n') return s def _prepare_pyshell_blocks(self, text): """Ensure that Python interactive shell sessions are put in code blocks -- even if not properly indented. """ if ">>>" not in text: return text less_than_tab = self.tab_width - 1 _pyshell_block_re = re.compile(r""" ^([ ]{0,%d})>>>[ ].*\n # first line ^(\1.*\S+.*\n)* # any number of subsequent lines ^\n # ends with a blank line """ % less_than_tab, re.M | re.X) return _pyshell_block_re.sub(self._pyshell_block_sub, text) def _wiki_table_sub(self, match): ttext = match.group(0).strip() #print 'wiki table: %r' % match.group(0) rows = [] for line in ttext.splitlines(0): line = line.strip()[2:-2].strip() row = [c.strip() for c in re.split(r'(?<!\\)\|\|', line)] rows.append(row) #pprint(rows) hlines = ['<table>', '<tbody>'] for row in rows: hrow = ['<tr>'] for cell in row: hrow.append('<td>') hrow.append(self._run_span_gamut(cell)) hrow.append('</td>') hrow.append('</tr>') hlines.append(''.join(hrow)) hlines += ['</tbody>', '</table>'] return '\n'.join(hlines) + '\n' def _do_wiki_tables(self, text): # Optimization. if "||" not in text: return text less_than_tab = self.tab_width - 1 wiki_table_re = re.compile(r''' (?:(?<=\n\n)|\A\n?) # leading blank line ^([ ]{0,%d})\|\|.+?\|\|[ ]*\n # first line (^\1\|\|.+?\|\|\n)* # any number of subsequent lines ''' % less_than_tab, re.M | re.X) return wiki_table_re.sub(self._wiki_table_sub, text) def _run_span_gamut(self, text): # These are all the transformations that occur *within* block-level # tags like paragraphs, headers, and list items. text = self._do_code_spans(text) text = self._escape_special_chars(text) # Process anchor and image tags. text = self._do_links(text) # Make links out of things like `<http://example.com/>` # Must come after _do_links(), because you can use < and > # delimiters in inline links like [this](<url>). text = self._do_auto_links(text) if "link-patterns" in self.extras: text = self._do_link_patterns(text) text = self._encode_amps_and_angles(text) text = self._do_italics_and_bold(text) if "smarty-pants" in self.extras: text = self._do_smart_punctuation(text) # Do hard breaks: text = re.sub(r" {2,}\n", " <br%s\n" % self.empty_element_suffix, text) return text # "Sorta" because auto-links are identified as "tag" tokens. _sorta_html_tokenize_re = re.compile(r""" ( # tag </? (?:\w+) # tag name (?:\s+(?:[\w-]+:)?[\w-]+=(?:".*?"|'.*?'))* # attributes \s*/?> | # auto-link (e.g., <http://www.activestate.com/>) <\w+[^>]*> | <!--.*?--> # comment | <\?.*?\?> # processing instruction ) """, re.X) def _escape_special_chars(self, text): # Python markdown note: the HTML tokenization here differs from # that in Markdown.pl, hence the behaviour for subtle cases can # differ (I believe the tokenizer here does a better job because # it isn't susceptible to unmatched '<' and '>' in HTML tags). # Note, however, that '>' is not allowed in an auto-link URL # here. escaped = [] is_html_markup = False for token in self._sorta_html_tokenize_re.split(text): if is_html_markup: # Within tags/HTML-comments/auto-links, encode * and _ # so they don't conflict with their use in Markdown for # italics and strong. We're replacing each such # character with its corresponding MD5 checksum value; # this is likely overkill, but it should prevent us from # colliding with the escape values by accident. escaped.append(token.replace('*', self._escape_table['*']) .replace('_', self._escape_table['_'])) else: escaped.append(self._encode_backslash_escapes(token)) is_html_markup = not is_html_markup return ''.join(escaped) def _hash_html_spans(self, text): # Used for safe_mode. def _is_auto_link(s): if ':' in s and self._auto_link_re.match(s): return True elif '@' in s and self._auto_email_link_re.match(s): return True return False tokens = [] is_html_markup = False for token in self._sorta_html_tokenize_re.split(text): if is_html_markup and not _is_auto_link(token): sanitized = self._sanitize_html(token) key = _hash_text(sanitized) self.html_spans[key] = sanitized tokens.append(key) else: tokens.append(token) is_html_markup = not is_html_markup return ''.join(tokens) def _unhash_html_spans(self, text): for key, sanitized in list(self.html_spans.items()): text = text.replace(key, sanitized) return text def _sanitize_html(self, s): if self.safe_mode == "replace": return self.html_removed_text elif self.safe_mode == "escape": replacements = [ ('&', '&amp;'), ('<', '&lt;'), ('>', '&gt;'), ] for before, after in replacements: s = s.replace(before, after) return s else: raise MarkdownError("invalid value for 'safe_mode': %r (must be " "'escape' or 'replace')" % self.safe_mode) _tail_of_inline_link_re = re.compile(r''' # Match tail of: [text](/url/) or [text](/url/ "title") \( # literal paren [ \t]* (?P<url> # \1 <.*?> | .*? ) [ \t]* ( # \2 (['"]) # quote char = \3 (?P<title>.*?) \3 # matching quote )? # title is optional \) ''', re.X | re.S) _tail_of_reference_link_re = re.compile(r''' # Match tail of: [text][id] [ ]? # one optional space (?:\n[ ]*)? # one optional newline followed by spaces \[ (?P<id>.*?) \] ''', re.X | re.S) def _do_links(self, text): """Turn Markdown link shortcuts into XHTML <a> and <img> tags. This is a combination of Markdown.pl's _DoAnchors() and _DoImages(). They are done together because that simplified the approach. It was necessary to use a different approach than Markdown.pl because of the lack of atomic matching support in Python's regex engine used in $g_nested_brackets. """ MAX_LINK_TEXT_SENTINEL = 3000 # markdown2 issue 24 # `anchor_allowed_pos` is used to support img links inside # anchors, but not anchors inside anchors. An anchor's start # pos must be `>= anchor_allowed_pos`. anchor_allowed_pos = 0 curr_pos = 0 while True: # Handle the next link. # The next '[' is the start of: # - an inline anchor: [text](url "title") # - a reference anchor: [text][id] # - an inline img: ![text](url "title") # - a reference img: ![text][id] # - a footnote ref: [^id] # (Only if 'footnotes' extra enabled) # - a footnote defn: [^id]: ... # (Only if 'footnotes' extra enabled) These have already # been stripped in _strip_footnote_definitions() so no # need to watch for them. # - a link definition: [id]: url "title" # These have already been stripped in # _strip_link_definitions() so no need to watch for them. # - not markup: [...anything else... try: start_idx = text.index('[', curr_pos) except ValueError: break text_length = len(text) # Find the matching closing ']'. # Markdown.pl allows *matching* brackets in link text so we # will here too. Markdown.pl *doesn't* currently allow # matching brackets in img alt text -- we'll differ in that # regard. bracket_depth = 0 for p in range(start_idx+1, min(start_idx+MAX_LINK_TEXT_SENTINEL, text_length)): ch = text[p] if ch == ']': bracket_depth -= 1 if bracket_depth < 0: break elif ch == '[': bracket_depth += 1 else: # Closing bracket not found within sentinel length. # This isn't markup. curr_pos = start_idx + 1 continue link_text = text[start_idx+1:p] # Possibly a footnote ref? if "footnotes" in self.extras and link_text.startswith("^"): normed_id = re.sub(r'\W', '-', link_text[1:]) if normed_id in self.footnotes: self.footnote_ids.append(normed_id) result = '<sup class="footnote-ref" id="fnref-%s">' \ '<a href="#fn-%s">%s</a></sup>' \ % (normed_id, normed_id, len(self.footnote_ids)) text = text[:start_idx] + result + text[p+1:] else: # This id isn't defined, leave the markup alone. curr_pos = p+1 continue # Now determine what this is by the remainder. p += 1 if p == text_length: return text # Inline anchor or img? if text[p] == '(': # attempt at perf improvement match = self._tail_of_inline_link_re.match(text, p) if match: # Handle an inline anchor or img. is_img = start_idx > 0 and text[start_idx-1] == "!" if is_img: start_idx -= 1 url, title = match.group("url"), match.group("title") if url and url[0] == '<': url = url[1:-1] # '<url>' -> 'url' # We've got to encode these to avoid conflicting # with italics/bold. url = url.replace('*', self._escape_table['*']) \ .replace('_', self._escape_table['_']) if title: title_str = ' title="%s"' % ( _xml_escape_attr(title) .replace('*', self._escape_table['*']) .replace('_', self._escape_table['_'])) else: title_str = '' if is_img: result = '<img src="%s" alt="%s"%s%s' \ % (url.replace('"', '&quot;'), _xml_escape_attr(link_text), title_str, self.empty_element_suffix) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) curr_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] elif start_idx >= anchor_allowed_pos: result_head = '<a href="%s"%s>' % (url, title_str) result = '%s%s</a>' % (result_head, link_text) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) # <img> allowed from curr_pos on, <a> from # anchor_allowed_pos on. curr_pos = start_idx + len(result_head) anchor_allowed_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] else: # Anchor not allowed here. curr_pos = start_idx + 1 continue # Reference anchor or img? else: match = self._tail_of_reference_link_re.match(text, p) if match: # Handle a reference-style anchor or img. is_img = start_idx > 0 and text[start_idx-1] == "!" if is_img: start_idx -= 1 link_id = match.group("id").lower() if not link_id: link_id = link_text.lower() # for links like [this][] if link_id in self.urls: url = self.urls[link_id] # We've got to encode these to avoid conflicting # with italics/bold. url = url.replace('*', self._escape_table['*']) \ .replace('_', self._escape_table['_']) title = self.titles.get(link_id) if title: before = title title = _xml_escape_attr(title) \ .replace('*', self._escape_table['*']) \ .replace('_', self._escape_table['_']) title_str = ' title="%s"' % title else: title_str = '' if is_img: result = '<img src="%s" alt="%s"%s%s' \ % (url.replace('"', '&quot;'), link_text.replace('"', '&quot;'), title_str, self.empty_element_suffix) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) curr_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] elif start_idx >= anchor_allowed_pos: result = '<a href="%s"%s>%s</a>' \ % (url, title_str, link_text) result_head = '<a href="%s"%s>' % (url, title_str) result = '%s%s</a>' % (result_head, link_text) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) # <img> allowed from curr_pos on, <a> from # anchor_allowed_pos on. curr_pos = start_idx + len(result_head) anchor_allowed_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] else: # Anchor not allowed here. curr_pos = start_idx + 1 else: # This id isn't defined, leave the markup alone. curr_pos = match.end() continue # Otherwise, it isn't markup. curr_pos = start_idx + 1 return text def header_id_from_text(self, text, prefix, n): """Generate a header id attribute value from the given header HTML content. This is only called if the "header-ids" extra is enabled. Subclasses may override this for different header ids. @param text {str} The text of the header tag @param prefix {str} The requested prefix for header ids. This is the value of the "header-ids" extra key, if any. Otherwise, None. @param n {int} The <hN> tag number, i.e. `1` for an <h1> tag. @returns {str} The value for the header tag's "id" attribute. Return None to not have an id attribute and to exclude this header from the TOC (if the "toc" extra is specified). """ header_id = _slugify(text) if prefix and isinstance(prefix, base_string_type): header_id = prefix + '-' + header_id if header_id in self._count_from_header_id: self._count_from_header_id[header_id] += 1 header_id += '-%s' % self._count_from_header_id[header_id] else: self._count_from_header_id[header_id] = 1 return header_id _toc = None def _toc_add_entry(self, level, id, name): if self._toc is None: self._toc = [] self._toc.append((level, id, self._unescape_special_chars(name))) _setext_h_re = re.compile(r'^(.+)[ \t]*\n(=+|-+)[ \t]*\n+', re.M) def _setext_h_sub(self, match): n = {"=": 1, "-": 2}[match.group(2)[0]] demote_headers = self.extras.get("demote-headers") if demote_headers: n = min(n + demote_headers, 6) header_id_attr = "" if "header-ids" in self.extras: header_id = self.header_id_from_text(match.group(1), self.extras["header-ids"], n) if header_id: header_id_attr = ' id="%s"' % header_id html = self._run_span_gamut(match.group(1)) if "toc" in self.extras and header_id: self._toc_add_entry(n, header_id, html) return "<h%d%s>%s</h%d>\n\n" % (n, header_id_attr, html, n) _atx_h_re = re.compile(r''' ^(\#{1,6}) # \1 = string of #'s [ \t]+ (.+?) # \2 = Header text [ \t]* (?<!\\) # ensure not an escaped trailing '#' \#* # optional closing #'s (not counted) \n+ ''', re.X | re.M) def _atx_h_sub(self, match): n = len(match.group(1)) demote_headers = self.extras.get("demote-headers") if demote_headers: n = min(n + demote_headers, 6) header_id_attr = "" if "header-ids" in self.extras: header_id = self.header_id_from_text(match.group(2), self.extras["header-ids"], n) if header_id: header_id_attr = ' id="%s"' % header_id html = self._run_span_gamut(match.group(2)) if "toc" in self.extras and header_id: self._toc_add_entry(n, header_id, html) return "<h%d%s>%s</h%d>\n\n" % (n, header_id_attr, html, n) def _do_headers(self, text): # Setext-style headers: # Header 1 # ======== # # Header 2 # -------- text = self._setext_h_re.sub(self._setext_h_sub, text) # atx-style headers: # # Header 1 # ## Header 2 # ## Header 2 with closing hashes ## # ... # ###### Header 6 text = self._atx_h_re.sub(self._atx_h_sub, text) return text _marker_ul_chars = '*+-' _marker_any = r'(?:[%s]|\d+\.)' % _marker_ul_chars _marker_ul = '(?:[%s])' % _marker_ul_chars _marker_ol = r'(?:\d+\.)' def _list_sub(self, match): lst = match.group(1) lst_type = match.group(3) in self._marker_ul_chars and "ul" or "ol" result = self._process_list_items(lst) if self.list_level: return "<%s>\n%s</%s>\n" % (lst_type, result, lst_type) else: return "<%s>\n%s</%s>\n\n" % (lst_type, result, lst_type) def _do_lists(self, text): # Form HTML ordered (numbered) and unordered (bulleted) lists. # Iterate over each *non-overlapping* list match. pos = 0 while True: # Find the *first* hit for either list style (ul or ol). We # match ul and ol separately to avoid adjacent lists of different # types running into each other (see issue #16). hits = [] for marker_pat in (self._marker_ul, self._marker_ol): less_than_tab = self.tab_width - 1 whole_list = r''' ( # \1 = whole list ( # \2 [ ]{0,%d} (%s) # \3 = first list item marker [ \t]+ (?!\ *\3\ ) # '- - - ...' isn't a list. See 'not_quite_a_list' test case. ) (?:.+?) ( # \4 \Z | \n{2,} (?=\S) (?! # Negative lookahead for another list item marker [ \t]* %s[ \t]+ ) ) ) ''' % (less_than_tab, marker_pat, marker_pat) if self.list_level: # sub-list list_re = re.compile("^"+whole_list, re.X | re.M | re.S) else: list_re = re.compile(r"(?:(?<=\n\n)|\A\n?)"+whole_list, re.X | re.M | re.S) match = list_re.search(text, pos) if match: hits.append((match.start(), match)) if not hits: break hits.sort() match = hits[0][1] start, end = match.span() text = text[:start] + self._list_sub(match) + text[end:] pos = end return text _list_item_re = re.compile(r''' (\n)? # leading line = \1 (^[ \t]*) # leading whitespace = \2 (?P<marker>%s) [ \t]+ # list marker = \3 ((?:.+?) # list item text = \4 (\n{1,2})) # eols = \5 (?= \n* (\Z | \2 (?P<next_marker>%s) [ \t]+)) ''' % (_marker_any, _marker_any), re.M | re.X | re.S) _last_li_endswith_two_eols = False def _list_item_sub(self, match): item = match.group(4) leading_line = match.group(1) leading_space = match.group(2) if leading_line or "\n\n" in item or self._last_li_endswith_two_eols: item = self._run_block_gamut(self._outdent(item)) else: # Recursion for sub-lists: item = self._do_lists(self._outdent(item)) if item.endswith('\n'): item = item[:-1] item = self._run_span_gamut(item) self._last_li_endswith_two_eols = (len(match.group(5)) == 2) return "<li>%s</li>\n" % item def _process_list_items(self, list_str): # Process the contents of a single ordered or unordered list, # splitting it into individual list items. # The $g_list_level global keeps track of when we're inside a list. # Each time we enter a list, we increment it; when we leave a list, # we decrement. If it's zero, we're not in a list anymore. # # We do this because when we're not inside a list, we want to treat # something like this: # # I recommend upgrading to version # 8. Oops, now this line is treated # as a sub-list. # # As a single paragraph, despite the fact that the second line starts # with a digit-period-space sequence. # # Whereas when we're inside a list (or sub-list), that line will be # treated as the start of a sub-list. What a kludge, huh? This is # an aspect of Markdown's syntax that's hard to parse perfectly # without resorting to mind-reading. Perhaps the solution is to # change the syntax rules such that sub-lists must start with a # starting cardinal number; e.g. "1." or "a.". self.list_level += 1 self._last_li_endswith_two_eols = False list_str = list_str.rstrip('\n') + '\n' list_str = self._list_item_re.sub(self._list_item_sub, list_str) self.list_level -= 1 return list_str def _get_pygments_lexer(self, lexer_name): try: from pygments import lexers, util except ImportError: return None try: return lexers.get_lexer_by_name(lexer_name) except util.ClassNotFound: return None def _color_with_pygments(self, codeblock, lexer, **formatter_opts): import pygments import pygments.formatters class HtmlCodeFormatter(pygments.formatters.HtmlFormatter): def _wrap_code(self, inner): """A function for use in a Pygments Formatter which wraps in <code> tags. """ yield 0, "<code>" for tup in inner: yield tup yield 0, "</code>" def wrap(self, source, outfile): """Return the source with a code, pre, and div.""" return self._wrap_div(self._wrap_pre(self._wrap_code(source))) formatter_opts.setdefault("cssclass", "codehilite") formatter = HtmlCodeFormatter(**formatter_opts) return pygments.highlight(codeblock, lexer, formatter) def _code_block_sub(self, match, is_fenced_code_block=False): lexer_name = None if is_fenced_code_block: lexer_name = match.group(1) if lexer_name: formatter_opts = self.extras['fenced-code-blocks'] or {} codeblock = match.group(2) codeblock = codeblock[:-1] # drop one trailing newline else: codeblock = match.group(1) codeblock = self._outdent(codeblock) codeblock = self._detab(codeblock) codeblock = codeblock.lstrip('\n') # trim leading newlines codeblock = codeblock.rstrip() # trim trailing whitespace # Note: "code-color" extra is DEPRECATED. if "code-color" in self.extras and codeblock.startswith(":::"): lexer_name, rest = codeblock.split('\n', 1) lexer_name = lexer_name[3:].strip() codeblock = rest.lstrip("\n") # Remove lexer declaration line. formatter_opts = self.extras['code-color'] or {} if lexer_name: lexer = self._get_pygments_lexer(lexer_name) if lexer: colored = self._color_with_pygments(codeblock, lexer, **formatter_opts) return "\n\n%s\n\n" % colored codeblock = self._encode_code(codeblock) pre_class_str = self._html_class_str_from_tag("pre") code_class_str = self._html_class_str_from_tag("code") return "\n\n<pre%s><code%s>%s\n</code></pre>\n\n" % ( pre_class_str, code_class_str, codeblock) def _html_class_str_from_tag(self, tag): """Get the appropriate ' class="..."' string (note the leading space), if any, for the given tag. """ if "html-classes" not in self.extras: return "" try: html_classes_from_tag = self.extras["html-classes"] except TypeError: return "" else: if tag in html_classes_from_tag: return ' class="%s"' % html_classes_from_tag[tag] return "" def _do_code_blocks(self, text): """Process Markdown `<pre><code>` blocks.""" code_block_re = re.compile(r''' (?:\n\n|\A\n?) ( # $1 = the code block -- one or more lines, starting with a space/tab (?: (?:[ ]{%d} | \t) # Lines must start with a tab or a tab-width of spaces .*\n+ )+ ) ((?=^[ ]{0,%d}\S)|\Z) # Lookahead for non-space at line-start, or end of doc ''' % (self.tab_width, self.tab_width), re.M | re.X) return code_block_re.sub(self._code_block_sub, text) _fenced_code_block_re = re.compile(r''' (?:\n\n|\A\n?) ^```([\w+-]+)?[ \t]*\n # opening fence, $1 = optional lang (.*?) # $2 = code block content ^```[ \t]*\n # closing fence ''', re.M | re.X | re.S) def _fenced_code_block_sub(self, match): return self._code_block_sub(match, is_fenced_code_block=True); def _do_fenced_code_blocks(self, text): """Process ```-fenced unindented code blocks ('fenced-code-blocks' extra).""" return self._fenced_code_block_re.sub(self._fenced_code_block_sub, text) # Rules for a code span: # - backslash escapes are not interpreted in a code span # - to include one or or a run of more backticks the delimiters must # be a longer run of backticks # - cannot start or end a code span with a backtick; pad with a # space and that space will be removed in the emitted HTML # See `test/tm-cases/escapes.text` for a number of edge-case # examples. _code_span_re = re.compile(r''' (?<!\\) (`+) # \1 = Opening run of ` (?!`) # See Note A test/tm-cases/escapes.text (.+?) # \2 = The code block (?<!`) \1 # Matching closer (?!`) ''', re.X | re.S) def _code_span_sub(self, match): c = match.group(2).strip(" \t") c = self._encode_code(c) return "<code>%s</code>" % c def _do_code_spans(self, text): # * Backtick quotes are used for <code></code> spans. # # * You can use multiple backticks as the delimiters if you want to # include literal backticks in the code span. So, this input: # # Just type ``foo `bar` baz`` at the prompt. # # Will translate to: # # <p>Just type <code>foo `bar` baz</code> at the prompt.</p> # # There's no arbitrary limit to the number of backticks you # can use as delimters. If you need three consecutive backticks # in your code, use four for delimiters, etc. # # * You can use spaces to get literal backticks at the edges: # # ... type `` `bar` `` ... # # Turns to: # # ... type <code>`bar`</code> ... return self._code_span_re.sub(self._code_span_sub, text) def _encode_code(self, text): """Encode/escape certain characters inside Markdown code runs. The point is that in code, these characters are literals, and lose their special Markdown meanings. """ replacements = [ # Encode all ampersands; HTML entities are not # entities within a Markdown code span. ('&', '&amp;'), # Do the angle bracket song and dance: ('<', '&lt;'), ('>', '&gt;'), ] for before, after in replacements: text = text.replace(before, after) hashed = _hash_text(text) self._escape_table[text] = hashed return hashed _strong_re = re.compile(r"(\*\*|__)(?=\S)(.+?[*_]*)(?<=\S)\1", re.S) _em_re = re.compile(r"(\*|_)(?=\S)(.+?)(?<=\S)\1", re.S) _code_friendly_strong_re = re.compile(r"\*\*(?=\S)(.+?[*_]*)(?<=\S)\*\*", re.S) _code_friendly_em_re = re.compile(r"\*(?=\S)(.+?)(?<=\S)\*", re.S) def _do_italics_and_bold(self, text): # <strong> must go first: if "code-friendly" in self.extras: text = self._code_friendly_strong_re.sub(r"<strong>\1</strong>", text) text = self._code_friendly_em_re.sub(r"<em>\1</em>", text) else: text = self._strong_re.sub(r"<strong>\2</strong>", text) text = self._em_re.sub(r"<em>\2</em>", text) return text # "smarty-pants" extra: Very liberal in interpreting a single prime as an # apostrophe; e.g. ignores the fact that "round", "bout", "twer", and # "twixt" can be written without an initial apostrophe. This is fine because # using scare quotes (single quotation marks) is rare. _apostrophe_year_re = re.compile(r"'(\d\d)(?=(\s|,|;|\.|\?|!|$))") _contractions = ["tis", "twas", "twer", "neath", "o", "n", "round", "bout", "twixt", "nuff", "fraid", "sup"] def _do_smart_contractions(self, text): text = self._apostrophe_year_re.sub(r"&#8217;\1", text) for c in self._contractions: text = text.replace("'%s" % c, "&#8217;%s" % c) text = text.replace("'%s" % c.capitalize(), "&#8217;%s" % c.capitalize()) return text # Substitute double-quotes before single-quotes. _opening_single_quote_re = re.compile(r"(?<!\S)'(?=\S)") _opening_double_quote_re = re.compile(r'(?<!\S)"(?=\S)') _closing_single_quote_re = re.compile(r"(?<=\S)'") _closing_double_quote_re = re.compile(r'(?<=\S)"(?=(\s|,|;|\.|\?|!|$))') def _do_smart_punctuation(self, text): """Fancifies 'single quotes', "double quotes", and apostrophes. Converts --, ---, and ... into en dashes, em dashes, and ellipses. Inspiration is: <http://daringfireball.net/projects/smartypants/> See "test/tm-cases/smarty_pants.text" for a full discussion of the support here and <http://code.google.com/p/python-markdown2/issues/detail?id=42> for a discussion of some diversion from the original SmartyPants. """ if "'" in text: # guard for perf text = self._do_smart_contractions(text) text = self._opening_single_quote_re.sub("&#8216;", text) text = self._closing_single_quote_re.sub("&#8217;", text) if '"' in text: # guard for perf text = self._opening_double_quote_re.sub("&#8220;", text) text = self._closing_double_quote_re.sub("&#8221;", text) text = text.replace("---", "&#8212;") text = text.replace("--", "&#8211;") text = text.replace("...", "&#8230;") text = text.replace(" . . . ", "&#8230;") text = text.replace(". . .", "&#8230;") return text _block_quote_re = re.compile(r''' ( # Wrap whole match in \1 ( ^[ \t]*>[ \t]? # '>' at the start of a line .+\n # rest of the first line (.+\n)* # subsequent consecutive lines \n* # blanks )+ ) ''', re.M | re.X) _bq_one_level_re = re.compile('^[ \t]*>[ \t]?', re.M); _html_pre_block_re = re.compile(r'(\s*<pre>.+?</pre>)', re.S) def _dedent_two_spaces_sub(self, match): return re.sub(r'(?m)^ ', '', match.group(1)) def _block_quote_sub(self, match): bq = match.group(1) bq = self._bq_one_level_re.sub('', bq) # trim one level of quoting bq = self._ws_only_line_re.sub('', bq) # trim whitespace-only lines bq = self._run_block_gamut(bq) # recurse bq = re.sub('(?m)^', ' ', bq) # These leading spaces screw with <pre> content, so we need to fix that: bq = self._html_pre_block_re.sub(self._dedent_two_spaces_sub, bq) return "<blockquote>\n%s\n</blockquote>\n\n" % bq def _do_block_quotes(self, text): if '>' not in text: return text return self._block_quote_re.sub(self._block_quote_sub, text) def _form_paragraphs(self, text): # Strip leading and trailing lines: text = text.strip('\n') # Wrap <p> tags. grafs = [] for i, graf in enumerate(re.split(r"\n{2,}", text)): if graf in self.html_blocks: # Unhashify HTML blocks grafs.append(self.html_blocks[graf]) else: cuddled_list = None if "cuddled-lists" in self.extras: # Need to put back trailing '\n' for `_list_item_re` # match at the end of the paragraph. li = self._list_item_re.search(graf + '\n') # Two of the same list marker in this paragraph: a likely # candidate for a list cuddled to preceding paragraph # text (issue 33). Note the `[-1]` is a quick way to # consider numeric bullets (e.g. "1." and "2.") to be # equal. if (li and len(li.group(2)) <= 3 and li.group("next_marker") and li.group("marker")[-1] == li.group("next_marker")[-1]): start = li.start() cuddled_list = self._do_lists(graf[start:]).rstrip("\n") assert cuddled_list.startswith("<ul>") or cuddled_list.startswith("<ol>") graf = graf[:start] # Wrap <p> tags. graf = self._run_span_gamut(graf) grafs.append("<p>" + graf.lstrip(" \t") + "</p>") if cuddled_list: grafs.append(cuddled_list) return "\n\n".join(grafs) def _add_footnotes(self, text): if self.footnotes: footer = [ '<div class="footnotes">', '<hr' + self.empty_element_suffix, '<ol>', ] for i, id in enumerate(self.footnote_ids): if i != 0: footer.append('') footer.append('<li id="fn-%s">' % id) footer.append(self._run_block_gamut(self.footnotes[id])) backlink = ('<a href="#fnref-%s" ' 'class="footnoteBackLink" ' 'title="Jump back to footnote %d in the text.">' '&#8617;</a>' % (id, i+1)) if footer[-1].endswith("</p>"): footer[-1] = footer[-1][:-len("</p>")] \ + '&nbsp;' + backlink + "</p>" else: footer.append("\n<p>%s</p>" % backlink) footer.append('</li>') footer.append('</ol>') footer.append('</div>') return text + '\n\n' + '\n'.join(footer) else: return text # Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin: # http://bumppo.net/projects/amputator/ _ampersand_re = re.compile(r'&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)') _naked_lt_re = re.compile(r'<(?![a-z/?\$!])', re.I) _naked_gt_re = re.compile(r'''(?<![a-z0-9?!/'"-])>''', re.I) def _encode_amps_and_angles(self, text): # Smart processing for ampersands and angle brackets that need # to be encoded. text = self._ampersand_re.sub('&amp;', text) # Encode naked <'s text = self._naked_lt_re.sub('&lt;', text) # Encode naked >'s # Note: Other markdown implementations (e.g. Markdown.pl, PHP # Markdown) don't do this. text = self._naked_gt_re.sub('&gt;', text) return text def _encode_backslash_escapes(self, text): for ch, escape in list(self._escape_table.items()): text = text.replace("\\"+ch, escape) return text _auto_link_re = re.compile(r'<((https?|ftp):[^\'">\s]+)>', re.I) def _auto_link_sub(self, match): g1 = match.group(1) return '<a href="%s">%s</a>' % (g1, g1) _auto_email_link_re = re.compile(r""" < (?:mailto:)? ( [-.\w]+ \@ [-\w]+(\.[-\w]+)*\.[a-z]+ ) > """, re.I | re.X | re.U) def _auto_email_link_sub(self, match): return self._encode_email_address( self._unescape_special_chars(match.group(1))) def _do_auto_links(self, text): text = self._auto_link_re.sub(self._auto_link_sub, text) text = self._auto_email_link_re.sub(self._auto_email_link_sub, text) return text def _encode_email_address(self, addr): # Input: an email address, e.g. "foo@example.com" # # Output: the email address as a mailto link, with each character # of the address encoded as either a decimal or hex entity, in # the hopes of foiling most address harvesting spam bots. E.g.: # # <a href="&#x6D;&#97;&#105;&#108;&#x74;&#111;:&#102;&#111;&#111;&#64;&#101; # x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;">&#102;&#111;&#111; # &#64;&#101;x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;</a> # # Based on a filter by Matthew Wickline, posted to the BBEdit-Talk # mailing list: <http://tinyurl.com/yu7ue> chars = [_xml_encode_email_char_at_random(ch) for ch in "mailto:" + addr] # Strip the mailto: from the visible part. addr = '<a href="%s">%s</a>' \ % (''.join(chars), ''.join(chars[7:])) return addr def _do_link_patterns(self, text): """Caveat emptor: there isn't much guarding against link patterns being formed inside other standard Markdown links, e.g. inside a [link def][like this]. Dev Notes: *Could* consider prefixing regexes with a negative lookbehind assertion to attempt to guard against this. """ link_from_hash = {} for regex, repl in self.link_patterns: replacements = [] for match in regex.finditer(text): if hasattr(repl, "__call__"): href = repl(match) else: href = match.expand(repl) replacements.append((match.span(), href)) for (start, end), href in reversed(replacements): escaped_href = ( href.replace('"', '&quot;') # b/c of attr quote # To avoid markdown <em> and <strong>: .replace('*', self._escape_table['*']) .replace('_', self._escape_table['_'])) link = '<a href="%s">%s</a>' % (escaped_href, text[start:end]) hash = _hash_text(link) link_from_hash[hash] = link text = text[:start] + hash + text[end:] for hash, link in list(link_from_hash.items()): text = text.replace(hash, link) return text def _unescape_special_chars(self, text): # Swap back in all the special characters we've hidden. for ch, hash in list(self._escape_table.items()): text = text.replace(hash, ch) return text def _outdent(self, text): # Remove one level of line-leading tabs or spaces return self._outdent_re.sub('', text) class MarkdownWithExtras(Markdown): """A markdowner class that enables most extras: - footnotes - code-color (only has effect if 'pygments' Python module on path) These are not included: - pyshell (specific to Python-related documenting) - code-friendly (because it *disables* part of the syntax) - link-patterns (because you need to specify some actual link-patterns anyway) """ extras = ["footnotes", "code-color"] #---- internal support functions class UnicodeWithAttrs(unicode): """A subclass of unicode used for the return value of conversion to possibly attach some attributes. E.g. the "toc_html" attribute when the "toc" extra is used. """ metadata = None _toc = None def toc_html(self): """Return the HTML for the current TOC. This expects the `_toc` attribute to have been set on this instance. """ if self._toc is None: return None def indent(): return ' ' * (len(h_stack) - 1) lines = [] h_stack = [0] # stack of header-level numbers for level, id, name in self._toc: if level > h_stack[-1]: lines.append("%s<ul>" % indent()) h_stack.append(level) elif level == h_stack[-1]: lines[-1] += "</li>" else: while level < h_stack[-1]: h_stack.pop() if not lines[-1].endswith("</li>"): lines[-1] += "</li>" lines.append("%s</ul></li>" % indent()) lines.append('%s<li><a href="#%s">%s</a>' % ( indent(), id, name)) while len(h_stack) > 1: h_stack.pop() if not lines[-1].endswith("</li>"): lines[-1] += "</li>" lines.append("%s</ul>" % indent()) return '\n'.join(lines) + '\n' toc_html = property(toc_html) ## {{{ http://code.activestate.com/recipes/577257/ (r1) import re char_map = {u'À': 'A', u'Á': 'A', u'Â': 'A', u'Ã': 'A', u'Ä': 'Ae', u'Å': 'A', u'Æ': 'A', u'Ā': 'A', u'Ą': 'A', u'Ă': 'A', u'Ç': 'C', u'Ć': 'C', u'Č': 'C', u'Ĉ': 'C', u'Ċ': 'C', u'Ď': 'D', u'Đ': 'D', u'È': 'E', u'É': 'E', u'Ê': 'E', u'Ë': 'E', u'Ē': 'E', u'Ę': 'E', u'Ě': 'E', u'Ĕ': 'E', u'Ė': 'E', u'Ĝ': 'G', u'Ğ': 'G', u'Ġ': 'G', u'Ģ': 'G', u'Ĥ': 'H', u'Ħ': 'H', u'Ì': 'I', u'Í': 'I', u'Î': 'I', u'Ï': 'I', u'Ī': 'I', u'Ĩ': 'I', u'Ĭ': 'I', u'Į': 'I', u'İ': 'I', u'IJ': 'IJ', u'Ĵ': 'J', u'Ķ': 'K', u'Ľ': 'K', u'Ĺ': 'K', u'Ļ': 'K', u'Ŀ': 'K', u'Ł': 'L', u'Ñ': 'N', u'Ń': 'N', u'Ň': 'N', u'Ņ': 'N', u'Ŋ': 'N', u'Ò': 'O', u'Ó': 'O', u'Ô': 'O', u'Õ': 'O', u'Ö': 'Oe', u'Ø': 'O', u'Ō': 'O', u'Ő': 'O', u'Ŏ': 'O', u'Œ': 'OE', u'Ŕ': 'R', u'Ř': 'R', u'Ŗ': 'R', u'Ś': 'S', u'Ş': 'S', u'Ŝ': 'S', u'Ș': 'S', u'Š': 'S', u'Ť': 'T', u'Ţ': 'T', u'Ŧ': 'T', u'Ț': 'T', u'Ù': 'U', u'Ú': 'U', u'Û': 'U', u'Ü': 'Ue', u'Ū': 'U', u'Ů': 'U', u'Ű': 'U', u'Ŭ': 'U', u'Ũ': 'U', u'Ų': 'U', u'Ŵ': 'W', u'Ŷ': 'Y', u'Ÿ': 'Y', u'Ý': 'Y', u'Ź': 'Z', u'Ż': 'Z', u'Ž': 'Z', u'à': 'a', u'á': 'a', u'â': 'a', u'ã': 'a', u'ä': 'ae', u'ā': 'a', u'ą': 'a', u'ă': 'a', u'å': 'a', u'æ': 'ae', u'ç': 'c', u'ć': 'c', u'č': 'c', u'ĉ': 'c', u'ċ': 'c', u'ď': 'd', u'đ': 'd', u'è': 'e', u'é': 'e', u'ê': 'e', u'ë': 'e', u'ē': 'e', u'ę': 'e', u'ě': 'e', u'ĕ': 'e', u'ė': 'e', u'ƒ': 'f', u'ĝ': 'g', u'ğ': 'g', u'ġ': 'g', u'ģ': 'g', u'ĥ': 'h', u'ħ': 'h', u'ì': 'i', u'í': 'i', u'î': 'i', u'ï': 'i', u'ī': 'i', u'ĩ': 'i', u'ĭ': 'i', u'į': 'i', u'ı': 'i', u'ij': 'ij', u'ĵ': 'j', u'ķ': 'k', u'ĸ': 'k', u'ł': 'l', u'ľ': 'l', u'ĺ': 'l', u'ļ': 'l', u'ŀ': 'l', u'ñ': 'n', u'ń': 'n', u'ň': 'n', u'ņ': 'n', u'ʼn': 'n', u'ŋ': 'n', u'ò': 'o', u'ó': 'o', u'ô': 'o', u'õ': 'o', u'ö': 'oe', u'ø': 'o', u'ō': 'o', u'ő': 'o', u'ŏ': 'o', u'œ': 'oe', u'ŕ': 'r', u'ř': 'r', u'ŗ': 'r', u'ś': 's', u'š': 's', u'ť': 't', u'ù': 'u', u'ú': 'u', u'û': 'u', u'ü': 'ue', u'ū': 'u', u'ů': 'u', u'ű': 'u', u'ŭ': 'u', u'ũ': 'u', u'ų': 'u', u'ŵ': 'w', u'ÿ': 'y', u'ý': 'y', u'ŷ': 'y', u'ż': 'z', u'ź': 'z', u'ž': 'z', u'ß': 'ss', u'ſ': 'ss', u'Α': 'A', u'Ά': 'A', u'Ἀ': 'A', u'Ἁ': 'A', u'Ἂ': 'A', u'Ἃ': 'A', u'Ἄ': 'A', u'Ἅ': 'A', u'Ἆ': 'A', u'Ἇ': 'A', u'ᾈ': 'A', u'ᾉ': 'A', u'ᾊ': 'A', u'ᾋ': 'A', u'ᾌ': 'A', u'ᾍ': 'A', u'ᾎ': 'A', u'ᾏ': 'A', u'Ᾰ': 'A', u'Ᾱ': 'A', u'Ὰ': 'A', u'Ά': 'A', u'ᾼ': 'A', u'Β': 'B', u'Γ': 'G', u'Δ': 'D', u'Ε': 'E', u'Έ': 'E', u'Ἐ': 'E', u'Ἑ': 'E', u'Ἒ': 'E', u'Ἓ': 'E', u'Ἔ': 'E', u'Ἕ': 'E', u'Έ': 'E', u'Ὲ': 'E', u'Ζ': 'Z', u'Η': 'I', u'Ή': 'I', u'Ἠ': 'I', u'Ἡ': 'I', u'Ἢ': 'I', u'Ἣ': 'I', u'Ἤ': 'I', u'Ἥ': 'I', u'Ἦ': 'I', u'Ἧ': 'I', u'ᾘ': 'I', u'ᾙ': 'I', u'ᾚ': 'I', u'ᾛ': 'I', u'ᾜ': 'I', u'ᾝ': 'I', u'ᾞ': 'I', u'ᾟ': 'I', u'Ὴ': 'I', u'Ή': 'I', u'ῌ': 'I', u'Θ': 'TH', u'Ι': 'I', u'Ί': 'I', u'Ϊ': 'I', u'Ἰ': 'I', u'Ἱ': 'I', u'Ἲ': 'I', u'Ἳ': 'I', u'Ἴ': 'I', u'Ἵ': 'I', u'Ἶ': 'I', u'Ἷ': 'I', u'Ῐ': 'I', u'Ῑ': 'I', u'Ὶ': 'I', u'Ί': 'I', u'Κ': 'K', u'Λ': 'L', u'Μ': 'M', u'Ν': 'N', u'Ξ': 'KS', u'Ο': 'O', u'Ό': 'O', u'Ὀ': 'O', u'Ὁ': 'O', u'Ὂ': 'O', u'Ὃ': 'O', u'Ὄ': 'O', u'Ὅ': 'O', u'Ὸ': 'O', u'Ό': 'O', u'Π': 'P', u'Ρ': 'R', u'Ῥ': 'R', u'Σ': 'S', u'Τ': 'T', u'Υ': 'Y', u'Ύ': 'Y', u'Ϋ': 'Y', u'Ὑ': 'Y', u'Ὓ': 'Y', u'Ὕ': 'Y', u'Ὗ': 'Y', u'Ῠ': 'Y', u'Ῡ': 'Y', u'Ὺ': 'Y', u'Ύ': 'Y', u'Φ': 'F', u'Χ': 'X', u'Ψ': 'PS', u'Ω': 'O', u'Ώ': 'O', u'Ὠ': 'O', u'Ὡ': 'O', u'Ὢ': 'O', u'Ὣ': 'O', u'Ὤ': 'O', u'Ὥ': 'O', u'Ὦ': 'O', u'Ὧ': 'O', u'ᾨ': 'O', u'ᾩ': 'O', u'ᾪ': 'O', u'ᾫ': 'O', u'ᾬ': 'O', u'ᾭ': 'O', u'ᾮ': 'O', u'ᾯ': 'O', u'Ὼ': 'O', u'Ώ': 'O', u'ῼ': 'O', u'α': 'a', u'ά': 'a', u'ἀ': 'a', u'ἁ': 'a', u'ἂ': 'a', u'ἃ': 'a', u'ἄ': 'a', u'ἅ': 'a', u'ἆ': 'a', u'ἇ': 'a', u'ᾀ': 'a', u'ᾁ': 'a', u'ᾂ': 'a', u'ᾃ': 'a', u'ᾄ': 'a', u'ᾅ': 'a', u'ᾆ': 'a', u'ᾇ': 'a', u'ὰ': 'a', u'ά': 'a', u'ᾰ': 'a', u'ᾱ': 'a', u'ᾲ': 'a', u'ᾳ': 'a', u'ᾴ': 'a', u'ᾶ': 'a', u'ᾷ': 'a', u'β': 'b', u'γ': 'g', u'δ': 'd', u'ε': 'e', u'έ': 'e', u'ἐ': 'e', u'ἑ': 'e', u'ἒ': 'e', u'ἓ': 'e', u'ἔ': 'e', u'ἕ': 'e', u'ὲ': 'e', u'έ': 'e', u'ζ': 'z', u'η': 'i', u'ή': 'i', u'ἠ': 'i', u'ἡ': 'i', u'ἢ': 'i', u'ἣ': 'i', u'ἤ': 'i', u'ἥ': 'i', u'ἦ': 'i', u'ἧ': 'i', u'ᾐ': 'i', u'ᾑ': 'i', u'ᾒ': 'i', u'ᾓ': 'i', u'ᾔ': 'i', u'ᾕ': 'i', u'ᾖ': 'i', u'ᾗ': 'i', u'ὴ': 'i', u'ή': 'i', u'ῂ': 'i', u'ῃ': 'i', u'ῄ': 'i', u'ῆ': 'i', u'ῇ': 'i', u'θ': 'th', u'ι': 'i', u'ί': 'i', u'ϊ': 'i', u'ΐ': 'i', u'ἰ': 'i', u'ἱ': 'i', u'ἲ': 'i', u'ἳ': 'i', u'ἴ': 'i', u'ἵ': 'i', u'ἶ': 'i', u'ἷ': 'i', u'ὶ': 'i', u'ί': 'i', u'ῐ': 'i', u'ῑ': 'i', u'ῒ': 'i', u'ΐ': 'i', u'ῖ': 'i', u'ῗ': 'i', u'κ': 'k', u'λ': 'l', u'μ': 'm', u'ν': 'n', u'ξ': 'ks', u'ο': 'o', u'ό': 'o', u'ὀ': 'o', u'ὁ': 'o', u'ὂ': 'o', u'ὃ': 'o', u'ὄ': 'o', u'ὅ': 'o', u'ὸ': 'o', u'ό': 'o', u'π': 'p', u'ρ': 'r', u'ῤ': 'r', u'ῥ': 'r', u'σ': 's', u'ς': 's', u'τ': 't', u'υ': 'y', u'ύ': 'y', u'ϋ': 'y', u'ΰ': 'y', u'ὐ': 'y', u'ὑ': 'y', u'ὒ': 'y', u'ὓ': 'y', u'ὔ': 'y', u'ὕ': 'y', u'ὖ': 'y', u'ὗ': 'y', u'ὺ': 'y', u'ύ': 'y', u'ῠ': 'y', u'ῡ': 'y', u'ῢ': 'y', u'ΰ': 'y', u'ῦ': 'y', u'ῧ': 'y', u'φ': 'f', u'χ': 'x', u'ψ': 'ps', u'ω': 'o', u'ώ': 'o', u'ὠ': 'o', u'ὡ': 'o', u'ὢ': 'o', u'ὣ': 'o', u'ὤ': 'o', u'ὥ': 'o', u'ὦ': 'o', u'ὧ': 'o', u'ᾠ': 'o', u'ᾡ': 'o', u'ᾢ': 'o', u'ᾣ': 'o', u'ᾤ': 'o', u'ᾥ': 'o', u'ᾦ': 'o', u'ᾧ': 'o', u'ὼ': 'o', u'ώ': 'o', u'ῲ': 'o', u'ῳ': 'o', u'ῴ': 'o', u'ῶ': 'o', u'ῷ': 'o', u'¨': '', u'΅': '', u'᾿': '', u'῾': '', u'῍': '', u'῝': '', u'῎': '', u'῞': '', u'῏': '', u'῟': '', u'῀': '', u'῁': '', u'΄': '', u'΅': '', u'`': '', u'῭': '', u'ͺ': '', u'᾽': '', u'А': 'A', u'Б': 'B', u'В': 'V', u'Г': 'G', u'Д': 'D', u'Е': 'E', u'Ё': 'YO', u'Ж': 'ZH', u'З': 'Z', u'И': 'I', u'Й': 'J', u'К': 'K', u'Л': 'L', u'М': 'M', u'Н': 'N', u'О': 'O', u'П': 'P', u'Р': 'R', u'С': 'S', u'Т': 'T', u'У': 'U', u'Ф': 'F', u'Х': 'H', u'Ц': 'TS', u'Ч': 'CH', u'Ш': 'SH', u'Щ': 'SCH', u'Ы': 'YI', u'Э': 'E', u'Ю': 'YU', u'Я': 'YA', u'а': 'A', u'б': 'B', u'в': 'V', u'г': 'G', u'д': 'D', u'е': 'E', u'ё': 'YO', u'ж': 'ZH', u'з': 'Z', u'и': 'I', u'й': 'J', u'к': 'K', u'л': 'L', u'м': 'M', u'н': 'N', u'о': 'O', u'п': 'P', u'р': 'R', u'с': 'S', u'т': 'T', u'у': 'U', u'ф': 'F', u'х': 'H', u'ц': 'TS', u'ч': 'CH', u'ш': 'SH', u'щ': 'SCH', u'ы': 'YI', u'э': 'E', u'ю': 'YU', u'я': 'YA', u'Ъ': '', u'ъ': '', u'Ь': '', u'ь': '', u'ð': 'd', u'Ð': 'D', u'þ': 'th', u'Þ': 'TH',u'ა': 'a', u'ბ': 'b', u'გ': 'g', u'დ': 'd', u'ე': 'e', u'ვ': 'v', u'ზ': 'z', u'თ': 't', u'ი': 'i', u'კ': 'k', u'ლ': 'l', u'მ': 'm', u'ნ': 'n', u'ო': 'o', u'პ': 'p', u'ჟ': 'zh', u'რ': 'r', u'ს': 's', u'ტ': 't', u'უ': 'u', u'ფ': 'p', u'ქ': 'k', u'ღ': 'gh', u'ყ': 'q', u'შ': 'sh', u'ჩ': 'ch', u'ც': 'ts', u'ძ': 'dz', u'წ': 'ts', u'ჭ': 'ch', u'ხ': 'kh', u'ჯ': 'j', u'ჰ': 'h' } def replace_char(m): char = m.group() if char_map.has_key(char): return char_map[char] else: return char _punct_re = re.compile(r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.]+') def _slugify(text, delim=u'-'): """Generates an ASCII-only slug.""" result = [] for word in _punct_re.split(text.lower()): word = word.encode('utf-8') if word: result.append(word) slugified = delim.join([i.decode('utf-8') for i in result]) return re.sub('[^a-zA-Z0-9\\s\\-]{1}', replace_char, slugified).lower() ## end of http://code.activestate.com/recipes/577257/ }}} # From http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52549 def _curry(*args, **kwargs): function, args = args[0], args[1:] def result(*rest, **kwrest): combined = kwargs.copy() combined.update(kwrest) return function(*args + rest, **combined) return result # Recipe: regex_from_encoded_pattern (1.0) def _regex_from_encoded_pattern(s): """'foo' -> re.compile(re.escape('foo')) '/foo/' -> re.compile('foo') '/foo/i' -> re.compile('foo', re.I) """ if s.startswith('/') and s.rfind('/') != 0: # Parse it: /PATTERN/FLAGS idx = s.rfind('/') pattern, flags_str = s[1:idx], s[idx+1:] flag_from_char = { "i": re.IGNORECASE, "l": re.LOCALE, "s": re.DOTALL, "m": re.MULTILINE, "u": re.UNICODE, } flags = 0 for char in flags_str: try: flags |= flag_from_char[char] except KeyError: raise ValueError("unsupported regex flag: '%s' in '%s' " "(must be one of '%s')" % (char, s, ''.join(list(flag_from_char.keys())))) return re.compile(s[1:idx], flags) else: # not an encoded regex return re.compile(re.escape(s)) # Recipe: dedent (0.1.2) def _dedentlines(lines, tabsize=8, skip_first_line=False): """_dedentlines(lines, tabsize=8, skip_first_line=False) -> dedented lines "lines" is a list of lines to dedent. "tabsize" is the tab width to use for indent width calculations. "skip_first_line" is a boolean indicating if the first line should be skipped for calculating the indent width and for dedenting. This is sometimes useful for docstrings and similar. Same as dedent() except operates on a sequence of lines. Note: the lines list is modified **in-place**. """ DEBUG = False if DEBUG: print("dedent: dedent(..., tabsize=%d, skip_first_line=%r)"\ % (tabsize, skip_first_line)) indents = [] margin = None for i, line in enumerate(lines): if i == 0 and skip_first_line: continue indent = 0 for ch in line: if ch == ' ': indent += 1 elif ch == '\t': indent += tabsize - (indent % tabsize) elif ch in '\r\n': continue # skip all-whitespace lines else: break else: continue # skip all-whitespace lines if DEBUG: print("dedent: indent=%d: %r" % (indent, line)) if margin is None: margin = indent else: margin = min(margin, indent) if DEBUG: print("dedent: margin=%r" % margin) if margin is not None and margin > 0: for i, line in enumerate(lines): if i == 0 and skip_first_line: continue removed = 0 for j, ch in enumerate(line): if ch == ' ': removed += 1 elif ch == '\t': removed += tabsize - (removed % tabsize) elif ch in '\r\n': if DEBUG: print("dedent: %r: EOL -> strip up to EOL" % line) lines[i] = lines[i][j:] break else: raise ValueError("unexpected non-whitespace char %r in " "line %r while removing %d-space margin" % (ch, line, margin)) if DEBUG: print("dedent: %r: %r -> removed %d/%d"\ % (line, ch, removed, margin)) if removed == margin: lines[i] = lines[i][j+1:] break elif removed > margin: lines[i] = ' '*(removed-margin) + lines[i][j+1:] break else: if removed: lines[i] = lines[i][removed:] return lines def _dedent(text, tabsize=8, skip_first_line=False): """_dedent(text, tabsize=8, skip_first_line=False) -> dedented text "text" is the text to dedent. "tabsize" is the tab width to use for indent width calculations. "skip_first_line" is a boolean indicating if the first line should be skipped for calculating the indent width and for dedenting. This is sometimes useful for docstrings and similar. textwrap.dedent(s), but don't expand tabs to spaces """ lines = text.splitlines(1) _dedentlines(lines, tabsize=tabsize, skip_first_line=skip_first_line) return ''.join(lines) class _memoized(object): """Decorator that caches a function's return value each time it is called. If called later with the same arguments, the cached value is returned, and not re-evaluated. http://wiki.python.org/moin/PythonDecoratorLibrary """ def __init__(self, func): self.func = func self.cache = {} def __call__(self, *args): try: return self.cache[args] except KeyError: self.cache[args] = value = self.func(*args) return value except TypeError: # uncachable -- for instance, passing a list as an argument. # Better to not cache than to blow up entirely. return self.func(*args) def __repr__(self): """Return the function's docstring.""" return self.func.__doc__ def _xml_oneliner_re_from_tab_width(tab_width): """Standalone XML processing instruction regex.""" return re.compile(r""" (?: (?<=\n\n) # Starting after a blank line | # or \A\n? # the beginning of the doc ) ( # save in $1 [ ]{0,%d} (?: <\?\w+\b\s+.*?\?> # XML processing instruction | <\w+:\w+\b\s+.*?/> # namespaced single tag ) [ \t]* (?=\n{2,}|\Z) # followed by a blank line or end of document ) """ % (tab_width - 1), re.X) _xml_oneliner_re_from_tab_width = _memoized(_xml_oneliner_re_from_tab_width) def _hr_tag_re_from_tab_width(tab_width): return re.compile(r""" (?: (?<=\n\n) # Starting after a blank line | # or \A\n? # the beginning of the doc ) ( # save in \1 [ ]{0,%d} <(hr) # start tag = \2 \b # word break ([^<>])*? # /?> # the matching end tag [ \t]* (?=\n{2,}|\Z) # followed by a blank line or end of document ) """ % (tab_width - 1), re.X) _hr_tag_re_from_tab_width = _memoized(_hr_tag_re_from_tab_width) def _xml_encode_email_char_at_random(ch): r = random() # Roughly 10% raw, 45% hex, 45% dec. # '@' *must* be encoded. I [John Gruber] insist. # Issue 26: '_' must be encoded. if r > 0.9 and ch not in "@_": return ch elif r < 0.45: # The [1:] is to drop leading '0': 0x63 -> x63 return '&#%s;' % hex(ord(ch))[1:] else: return '&#%s;' % ord(ch) #---- mainline class _NoReflowFormatter(optparse.IndentedHelpFormatter): """An optparse formatter that does NOT reflow the description.""" def format_description(self, description): return description or "" def _test(): import doctest doctest.testmod() def main(argv=None): if argv is None: argv = sys.argv if not logging.root.handlers: logging.basicConfig() usage = "usage: %prog [PATHS...]" version = "%prog "+__version__ parser = optparse.OptionParser(prog="markdown2", usage=usage, version=version, description=cmdln_desc, formatter=_NoReflowFormatter()) parser.add_option("-v", "--verbose", dest="log_level", action="store_const", const=logging.DEBUG, help="more verbose output") parser.add_option("--encoding", help="specify encoding of text content") parser.add_option("--html4tags", action="store_true", default=False, help="use HTML 4 style for empty element tags") parser.add_option("-s", "--safe", metavar="MODE", dest="safe_mode", help="sanitize literal HTML: 'escape' escapes " "HTML meta chars, 'replace' replaces with an " "[HTML_REMOVED] note") parser.add_option("-x", "--extras", action="append", help="Turn on specific extra features (not part of " "the core Markdown spec). See above.") parser.add_option("--use-file-vars", help="Look for and use Emacs-style 'markdown-extras' " "file var to turn on extras. See " "<https://github.com/trentm/python-markdown2/wiki/Extras>") parser.add_option("--link-patterns-file", help="path to a link pattern file") parser.add_option("--self-test", action="store_true", help="run internal self-tests (some doctests)") parser.add_option("--compare", action="store_true", help="run against Markdown.pl as well (for testing)") parser.set_defaults(log_level=logging.INFO, compare=False, encoding="utf-8", safe_mode=None, use_file_vars=False) opts, paths = parser.parse_args() log.setLevel(opts.log_level) if opts.self_test: return _test() if opts.extras: extras = {} for s in opts.extras: splitter = re.compile("[,;: ]+") for e in splitter.split(s): if '=' in e: ename, earg = e.split('=', 1) try: earg = int(earg) except ValueError: pass else: ename, earg = e, None extras[ename] = earg else: extras = None if opts.link_patterns_file: link_patterns = [] f = open(opts.link_patterns_file) try: for i, line in enumerate(f.readlines()): if not line.strip(): continue if line.lstrip().startswith("#"): continue try: pat, href = line.rstrip().rsplit(None, 1) except ValueError: raise MarkdownError("%s:%d: invalid link pattern line: %r" % (opts.link_patterns_file, i+1, line)) link_patterns.append( (_regex_from_encoded_pattern(pat), href)) finally: f.close() else: link_patterns = None from os.path import join, dirname, abspath, exists markdown_pl = join(dirname(dirname(abspath(__file__))), "test", "Markdown.pl") if not paths: paths = ['-'] for path in paths: if path == '-': text = sys.stdin.read() else: fp = codecs.open(path, 'r', opts.encoding) text = fp.read() fp.close() if opts.compare: from subprocess import Popen, PIPE print("==== Markdown.pl ====") p = Popen('perl %s' % markdown_pl, shell=True, stdin=PIPE, stdout=PIPE, close_fds=True) p.stdin.write(text.encode('utf-8')) p.stdin.close() perl_html = p.stdout.read().decode('utf-8') if py3: sys.stdout.write(perl_html) else: sys.stdout.write(perl_html.encode( sys.stdout.encoding or "utf-8", 'xmlcharrefreplace')) print("==== markdown2.py ====") html = markdown(text, html4tags=opts.html4tags, safe_mode=opts.safe_mode, extras=extras, link_patterns=link_patterns, use_file_vars=opts.use_file_vars) if py3: sys.stdout.write(html) else: sys.stdout.write(html.encode( sys.stdout.encoding or "utf-8", 'xmlcharrefreplace')) if extras and "toc" in extras: log.debug("toc_html: " + html.toc_html.encode(sys.stdout.encoding or "utf-8", 'xmlcharrefreplace')) if opts.compare: test_dir = join(dirname(dirname(abspath(__file__))), "test") if exists(join(test_dir, "test_markdown2.py")): sys.path.insert(0, test_dir) from test_markdown2 import norm_html_from_html norm_html = norm_html_from_html(html) norm_perl_html = norm_html_from_html(perl_html) else: norm_html = html norm_perl_html = perl_html print("==== match? %r ====" % (norm_perl_html == norm_html)) template_html = u'''<!DOCTYPE html> <!-- Backdoc is a tool for backbone-like documentation generation. Backdoc main goal is to help to generate one page documentation from one markdown source file. https://github.com/chibisov/backdoc --> <html lang="ru"> <head> <meta charset="UTF-8"/> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> <meta name="HandheldFriendly" content="true" /> <title><!-- title --></title> <!-- Bootstrap --> <style type="text/css"> /*! * Bootstrap v3.0.0 * * Copyright 2013 Twitter, Inc * Licensed under the Apache License v2.0 * http://www.apache.org/licenses/LICENSE-2.0 * * Designed and built with all the love in the world by @mdo and @fat. *//*! normalize.css v2.1.0 | MIT License | git.io/normalize */ article,aside,details,figcaption,figure,footer,header,hgroup,main,nav,section,summary{display:block}audio,canvas,video{display:inline-block}audio:not([controls]){display:none;height:0}[hidden]{display:none}html{font-family:sans-serif;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%}body{margin:0}a:focus{outline:thin dotted}a:active,a:hover{outline:0}h1{margin:.67em 0;font-size:2em}abbr[title]{border-bottom:1px dotted}b,strong{font-weight:bold}dfn{font-style:italic}hr{height:0;-moz-box-sizing:content-box;box-sizing:content-box}mark{color:#000;background:#ff0}code,kbd,pre,samp{font-family:monospace,serif;font-size:1em}pre{white-space:pre-wrap}q{quotes:"\201C" "\201D" "\2018" "\2019"}small{font-size:80%}sub,sup{position:relative;font-size:75%;line-height:0;vertical-align:baseline}sup{top:-0.5em}sub{bottom:-0.25em}img{border:0}svg:not(:root){overflow:hidden}figure{margin:0}fieldset{padding:.35em .625em .75em;margin:0 2px;border:1px solid #c0c0c0}legend{padding:0;border:0}button,input,select,textarea{margin:0;font-family:inherit;font-size:100%}button,input{line-height:normal}button,select{text-transform:none}button,html input[type="button"],input[type="reset"],input[type="submit"]{cursor:pointer;-webkit-appearance:button}button[disabled],html input[disabled]{cursor:default}input[type="checkbox"],input[type="radio"]{padding:0;box-sizing:border-box}input[type="search"]{-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;-webkit-appearance:textfield}input[type="search"]::-webkit-search-cancel-button,input[type="search"]::-webkit-search-decoration{-webkit-appearance:none}button::-moz-focus-inner,input::-moz-focus-inner{padding:0;border:0}textarea{overflow:auto;vertical-align:top}table{border-collapse:collapse;border-spacing:0}@media print{*{color:#000!important;text-shadow:none!important;background:transparent!important;box-shadow:none!important}a,a:visited{text-decoration:underline}a[href]:after{content:" (" attr(href) ")"}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100%!important}@page{margin:2cm .5cm}p,h2,h3{orphans:3;widows:3}h2,h3{page-break-after:avoid}.navbar{display:none}.table td,.table th{background-color:#fff!important}.btn>.caret,.dropup>.btn>.caret{border-top-color:#000!important}.label{border:1px solid #000}.table{border-collapse:collapse!important}.table-bordered th,.table-bordered td{border:1px solid #ddd!important}}*{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}html{font-size:62.5%;-webkit-tap-highlight-color:rgba(0,0,0,0)}body{font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px;line-height:1.428571429;color:#333;background-color:#fff}input,button,select,textarea{font-family:inherit;font-size:inherit;line-height:inherit}a{color:#428bca;text-decoration:none}a:hover,a:focus{color:#2a6496;text-decoration:underline}a:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}img{vertical-align:middle}.img-responsive{display:inline-block;height:auto;max-width:100%}.img-rounded{border-radius:6px}.img-circle{border-radius:500px}hr{margin-top:20px;margin-bottom:20px;border:0;border-top:1px solid #eee}p{margin:0 0 10px}.lead{margin-bottom:20px;font-size:16.099999999999998px;font-weight:200;line-height:1.4}@media(min-width:768px){.lead{font-size:21px}}small{font-size:85%}cite{font-style:normal}.text-muted{color:#999}.text-primary{color:#428bca}.text-warning{color:#c09853}.text-danger{color:#b94a48}.text-success{color:#468847}.text-info{color:#3a87ad}.text-left{text-align:left}.text-right{text-align:right}.text-center{text-align:center}h1,h2,h3,h4,h5,h6,.h1,.h2,.h3,.h4,.h5,.h6{font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-weight:500;line-height:1.1}h1 small,h2 small,h3 small,h4 small,h5 small,h6 small,.h1 small,.h2 small,.h3 small,.h4 small,.h5 small,.h6 small{font-weight:normal;line-height:1;color:#999}h1,h2,h3{margin-top:20px;margin-bottom:10px}h4,h5,h6{margin-top:10px;margin-bottom:10px}h1,.h1{font-size:38px}h2,.h2{font-size:32px}h3,.h3{font-size:24px}h4,.h4{font-size:18px}h5,.h5{font-size:14px}h6,.h6{font-size:12px}h1 small,.h1 small{font-size:24px}h2 small,.h2 small{font-size:18px}h3 small,.h3 small,h4 small,.h4 small{font-size:14px}.page-header{padding-bottom:9px;margin:40px 0 20px;border-bottom:1px solid #eee}ul,ol{margin-top:0;margin-bottom:10px}ul ul,ol ul,ul ol,ol ol{margin-bottom:0}.list-unstyled{padding-left:0;list-style:none}.list-inline{padding-left:0;list-style:none}.list-inline>li{display:inline-block;padding-right:5px;padding-left:5px}dl{margin-bottom:20px}dt,dd{line-height:1.428571429}dt{font-weight:bold}dd{margin-left:0}.dl-horizontal dt{float:left;width:160px;overflow:hidden;clear:left;text-align:right;text-overflow:ellipsis;white-space:nowrap}.dl-horizontal dd{margin-left:180px}.dl-horizontal dd:before,.dl-horizontal dd:after{display:table;content:" "}.dl-horizontal dd:after{clear:both}.dl-horizontal dd:before,.dl-horizontal dd:after{display:table;content:" "}.dl-horizontal dd:after{clear:both}abbr[title],abbr[data-original-title]{cursor:help;border-bottom:1px dotted #999}abbr.initialism{font-size:90%;text-transform:uppercase}blockquote{padding:10px 20px;margin:0 0 20px;border-left:5px solid #eee}blockquote p{font-size:17.5px;font-weight:300;line-height:1.25}blockquote p:last-child{margin-bottom:0}blockquote small{display:block;line-height:1.428571429;color:#999}blockquote small:before{content:'\2014 \00A0'}blockquote.pull-right{float:right;padding-right:15px;padding-left:0;border-right:5px solid #eee;border-left:0}blockquote.pull-right p,blockquote.pull-right small{text-align:right}blockquote.pull-right small:before{content:''}blockquote.pull-right small:after{content:'\00A0 \2014'}q:before,q:after,blockquote:before,blockquote:after{content:""}address{display:block;margin-bottom:20px;font-style:normal;line-height:1.428571429}code,pre{font-family:Monaco,Menlo,Consolas,"Courier New",monospace}code{padding:2px 4px;font-size:90%;color:#c7254e;white-space:nowrap;background-color:#f9f2f4;border-radius:4px}pre{display:block;padding:9.5px;margin:0 0 10px;font-size:13px;line-height:1.428571429;color:#333;word-break:break-all;word-wrap:break-word;background-color:#f5f5f5;border:1px solid #ccc;border-radius:4px}pre.prettyprint{margin-bottom:20px}pre code{padding:0;color:inherit;white-space:pre-wrap;background-color:transparent;border:0}.pre-scrollable{max-height:340px;overflow-y:scroll}.container{margin-right:auto;margin-left:auto}.container:before,.container:after{display:table;content:" "}.container:after{clear:both}.container:before,.container:after{display:table;content:" "}.container:after{clear:both}.row:before,.row:after{display:table;content:" "}.row:after{clear:both}.row:before,.row:after{display:table;content:" "}.row:after{clear:both}@media(min-width:768px){.row{margin-right:-15px;margin-left:-15px}}.row .row{margin-right:-15px;margin-left:-15px}.col-1,.col-2,.col-3,.col-4,.col-5,.col-6,.col-7,.col-8,.col-9,.col-10,.col-11,.col-12,.col-sm-1,.col-sm-2,.col-sm-3,.col-sm-4,.col-sm-5,.col-sm-6,.col-sm-7,.col-sm-8,.col-sm-9,.col-sm-10,.col-sm-11,.col-sm-12,.col-lg-1,.col-lg-2,.col-lg-3,.col-lg-4,.col-lg-5,.col-lg-6,.col-lg-7,.col-lg-8,.col-lg-9,.col-lg-10,.col-lg-11,.col-lg-12{position:relative;min-height:1px;padding-right:15px;padding-left:15px}.col-1,.col-2,.col-3,.col-4,.col-5,.col-6,.col-7,.col-8,.col-9,.col-10,.col-11,.col-12{float:left}.col-1{width:8.333333333333332%}.col-2{width:16.666666666666664%}.col-3{width:25%}.col-4{width:33.33333333333333%}.col-5{width:41.66666666666667%}.col-6{width:50%}.col-7{width:58.333333333333336%}.col-8{width:66.66666666666666%}.col-9{width:75%}.col-10{width:83.33333333333334%}.col-11{width:91.66666666666666%}.col-12{width:100%}@media(min-width:768px){.container{max-width:728px}.col-sm-1,.col-sm-2,.col-sm-3,.col-sm-4,.col-sm-5,.col-sm-6,.col-sm-7,.col-sm-8,.col-sm-9,.col-sm-10,.col-sm-11,.col-sm-12{float:left}.col-sm-1{width:8.333333333333332%}.col-sm-2{width:16.666666666666664%}.col-sm-3{width:25%}.col-sm-4{width:33.33333333333333%}.col-sm-5{width:41.66666666666667%}.col-sm-6{width:50%}.col-sm-7{width:58.333333333333336%}.col-sm-8{width:66.66666666666666%}.col-sm-9{width:75%}.col-sm-10{width:83.33333333333334%}.col-sm-11{width:91.66666666666666%}.col-sm-12{width:100%}.col-push-1{left:8.333333333333332%}.col-push-2{left:16.666666666666664%}.col-push-3{left:25%}.col-push-4{left:33.33333333333333%}.col-push-5{left:41.66666666666667%}.col-push-6{left:50%}.col-push-7{left:58.333333333333336%}.col-push-8{left:66.66666666666666%}.col-push-9{left:75%}.col-push-10{left:83.33333333333334%}.col-push-11{left:91.66666666666666%}.col-pull-1{right:8.333333333333332%}.col-pull-2{right:16.666666666666664%}.col-pull-3{right:25%}.col-pull-4{right:33.33333333333333%}.col-pull-5{right:41.66666666666667%}.col-pull-6{right:50%}.col-pull-7{right:58.333333333333336%}.col-pull-8{right:66.66666666666666%}.col-pull-9{right:75%}.col-pull-10{right:83.33333333333334%}.col-pull-11{right:91.66666666666666%}}@media(min-width:992px){.container{max-width:940px}.col-lg-1,.col-lg-2,.col-lg-3,.col-lg-4,.col-lg-5,.col-lg-6,.col-lg-7,.col-lg-8,.col-lg-9,.col-lg-10,.col-lg-11,.col-lg-12{float:left}.col-lg-1{width:8.333333333333332%}.col-lg-2{width:16.666666666666664%}.col-lg-3{width:25%}.col-lg-4{width:33.33333333333333%}.col-lg-5{width:41.66666666666667%}.col-lg-6{width:50%}.col-lg-7{width:58.333333333333336%}.col-lg-8{width:66.66666666666666%}.col-lg-9{width:75%}.col-lg-10{width:83.33333333333334%}.col-lg-11{width:91.66666666666666%}.col-lg-12{width:100%}.col-offset-1{margin-left:8.333333333333332%}.col-offset-2{margin-left:16.666666666666664%}.col-offset-3{margin-left:25%}.col-offset-4{margin-left:33.33333333333333%}.col-offset-5{margin-left:41.66666666666667%}.col-offset-6{margin-left:50%}.col-offset-7{margin-left:58.333333333333336%}.col-offset-8{margin-left:66.66666666666666%}.col-offset-9{margin-left:75%}.col-offset-10{margin-left:83.33333333333334%}.col-offset-11{margin-left:91.66666666666666%}}@media(min-width:1200px){.container{max-width:1170px}}table{max-width:100%;background-color:transparent}th{text-align:left}.table{width:100%;margin-bottom:20px}.table thead>tr>th,.table tbody>tr>th,.table tfoot>tr>th,.table thead>tr>td,.table tbody>tr>td,.table tfoot>tr>td{padding:8px;line-height:1.428571429;vertical-align:top;border-top:1px solid #ddd}.table thead>tr>th{vertical-align:bottom}.table caption+thead tr:first-child th,.table colgroup+thead tr:first-child th,.table thead:first-child tr:first-child th,.table caption+thead tr:first-child td,.table colgroup+thead tr:first-child td,.table thead:first-child tr:first-child td{border-top:0}.table tbody+tbody{border-top:2px solid #ddd}.table .table{background-color:#fff}.table-condensed thead>tr>th,.table-condensed tbody>tr>th,.table-condensed tfoot>tr>th,.table-condensed thead>tr>td,.table-condensed tbody>tr>td,.table-condensed tfoot>tr>td{padding:5px}.table-bordered{border:1px solid #ddd}.table-bordered>thead>tr>th,.table-bordered>tbody>tr>th,.table-bordered>tfoot>tr>th,.table-bordered>thead>tr>td,.table-bordered>tbody>tr>td,.table-bordered>tfoot>tr>td{border:1px solid #ddd}.table-striped>tbody>tr:nth-child(odd)>td,.table-striped>tbody>tr:nth-child(odd)>th{background-color:#f9f9f9}.table-hover>tbody>tr:hover>td,.table-hover>tbody>tr:hover>th{background-color:#f5f5f5}table col[class^="col-"]{display:table-column;float:none}table td[class^="col-"],table th[class^="col-"]{display:table-cell;float:none}.table>thead>tr>td.active,.table>tbody>tr>td.active,.table>tfoot>tr>td.active,.table>thead>tr>th.active,.table>tbody>tr>th.active,.table>tfoot>tr>th.active,.table>thead>tr.active>td,.table>tbody>tr.active>td,.table>tfoot>tr.active>td,.table>thead>tr.active>th,.table>tbody>tr.active>th,.table>tfoot>tr.active>th{background-color:#f5f5f5}.table>thead>tr>td.success,.table>tbody>tr>td.success,.table>tfoot>tr>td.success,.table>thead>tr>th.success,.table>tbody>tr>th.success,.table>tfoot>tr>th.success,.table>thead>tr.success>td,.table>tbody>tr.success>td,.table>tfoot>tr.success>td,.table>thead>tr.success>th,.table>tbody>tr.success>th,.table>tfoot>tr.success>th{background-color:#dff0d8;border-color:#d6e9c6}.table>thead>tr>td.danger,.table>tbody>tr>td.danger,.table>tfoot>tr>td.danger,.table>thead>tr>th.danger,.table>tbody>tr>th.danger,.table>tfoot>tr>th.danger,.table>thead>tr.danger>td,.table>tbody>tr.danger>td,.table>tfoot>tr.danger>td,.table>thead>tr.danger>th,.table>tbody>tr.danger>th,.table>tfoot>tr.danger>th{background-color:#f2dede;border-color:#eed3d7}.table>thead>tr>td.warning,.table>tbody>tr>td.warning,.table>tfoot>tr>td.warning,.table>thead>tr>th.warning,.table>tbody>tr>th.warning,.table>tfoot>tr>th.warning,.table>thead>tr.warning>td,.table>tbody>tr.warning>td,.table>tfoot>tr.warning>td,.table>thead>tr.warning>th,.table>tbody>tr.warning>th,.table>tfoot>tr.warning>th{background-color:#fcf8e3;border-color:#fbeed5}.table-hover>tbody>tr>td.success:hover,.table-hover>tbody>tr>th.success:hover,.table-hover>tbody>tr.success:hover>td{background-color:#d0e9c6;border-color:#c9e2b3}.table-hover>tbody>tr>td.danger:hover,.table-hover>tbody>tr>th.danger:hover,.table-hover>tbody>tr.danger:hover>td{background-color:#ebcccc;border-color:#e6c1c7}.table-hover>tbody>tr>td.warning:hover,.table-hover>tbody>tr>th.warning:hover,.table-hover>tbody>tr.warning:hover>td{background-color:#faf2cc;border-color:#f8e5be}fieldset{padding:0;margin:0;border:0}legend{display:block;width:100%;padding:0;margin-bottom:20px;font-size:21px;line-height:inherit;color:#333;border:0;border-bottom:1px solid #e5e5e5}label{display:inline-block;margin-bottom:5px;font-weight:bold}input[type="search"]{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}input[type="radio"],input[type="checkbox"]{margin:4px 0 0;margin-top:1px \9;line-height:normal}input[type="file"]{display:block}select[multiple],select[size]{height:auto}select optgroup{font-family:inherit;font-size:inherit;font-style:inherit}input[type="file"]:focus,input[type="radio"]:focus,input[type="checkbox"]:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}input[type="number"]::-webkit-outer-spin-button,input[type="number"]::-webkit-inner-spin-button{height:auto}.form-control:-moz-placeholder{color:#999}.form-control::-moz-placeholder{color:#999}.form-control:-ms-input-placeholder{color:#999}.form-control::-webkit-input-placeholder{color:#999}.form-control{display:block;width:100%;height:38px;padding:8px 12px;font-size:14px;line-height:1.428571429;color:#555;vertical-align:middle;background-color:#fff;border:1px solid #ccc;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);-webkit-transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s;transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s}.form-control:focus{border-color:rgba(82,168,236,0.8);outline:0;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6)}.form-control[disabled],.form-control[readonly],fieldset[disabled] .form-control{cursor:not-allowed;background-color:#eee}textarea.form-control{height:auto}.form-group{margin-bottom:15px}.radio,.checkbox{display:block;min-height:20px;padding-left:20px;margin-top:10px;margin-bottom:10px;vertical-align:middle}.radio label,.checkbox label{display:inline;margin-bottom:0;font-weight:normal;cursor:pointer}.radio input[type="radio"],.radio-inline input[type="radio"],.checkbox input[type="checkbox"],.checkbox-inline input[type="checkbox"]{float:left;margin-left:-20px}.radio+.radio,.checkbox+.checkbox{margin-top:-5px}.radio-inline,.checkbox-inline{display:inline-block;padding-left:20px;margin-bottom:0;font-weight:normal;vertical-align:middle;cursor:pointer}.radio-inline+.radio-inline,.checkbox-inline+.checkbox-inline{margin-top:0;margin-left:10px}.form-control.input-large{height:56px;padding:14px 16px;font-size:18px;border-radius:6px}.form-control.input-small{height:30px;padding:5px 10px;font-size:12px;border-radius:3px}select.input-large{height:56px;line-height:56px}select.input-small{height:30px;line-height:30px}.has-warning .help-block,.has-warning .control-label{color:#c09853}.has-warning .form-control{padding-right:32px;border-color:#c09853;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075)}.has-warning .form-control:focus{border-color:#a47e3c;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #dbc59e;box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #dbc59e}.has-warning .input-group-addon{color:#c09853;background-color:#fcf8e3;border-color:#c09853}.has-error .help-block,.has-error .control-label{color:#b94a48}.has-error .form-control{padding-right:32px;border-color:#b94a48;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075)}.has-error .form-control:focus{border-color:#953b39;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #d59392;box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #d59392}.has-error .input-group-addon{color:#b94a48;background-color:#f2dede;border-color:#b94a48}.has-success .help-block,.has-success .control-label{color:#468847}.has-success .form-control{padding-right:32px;border-color:#468847;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075)}.has-success .form-control:focus{border-color:#356635;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7aba7b;box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7aba7b}.has-success .input-group-addon{color:#468847;background-color:#dff0d8;border-color:#468847}.help-block{display:block;margin-top:5px;margin-bottom:10px;color:#737373}.input-group{display:table;border-collapse:separate}.input-group.col{float:none;padding-right:0;padding-left:0}.input-group .form-control{width:100%;margin-bottom:0}.input-group-addon,.input-group-btn,.input-group .form-control{display:table-cell}.input-group-addon:not(:first-child):not(:last-child),.input-group-btn:not(:first-child):not(:last-child),.input-group .form-control:not(:first-child):not(:last-child){border-radius:0}.input-group-addon,.input-group-btn{width:1%;white-space:nowrap;vertical-align:middle}.input-group-addon{padding:8px 12px;font-size:14px;font-weight:normal;line-height:1.428571429;text-align:center;background-color:#eee;border:1px solid #ccc;border-radius:4px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.input-group-addon.input-small{padding:5px 10px;font-size:12px;border-radius:3px}.input-group-addon.input-large{padding:14px 16px;font-size:18px;border-radius:6px}.input-group .form-control:first-child,.input-group-addon:first-child,.input-group-btn:first-child>.btn,.input-group-btn:first-child>.dropdown-toggle,.input-group-btn:last-child>.btn:not(:last-child):not(.dropdown-toggle){border-top-right-radius:0;border-bottom-right-radius:0}.input-group-addon:first-child{border-right:0}.input-group .form-control:last-child,.input-group-addon:last-child,.input-group-btn:last-child>.btn,.input-group-btn:last-child>.dropdown-toggle,.input-group-btn:first-child>.btn:not(:first-child){border-bottom-left-radius:0;border-top-left-radius:0}.input-group-addon:last-child{border-left:0}.input-group-btn{position:relative;white-space:nowrap}.input-group-btn>.btn{position:relative}.input-group-btn>.btn+.btn{margin-left:-4px}.input-group-btn>.btn:hover,.input-group-btn>.btn:active{z-index:2}.form-inline .form-control,.form-inline .radio,.form-inline .checkbox{display:inline-block}.form-inline .radio,.form-inline .checkbox{margin-top:0;margin-bottom:0}.form-horizontal .control-label{padding-top:6px}.form-horizontal .form-group:before,.form-horizontal .form-group:after{display:table;content:" "}.form-horizontal .form-group:after{clear:both}.form-horizontal .form-group:before,.form-horizontal .form-group:after{display:table;content:" "}.form-horizontal .form-group:after{clear:both}@media(min-width:768px){.form-horizontal .form-group{margin-right:-15px;margin-left:-15px}}.form-horizontal .form-group .row{margin-right:-15px;margin-left:-15px}@media(min-width:768px){.form-horizontal .control-label{text-align:right}}.btn{display:inline-block;padding:8px 12px;margin-bottom:0;font-size:14px;font-weight:500;line-height:1.428571429;text-align:center;white-space:nowrap;vertical-align:middle;cursor:pointer;border:1px solid transparent;border-radius:4px}.btn:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn:hover,.btn:focus{color:#fff;text-decoration:none}.btn:active,.btn.active{outline:0;-webkit-box-shadow:inset 0 3px 5px rgba(0,0,0,0.125);box-shadow:inset 0 3px 5px rgba(0,0,0,0.125)}.btn.disabled,.btn[disabled],fieldset[disabled] .btn{pointer-events:none;cursor:default;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;box-shadow:none}.btn-default{color:#fff;background-color:#474949;border-color:#474949}.btn-default:hover,.btn-default:focus,.btn-default:active,.btn-default.active{background-color:#3a3c3c;border-color:#2e2f2f}.btn-default.disabled,.btn-default[disabled],fieldset[disabled] .btn-default,.btn-default.disabled:hover,.btn-default[disabled]:hover,fieldset[disabled] .btn-default:hover,.btn-default.disabled:focus,.btn-default[disabled]:focus,fieldset[disabled] .btn-default:focus,.btn-default.disabled:active,.btn-default[disabled]:active,fieldset[disabled] .btn-default:active,.btn-default.disabled.active,.btn-default[disabled].active,fieldset[disabled] .btn-default.active{background-color:#474949;border-color:#474949}.btn-primary{color:#fff;background-color:#428bca;border-color:#428bca}.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active{background-color:#357ebd;border-color:#3071a9}.btn-primary.disabled,.btn-primary[disabled],fieldset[disabled] .btn-primary,.btn-primary.disabled:hover,.btn-primary[disabled]:hover,fieldset[disabled] .btn-primary:hover,.btn-primary.disabled:focus,.btn-primary[disabled]:focus,fieldset[disabled] .btn-primary:focus,.btn-primary.disabled:active,.btn-primary[disabled]:active,fieldset[disabled] .btn-primary:active,.btn-primary.disabled.active,.btn-primary[disabled].active,fieldset[disabled] .btn-primary.active{background-color:#428bca;border-color:#428bca}.btn-warning{color:#fff;background-color:#f0ad4e;border-color:#f0ad4e}.btn-warning:hover,.btn-warning:focus,.btn-warning:active,.btn-warning.active{background-color:#eea236;border-color:#ec971f}.btn-warning.disabled,.btn-warning[disabled],fieldset[disabled] .btn-warning,.btn-warning.disabled:hover,.btn-warning[disabled]:hover,fieldset[disabled] .btn-warning:hover,.btn-warning.disabled:focus,.btn-warning[disabled]:focus,fieldset[disabled] .btn-warning:focus,.btn-warning.disabled:active,.btn-warning[disabled]:active,fieldset[disabled] .btn-warning:active,.btn-warning.disabled.active,.btn-warning[disabled].active,fieldset[disabled] .btn-warning.active{background-color:#f0ad4e;border-color:#f0ad4e}.btn-danger{color:#fff;background-color:#d9534f;border-color:#d9534f}.btn-danger:hover,.btn-danger:focus,.btn-danger:active,.btn-danger.active{background-color:#d43f3a;border-color:#c9302c}.btn-danger.disabled,.btn-danger[disabled],fieldset[disabled] .btn-danger,.btn-danger.disabled:hover,.btn-danger[disabled]:hover,fieldset[disabled] .btn-danger:hover,.btn-danger.disabled:focus,.btn-danger[disabled]:focus,fieldset[disabled] .btn-danger:focus,.btn-danger.disabled:active,.btn-danger[disabled]:active,fieldset[disabled] .btn-danger:active,.btn-danger.disabled.active,.btn-danger[disabled].active,fieldset[disabled] .btn-danger.active{background-color:#d9534f;border-color:#d9534f}.btn-success{color:#fff;background-color:#5cb85c;border-color:#5cb85c}.btn-success:hover,.btn-success:focus,.btn-success:active,.btn-success.active{background-color:#4cae4c;border-color:#449d44}.btn-success.disabled,.btn-success[disabled],fieldset[disabled] .btn-success,.btn-success.disabled:hover,.btn-success[disabled]:hover,fieldset[disabled] .btn-success:hover,.btn-success.disabled:focus,.btn-success[disabled]:focus,fieldset[disabled] .btn-success:focus,.btn-success.disabled:active,.btn-success[disabled]:active,fieldset[disabled] .btn-success:active,.btn-success.disabled.active,.btn-success[disabled].active,fieldset[disabled] .btn-success.active{background-color:#5cb85c;border-color:#5cb85c}.btn-info{color:#fff;background-color:#5bc0de;border-color:#5bc0de}.btn-info:hover,.btn-info:focus,.btn-info:active,.btn-info.active{background-color:#46b8da;border-color:#31b0d5}.btn-info.disabled,.btn-info[disabled],fieldset[disabled] .btn-info,.btn-info.disabled:hover,.btn-info[disabled]:hover,fieldset[disabled] .btn-info:hover,.btn-info.disabled:focus,.btn-info[disabled]:focus,fieldset[disabled] .btn-info:focus,.btn-info.disabled:active,.btn-info[disabled]:active,fieldset[disabled] .btn-info:active,.btn-info.disabled.active,.btn-info[disabled].active,fieldset[disabled] .btn-info.active{background-color:#5bc0de;border-color:#5bc0de}.btn-link{font-weight:normal;color:#428bca;cursor:pointer;border-radius:0}.btn-link,.btn-link:active,.btn-link[disabled],fieldset[disabled] .btn-link{background-color:transparent;-webkit-box-shadow:none;box-shadow:none}.btn-link,.btn-link:hover,.btn-link:focus,.btn-link:active{border-color:transparent}.btn-link:hover,.btn-link:focus{color:#2a6496;text-decoration:underline;background-color:transparent}.btn-link[disabled]:hover,fieldset[disabled] .btn-link:hover,.btn-link[disabled]:focus,fieldset[disabled] .btn-link:focus{color:#333;text-decoration:none}.btn-large{padding:14px 16px;font-size:18px;border-radius:6px}.btn-small{padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}.btn-block{display:block;width:100%;padding-right:0;padding-left:0}.btn-block+.btn-block{margin-top:5px}input[type="submit"].btn-block,input[type="reset"].btn-block,input[type="button"].btn-block{width:100%}.fade{opacity:0;-webkit-transition:opacity .15s linear;transition:opacity .15s linear}.fade.in{opacity:1}.collapse{display:none}.collapse.in{display:block}.collapsing{position:relative;height:0;overflow:hidden;-webkit-transition:height .35s ease;transition:height .35s ease}.caret{display:inline-block;width:0;height:0;margin-left:2px;vertical-align:middle;border-top:4px solid #000;border-right:4px solid transparent;border-left:4px solid transparent;content:""}.dropdown-menu{position:absolute;top:100%;left:0;z-index:1000;display:none;float:left;min-width:160px;padding:5px 0;margin:2px 0 0;list-style:none;background-color:#fff;border:1px solid #ccc;border:1px solid rgba(0,0,0,0.15);border-radius:4px;-webkit-box-shadow:0 6px 12px rgba(0,0,0,0.175);box-shadow:0 6px 12px rgba(0,0,0,0.175);background-clip:padding-box}.dropdown-menu.pull-right{right:0;left:auto}.dropdown-menu .divider{height:1px;margin:9px 0;overflow:hidden;background-color:#e5e5e5}.dropdown-menu>li>a{display:block;padding:3px 20px;clear:both;font-weight:normal;line-height:1.428571429;color:#333;white-space:nowrap}.dropdown-menu>li>a:hover,.dropdown-menu>li>a:focus{color:#fff;text-decoration:none;background-color:#357ebd;background-image:-webkit-gradient(linear,left 0,left 100%,from(#428bca),to(#357ebd));background-image:-webkit-linear-gradient(top,#428bca,0%,#357ebd,100%);background-image:-moz-linear-gradient(top,#428bca 0,#357ebd 100%);background-image:linear-gradient(to bottom,#428bca 0,#357ebd 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff428bca',endColorstr='#ff357ebd',GradientType=0)}.dropdown-menu>.active>a,.dropdown-menu>.active>a:hover,.dropdown-menu>.active>a:focus{color:#fff;text-decoration:none;background-color:#357ebd;background-image:-webkit-gradient(linear,left 0,left 100%,from(#428bca),to(#357ebd));background-image:-webkit-linear-gradient(top,#428bca,0%,#357ebd,100%);background-image:-moz-linear-gradient(top,#428bca 0,#357ebd 100%);background-image:linear-gradient(to bottom,#428bca 0,#357ebd 100%);background-repeat:repeat-x;outline:0;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff428bca',endColorstr='#ff357ebd',GradientType=0)}.dropdown-menu>.disabled>a,.dropdown-menu>.disabled>a:hover,.dropdown-menu>.disabled>a:focus{color:#999}.dropdown-menu>.disabled>a:hover,.dropdown-menu>.disabled>a:focus{text-decoration:none;cursor:not-allowed;background-color:transparent;background-image:none;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.open>.dropdown-menu{display:block}.open>a{outline:0}.dropdown-header{display:block;padding:3px 20px;font-size:12px;line-height:1.428571429;color:#999}.dropdown-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:990}.pull-right>.dropdown-menu{right:0;left:auto}.dropup .caret,.navbar-fixed-bottom .dropdown .caret{border-top:0;border-bottom:4px solid #000;content:""}.dropup .dropdown-menu,.navbar-fixed-bottom .dropdown .dropdown-menu{top:auto;bottom:100%;margin-bottom:1px}.list-group{padding-left:0;margin-bottom:20px;background-color:#fff}.list-group-item{position:relative;display:block;padding:10px 30px 10px 15px;margin-bottom:-1px;border:1px solid #ddd}.list-group-item:first-child{border-top-right-radius:4px;border-top-left-radius:4px}.list-group-item:last-child{margin-bottom:0;border-bottom-right-radius:4px;border-bottom-left-radius:4px}.list-group-item>.badge{float:right;margin-right:-15px}.list-group-item-heading{margin-top:0;margin-bottom:5px}.list-group-item-text{margin-bottom:0;line-height:1.3}a.list-group-item .list-group-item-heading{color:#333}a.list-group-item .list-group-item-text{color:#555}a.list-group-item:hover,a.list-group-item:focus{text-decoration:none;background-color:#f5f5f5}a.list-group-item.active{z-index:2;color:#fff;background-color:#428bca;border-color:#428bca}a.list-group-item.active .list-group-item-heading{color:inherit}a.list-group-item.active .list-group-item-text{color:#e1edf7}.panel{padding:15px;margin-bottom:20px;background-color:#fff;border:1px solid #ddd;border-radius:4px;-webkit-box-shadow:0 1px 1px rgba(0,0,0,0.05);box-shadow:0 1px 1px rgba(0,0,0,0.05)}.panel-heading{padding:10px 15px;margin:-15px -15px 15px;background-color:#f5f5f5;border-bottom:1px solid #ddd;border-top-right-radius:3px;border-top-left-radius:3px}.panel-title{margin-top:0;margin-bottom:0;font-size:17.5px;font-weight:500}.panel-footer{padding:10px 15px;margin:15px -15px -15px;background-color:#f5f5f5;border-top:1px solid #ddd;border-bottom-right-radius:3px;border-bottom-left-radius:3px}.panel-primary{border-color:#428bca}.panel-primary .panel-heading{color:#fff;background-color:#428bca;border-color:#428bca}.panel-success{border-color:#d6e9c6}.panel-success .panel-heading{color:#468847;background-color:#dff0d8;border-color:#d6e9c6}.panel-warning{border-color:#fbeed5}.panel-warning .panel-heading{color:#c09853;background-color:#fcf8e3;border-color:#fbeed5}.panel-danger{border-color:#eed3d7}.panel-danger .panel-heading{color:#b94a48;background-color:#f2dede;border-color:#eed3d7}.panel-info{border-color:#bce8f1}.panel-info .panel-heading{color:#3a87ad;background-color:#d9edf7;border-color:#bce8f1}.list-group-flush{margin:15px -15px -15px}.list-group-flush .list-group-item{border-width:1px 0}.list-group-flush .list-group-item:first-child{border-top-right-radius:0;border-top-left-radius:0}.list-group-flush .list-group-item:last-child{border-bottom:0}.well{min-height:20px;padding:19px;margin-bottom:20px;background-color:#f5f5f5;border:1px solid #e3e3e3;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.05);box-shadow:inset 0 1px 1px rgba(0,0,0,0.05)}.well blockquote{border-color:#ddd;border-color:rgba(0,0,0,0.15)}.well-large{padding:24px;border-radius:6px}.well-small{padding:9px;border-radius:3px}.close{float:right;font-size:21px;font-weight:bold;line-height:1;color:#000;text-shadow:0 1px 0 #fff;opacity:.2;filter:alpha(opacity=20)}.close:hover,.close:focus{color:#000;text-decoration:none;cursor:pointer;opacity:.5;filter:alpha(opacity=50)}button.close{padding:0;cursor:pointer;background:transparent;border:0;-webkit-appearance:none}.nav{padding-left:0;margin-bottom:0;list-style:none}.nav:before,.nav:after{display:table;content:" "}.nav:after{clear:both}.nav:before,.nav:after{display:table;content:" "}.nav:after{clear:both}.nav>li{position:relative;display:block}.nav>li>a{position:relative;display:block;padding:10px 15px}.nav>li>a:hover,.nav>li>a:focus{text-decoration:none;background-color:#eee}.nav>li.disabled>a{color:#999}.nav>li.disabled>a:hover,.nav>li.disabled>a:focus{color:#999;text-decoration:none;cursor:not-allowed;background-color:transparent}.nav>li+.nav-header{margin-top:9px}.nav.open>a,.nav.open>a:hover,.nav.open>a:focus{color:#fff;background-color:#428bca;border-color:#428bca}.nav.open>a .caret,.nav.open>a:hover .caret,.nav.open>a:focus .caret{border-top-color:#fff;border-bottom-color:#fff}.nav>.pull-right{float:right}.nav .nav-divider{height:1px;margin:9px 0;overflow:hidden;background-color:#e5e5e5}.nav-tabs{border-bottom:1px solid #ddd}.nav-tabs>li{float:left;margin-bottom:-1px}.nav-tabs>li>a{margin-right:2px;line-height:1.428571429;border:1px solid transparent;border-radius:4px 4px 0 0}.nav-tabs>li>a:hover{border-color:#eee}.nav-tabs>li.active>a,.nav-tabs>li.active>a:hover,.nav-tabs>li.active>a:focus{color:#555;cursor:default;background-color:#fff;border:1px solid #ddd;border-bottom-color:transparent}.nav-tabs.nav-justified{width:100%;border-bottom:0}.nav-tabs.nav-justified>li{display:table-cell;float:none;width:1%}.nav-tabs.nav-justified>li>a{text-align:center}.nav-tabs.nav-justified>li>a{margin-right:0;border-bottom:1px solid #ddd}.nav-tabs.nav-justified>.active>a{border-bottom-color:#fff}.nav-pills>li{float:left}.nav-pills>li>a{border-radius:5px}.nav-pills>li+li{margin-left:2px}.nav-pills>li.active>a,.nav-pills>li.active>a:hover,.nav-pills>li.active>a:focus{color:#fff;background-color:#428bca}.nav-stacked>li{float:none}.nav-stacked>li+li>a{margin-top:2px;margin-left:0}.nav-justified{width:100%}.nav-justified>li{display:table-cell;float:none;width:1%}.nav-justified>li>a{text-align:center}.nav-tabs-justified{border-bottom:0}.nav-tabs-justified>li>a{margin-right:0;border-bottom:1px solid #ddd}.nav-tabs-justified>.active>a{border-bottom-color:#fff}.tabbable:before,.tabbable:after{display:table;content:" "}.tabbable:after{clear:both}.tabbable:before,.tabbable:after{display:table;content:" "}.tabbable:after{clear:both}.tab-content>.tab-pane,.pill-content>.pill-pane{display:none}.tab-content>.active,.pill-content>.active{display:block}.nav .caret{border-top-color:#428bca;border-bottom-color:#428bca}.nav a:hover .caret{border-top-color:#2a6496;border-bottom-color:#2a6496}.nav-tabs .dropdown-menu{margin-top:-1px;border-top-right-radius:0;border-top-left-radius:0}.navbar{position:relative;min-height:50px;padding-right:15px;padding-left:15px;margin-bottom:20px;background-color:#eee;border-radius:4px}.navbar:before,.navbar:after{display:table;content:" "}.navbar:after{clear:both}.navbar:before,.navbar:after{display:table;content:" "}.navbar:after{clear:both}.navbar-nav{margin-top:10px;margin-bottom:15px}.navbar-nav>li>a{padding-top:15px;padding-bottom:15px;line-height:20px;color:#777;border-radius:4px}.navbar-nav>li>a:hover,.navbar-nav>li>a:focus{color:#333;background-color:transparent}.navbar-nav>.active>a,.navbar-nav>.active>a:hover,.navbar-nav>.active>a:focus{color:#555;background-color:#d5d5d5}.navbar-nav>.disabled>a,.navbar-nav>.disabled>a:hover,.navbar-nav>.disabled>a:focus{color:#ccc;background-color:transparent}.navbar-nav.pull-right{width:100%}.navbar-static-top{border-radius:0}.navbar-fixed-top,.navbar-fixed-bottom{position:fixed;right:0;left:0;z-index:1030;border-radius:0}.navbar-fixed-top{top:0}.navbar-fixed-bottom{bottom:0;margin-bottom:0}.navbar-brand{display:block;max-width:200px;padding:15px 15px;margin-right:auto;margin-left:auto;font-size:18px;font-weight:500;line-height:20px;color:#777;text-align:center}.navbar-brand:hover,.navbar-brand:focus{color:#5e5e5e;text-decoration:none;background-color:transparent}.navbar-toggle{position:absolute;top:9px;right:10px;width:48px;height:32px;padding:8px 12px;background-color:transparent;border:1px solid #ddd;border-radius:4px}.navbar-toggle:hover,.navbar-toggle:focus{background-color:#ddd}.navbar-toggle .icon-bar{display:block;width:22px;height:2px;background-color:#ccc;border-radius:1px}.navbar-toggle .icon-bar+.icon-bar{margin-top:4px}.navbar-form{margin-top:6px;margin-bottom:6px}.navbar-form .form-control,.navbar-form .radio,.navbar-form .checkbox{display:inline-block}.navbar-form .radio,.navbar-form .checkbox{margin-top:0;margin-bottom:0}.navbar-nav>li>.dropdown-menu{margin-top:0;border-top-right-radius:0;border-top-left-radius:0}.navbar-fixed-bottom .navbar-nav>li>.dropdown-menu{border-bottom-right-radius:0;border-bottom-left-radius:0}.navbar-nav>.dropdown>a:hover .caret,.navbar-nav>.dropdown>a:focus .caret{border-top-color:#333;border-bottom-color:#333}.navbar-nav>.open>a,.navbar-nav>.open>a:hover,.navbar-nav>.open>a:focus{color:#555;background-color:#d5d5d5}.navbar-nav>.open>a .caret,.navbar-nav>.open>a:hover .caret,.navbar-nav>.open>a:focus .caret{border-top-color:#555;border-bottom-color:#555}.navbar-nav>.dropdown>a .caret{border-top-color:#777;border-bottom-color:#777}.navbar-nav.pull-right>li>.dropdown-menu,.navbar-nav>li>.dropdown-menu.pull-right{right:0;left:auto}.navbar-inverse{background-color:#222}.navbar-inverse .navbar-brand{color:#999}.navbar-inverse .navbar-brand:hover,.navbar-inverse .navbar-brand:focus{color:#fff;background-color:transparent}.navbar-inverse .navbar-text{color:#999}.navbar-inverse .navbar-nav>li>a{color:#999}.navbar-inverse .navbar-nav>li>a:hover,.navbar-inverse .navbar-nav>li>a:focus{color:#fff;background-color:transparent}.navbar-inverse .navbar-nav>.active>a,.navbar-inverse .navbar-nav>.active>a:hover,.navbar-inverse .navbar-nav>.active>a:focus{color:#fff;background-color:#080808}.navbar-inverse .navbar-nav>.disabled>a,.navbar-inverse .navbar-nav>.disabled>a:hover,.navbar-inverse .navbar-nav>.disabled>a:focus{color:#444;background-color:transparent}.navbar-inverse .navbar-toggle{border-color:#333}.navbar-inverse .navbar-toggle:hover,.navbar-inverse .navbar-toggle:focus{background-color:#333}.navbar-inverse .navbar-toggle .icon-bar{background-color:#fff}.navbar-inverse .navbar-nav>.open>a,.navbar-inverse .navbar-nav>.open>a:hover,.navbar-inverse .navbar-nav>.open>a:focus{color:#fff;background-color:#080808}.navbar-inverse .navbar-nav>.dropdown>a:hover .caret{border-top-color:#fff;border-bottom-color:#fff}.navbar-inverse .navbar-nav>.dropdown>a .caret{border-top-color:#999;border-bottom-color:#999}.navbar-inverse .navbar-nav>.open>a .caret,.navbar-inverse .navbar-nav>.open>a:hover .caret,.navbar-inverse .navbar-nav>.open>a:focus .caret{border-top-color:#fff;border-bottom-color:#fff}@media screen and (min-width:768px){.navbar-brand{float:left;margin-right:5px;margin-left:-15px}.navbar-nav{float:left;margin-top:0;margin-bottom:0}.navbar-nav>li{float:left}.navbar-nav>li>a{border-radius:0}.navbar-nav.pull-right{float:right;width:auto}.navbar-toggle{position:relative;top:auto;left:auto;display:none}.nav-collapse.collapse{display:block!important;height:auto!important;overflow:visible!important}}.navbar-btn{margin-top:6px}.navbar-text{margin-top:15px;margin-bottom:15px}.navbar-link{color:#777}.navbar-link:hover{color:#333}.navbar-inverse .navbar-link{color:#999}.navbar-inverse .navbar-link:hover{color:#fff}.btn .caret{border-top-color:#fff}.dropup .btn .caret{border-bottom-color:#fff}.btn-group,.btn-group-vertical{position:relative;display:inline-block;vertical-align:middle}.btn-group>.btn,.btn-group-vertical>.btn{position:relative;float:left}.btn-group>.btn:hover,.btn-group-vertical>.btn:hover,.btn-group>.btn:active,.btn-group-vertical>.btn:active{z-index:2}.btn-group .btn+.btn{margin-left:-1px}.btn-toolbar:before,.btn-toolbar:after{display:table;content:" "}.btn-toolbar:after{clear:both}.btn-toolbar:before,.btn-toolbar:after{display:table;content:" "}.btn-toolbar:after{clear:both}.btn-toolbar .btn-group{float:left}.btn-toolbar>.btn+.btn,.btn-toolbar>.btn-group+.btn,.btn-toolbar>.btn+.btn-group,.btn-toolbar>.btn-group+.btn-group{margin-left:5px}.btn-group>.btn:not(:first-child):not(:last-child):not(.dropdown-toggle){border-radius:0}.btn-group>.btn:first-child{margin-left:0}.btn-group>.btn:first-child:not(:last-child):not(.dropdown-toggle){border-top-right-radius:0;border-bottom-right-radius:0}.btn-group>.btn:last-child:not(:first-child),.btn-group>.dropdown-toggle:not(:first-child){border-bottom-left-radius:0;border-top-left-radius:0}.btn-group>.btn-group{float:left}.btn-group>.btn-group:not(:first-child):not(:last-child)>.btn{border-radius:0}.btn-group>.btn-group:first-child>.btn:last-child,.btn-group>.btn-group:first-child>.dropdown-toggle{border-top-right-radius:0;border-bottom-right-radius:0}.btn-group>.btn-group:last-child>.btn:first-child{border-bottom-left-radius:0;border-top-left-radius:0}.btn-group .dropdown-toggle:active,.btn-group.open .dropdown-toggle{outline:0}.btn-group>.btn+.dropdown-toggle{padding-right:8px;padding-left:8px}.btn-group>.btn-large+.dropdown-toggle{padding-right:12px;padding-left:12px}.btn-group.open .dropdown-toggle{-webkit-box-shadow:inset 0 3px 5px rgba(0,0,0,0.125);box-shadow:inset 0 3px 5px rgba(0,0,0,0.125)}.btn .caret{margin-left:0}.btn-large .caret{border-width:5px}.dropup .btn-large .caret{border-bottom-width:5px}.btn-group-vertical>.btn{display:block;float:none;width:100%;max-width:100%}.btn-group-vertical>.btn+.btn{margin-top:-1px}.btn-group-vertical .btn:not(:first-child):not(:last-child){border-radius:0}.btn-group-vertical .btn:first-child{border-bottom-right-radius:0;border-bottom-left-radius:0}.btn-group-vertical .btn:last-child{border-top-right-radius:0;border-top-left-radius:0}.btn-group-justified{display:table;width:100%}.btn-group-justified .btn{display:table-cell;float:none;width:1%}.btn-group[data-toggle="buttons"]>.btn>input[type="radio"],.btn-group[data-toggle="buttons"]>.btn>input[type="checkbox"]{display:none}.breadcrumb{padding:8px 15px;margin-bottom:20px;list-style:none;background-color:#f5f5f5;border-radius:4px}.breadcrumb>li{display:inline-block}.breadcrumb>li+li:before{padding:0 5px;color:#ccc;content:"/\00a0"}.breadcrumb>.active{color:#999}.pagination{display:inline-block;padding-left:0;margin:20px 0;border-radius:4px}.pagination>li{display:inline}.pagination>li>a,.pagination>li>span{float:left;padding:4px 12px;line-height:1.428571429;text-decoration:none;background-color:#fff;border:1px solid #ddd;border-left-width:0}.pagination>li:first-child>a,.pagination>li:first-child>span{border-left-width:1px;border-bottom-left-radius:4px;border-top-left-radius:4px}.pagination>li:last-child>a,.pagination>li:last-child>span{border-top-right-radius:4px;border-bottom-right-radius:4px}.pagination>li>a:hover,.pagination>li>a:focus,.pagination>.active>a,.pagination>.active>span{background-color:#f5f5f5}.pagination>.active>a,.pagination>.active>span{color:#999;cursor:default}.pagination>.disabled>span,.pagination>.disabled>a,.pagination>.disabled>a:hover,.pagination>.disabled>a:focus{color:#999;cursor:not-allowed;background-color:#fff}.pagination-large>li>a,.pagination-large>li>span{padding:14px 16px;font-size:18px}.pagination-large>li:first-child>a,.pagination-large>li:first-child>span{border-bottom-left-radius:6px;border-top-left-radius:6px}.pagination-large>li:last-child>a,.pagination-large>li:last-child>span{border-top-right-radius:6px;border-bottom-right-radius:6px}.pagination-small>li>a,.pagination-small>li>span{padding:5px 10px;font-size:12px}.pagination-small>li:first-child>a,.pagination-small>li:first-child>span{border-bottom-left-radius:3px;border-top-left-radius:3px}.pagination-small>li:last-child>a,.pagination-small>li:last-child>span{border-top-right-radius:3px;border-bottom-right-radius:3px}.pager{padding-left:0;margin:20px 0;text-align:center;list-style:none}.pager:before,.pager:after{display:table;content:" "}.pager:after{clear:both}.pager:before,.pager:after{display:table;content:" "}.pager:after{clear:both}.pager li{display:inline}.pager li>a,.pager li>span{display:inline-block;padding:5px 14px;background-color:#fff;border:1px solid #ddd;border-radius:15px}.pager li>a:hover,.pager li>a:focus{text-decoration:none;background-color:#f5f5f5}.pager .next>a,.pager .next>span{float:right}.pager .previous>a,.pager .previous>span{float:left}.pager .disabled>a,.pager .disabled>a:hover,.pager .disabled>a:focus,.pager .disabled>span{color:#999;cursor:not-allowed;background-color:#fff}.modal-open{overflow:hidden}.modal{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1040;display:none;overflow:auto;overflow-y:scroll}.modal.fade .modal-dialog{-webkit-transform:translate(0,-25%);-ms-transform:translate(0,-25%);transform:translate(0,-25%);-webkit-transition:-webkit-transform .3s ease-out;-moz-transition:-moz-transform .3s ease-out;-o-transition:-o-transform .3s ease-out;transition:transform .3s ease-out}.modal.fade.in .modal-dialog{-webkit-transform:translate(0,0);-ms-transform:translate(0,0);transform:translate(0,0)}.modal-dialog{position:relative;top:0;right:0;left:0;z-index:1050;width:auto;padding:10px}.modal-content{position:relative;background-color:#fff;border:1px solid #999;border:1px solid rgba(0,0,0,0.2);border-radius:6px;outline:0;-webkit-box-shadow:0 3px 9px rgba(0,0,0,0.5);box-shadow:0 3px 9px rgba(0,0,0,0.5);background-clip:padding-box}.modal-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1030;background-color:#000}.modal-backdrop.fade{opacity:0;filter:alpha(opacity=0)}.modal-backdrop.fade.in{opacity:.5;filter:alpha(opacity=50)}.modal-header{min-height:16.428571429px;padding:15px;border-bottom:1px solid #e5e5e5}.modal-header .close{margin-top:-2px}.modal-title{margin:0;line-height:1.428571429}.modal-body{position:relative;padding:20px}.modal-footer{padding:19px 20px 20px;margin-top:15px;text-align:right;border-top:1px solid #e5e5e5}.modal-footer:before,.modal-footer:after{display:table;content:" "}.modal-footer:after{clear:both}.modal-footer:before,.modal-footer:after{display:table;content:" "}.modal-footer:after{clear:both}.modal-footer .btn+.btn{margin-bottom:0;margin-left:5px}.modal-footer .btn-group .btn+.btn{margin-left:-1px}.modal-footer .btn-block+.btn-block{margin-left:0}@media screen and (min-width:768px){.modal-dialog{right:auto;left:50%;width:560px;padding-top:30px;padding-bottom:30px;margin-left:-280px}.modal-content{-webkit-box-shadow:0 5px 15px rgba(0,0,0,0.5);box-shadow:0 5px 15px rgba(0,0,0,0.5)}}.tooltip{position:absolute;z-index:1030;display:block;font-size:12px;line-height:1.4;opacity:0;filter:alpha(opacity=0);visibility:visible}.tooltip.in{opacity:1;filter:alpha(opacity=100)}.tooltip.top{padding:5px 0;margin-top:-3px}.tooltip.right{padding:0 5px;margin-left:3px}.tooltip.bottom{padding:5px 0;margin-top:3px}.tooltip.left{padding:0 5px;margin-left:-3px}.tooltip-inner{max-width:200px;padding:3px 8px;color:#fff;text-align:center;text-decoration:none;background-color:rgba(0,0,0,0.9);border-radius:4px}.tooltip-arrow{position:absolute;width:0;height:0;border-color:transparent;border-style:solid}.tooltip.top .tooltip-arrow{bottom:0;left:50%;margin-left:-5px;border-top-color:rgba(0,0,0,0.9);border-width:5px 5px 0}.tooltip.top-left .tooltip-arrow{bottom:0;left:5px;border-top-color:rgba(0,0,0,0.9);border-width:5px 5px 0}.tooltip.top-right .tooltip-arrow{right:5px;bottom:0;border-top-color:rgba(0,0,0,0.9);border-width:5px 5px 0}.tooltip.right .tooltip-arrow{top:50%;left:0;margin-top:-5px;border-right-color:rgba(0,0,0,0.9);border-width:5px 5px 5px 0}.tooltip.left .tooltip-arrow{top:50%;right:0;margin-top:-5px;border-left-color:rgba(0,0,0,0.9);border-width:5px 0 5px 5px}.tooltip.bottom .tooltip-arrow{top:0;left:50%;margin-left:-5px;border-bottom-color:rgba(0,0,0,0.9);border-width:0 5px 5px}.tooltip.bottom-left .tooltip-arrow{top:0;left:5px;border-bottom-color:rgba(0,0,0,0.9);border-width:0 5px 5px}.tooltip.bottom-right .tooltip-arrow{top:0;right:5px;border-bottom-color:rgba(0,0,0,0.9);border-width:0 5px 5px}.popover{position:absolute;top:0;left:0;z-index:1010;display:none;max-width:276px;padding:1px;text-align:left;white-space:normal;background-color:#fff;border:1px solid #ccc;border:1px solid rgba(0,0,0,0.2);border-radius:6px;-webkit-box-shadow:0 5px 10px rgba(0,0,0,0.2);box-shadow:0 5px 10px rgba(0,0,0,0.2);background-clip:padding-box;-webkit-bg-clip:padding-box;-moz-bg-clip:padding}.popover.top{margin-top:-10px}.popover.right{margin-left:10px}.popover.bottom{margin-top:10px}.popover.left{margin-left:-10px}.popover-title{padding:8px 14px;margin:0;font-size:14px;font-weight:normal;line-height:18px;background-color:#f7f7f7;border-bottom:1px solid #ebebeb;border-radius:5px 5px 0 0}.popover-content{padding:9px 14px}.popover .arrow,.popover .arrow:after{position:absolute;display:block;width:0;height:0;border-color:transparent;border-style:solid}.popover .arrow{border-width:11px}.popover .arrow:after{border-width:10px;content:""}.popover.top .arrow{bottom:-11px;left:50%;margin-left:-11px;border-top-color:#999;border-top-color:rgba(0,0,0,0.25);border-bottom-width:0}.popover.top .arrow:after{bottom:1px;margin-left:-10px;border-top-color:#fff;border-bottom-width:0;content:" "}.popover.right .arrow{top:50%;left:-11px;margin-top:-11px;border-right-color:#999;border-right-color:rgba(0,0,0,0.25);border-left-width:0}.popover.right .arrow:after{bottom:-10px;left:1px;border-right-color:#fff;border-left-width:0;content:" "}.popover.bottom .arrow{top:-11px;left:50%;margin-left:-11px;border-bottom-color:#999;border-bottom-color:rgba(0,0,0,0.25);border-top-width:0}.popover.bottom .arrow:after{top:1px;margin-left:-10px;border-bottom-color:#fff;border-top-width:0;content:" "}.popover.left .arrow{top:50%;right:-11px;margin-top:-11px;border-left-color:#999;border-left-color:rgba(0,0,0,0.25);border-right-width:0}.popover.left .arrow:after{right:1px;bottom:-10px;border-left-color:#fff;border-right-width:0;content:" "}.alert{padding:10px 35px 10px 15px;margin-bottom:20px;color:#c09853;background-color:#fcf8e3;border:1px solid #fbeed5;border-radius:4px}.alert h4{margin-top:0;color:inherit}.alert hr{border-top-color:#f8e5be}.alert .alert-link{font-weight:500;color:#a47e3c}.alert .close{position:relative;top:-2px;right:-21px;color:inherit}.alert-success{color:#468847;background-color:#dff0d8;border-color:#d6e9c6}.alert-success hr{border-top-color:#c9e2b3}.alert-success .alert-link{color:#356635}.alert-danger{color:#b94a48;background-color:#f2dede;border-color:#eed3d7}.alert-danger hr{border-top-color:#e6c1c7}.alert-danger .alert-link{color:#953b39}.alert-info{color:#3a87ad;background-color:#d9edf7;border-color:#bce8f1}.alert-info hr{border-top-color:#a6e1ec}.alert-info .alert-link{color:#2d6987}.alert-block{padding-top:15px;padding-bottom:15px}.alert-block>p,.alert-block>ul{margin-bottom:0}.alert-block p+p{margin-top:5px}.thumbnail,.img-thumbnail{padding:4px;line-height:1.428571429;background-color:#fff;border:1px solid #ddd;border-radius:4px;-webkit-transition:all .2s ease-in-out;transition:all .2s ease-in-out}.thumbnail{display:block}.thumbnail>img,.img-thumbnail{display:inline-block;height:auto;max-width:100%}a.thumbnail:hover,a.thumbnail:focus{border-color:#428bca}.thumbnail>img{margin-right:auto;margin-left:auto}.thumbnail .caption{padding:9px;color:#333}.media,.media-body{overflow:hidden;zoom:1}.media,.media .media{margin-top:15px}.media:first-child{margin-top:0}.media-object{display:block}.media-heading{margin:0 0 5px}.media>.pull-left{margin-right:10px}.media>.pull-right{margin-left:10px}.media-list{padding-left:0;list-style:none}.label{display:inline;padding:.25em .6em;font-size:75%;font-weight:500;line-height:1;color:#fff;text-align:center;white-space:nowrap;vertical-align:middle;background-color:#999;border-radius:.25em}.label[href]:hover,.label[href]:focus{color:#fff;text-decoration:none;cursor:pointer;background-color:#808080}.label-danger{background-color:#d9534f}.label-danger[href]:hover,.label-danger[href]:focus{background-color:#c9302c}.label-success{background-color:#5cb85c}.label-success[href]:hover,.label-success[href]:focus{background-color:#449d44}.label-warning{background-color:#f0ad4e}.label-warning[href]:hover,.label-warning[href]:focus{background-color:#ec971f}.label-info{background-color:#5bc0de}.label-info[href]:hover,.label-info[href]:focus{background-color:#31b0d5}.badge{display:inline-block;min-width:10px;padding:3px 7px;font-size:12px;font-weight:bold;line-height:1;color:#fff;text-align:center;white-space:nowrap;vertical-align:middle;background-color:#999;border-radius:10px}.badge:empty{display:none}a.badge:hover,a.badge:focus{color:#fff;text-decoration:none;cursor:pointer}.btn .badge{position:relative;top:-1px}a.list-group-item.active>.badge,.nav-pills>.active>a>.badge{color:#428bca;background-color:#fff}.nav-pills>li>a>.badge{margin-left:3px}@-webkit-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@-moz-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@-ms-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@-o-keyframes progress-bar-stripes{from{background-position:0 0}to{background-position:40px 0}}@keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}.progress{height:20px;margin-bottom:20px;overflow:hidden;background-color:#f5f5f5;border-radius:4px;-webkit-box-shadow:inset 0 1px 2px rgba(0,0,0,0.1);box-shadow:inset 0 1px 2px rgba(0,0,0,0.1)}.progress-bar{float:left;width:0;height:100%;font-size:12px;color:#fff;text-align:center;background-color:#428bca;-webkit-box-shadow:inset 0 -1px 0 rgba(0,0,0,0.15);box-shadow:inset 0 -1px 0 rgba(0,0,0,0.15);-webkit-transition:width .6s ease;transition:width .6s ease}.progress-striped .progress-bar{background-color:#428bca;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-size:40px 40px}.progress.active .progress-bar{-webkit-animation:progress-bar-stripes 2s linear infinite;-moz-animation:progress-bar-stripes 2s linear infinite;-ms-animation:progress-bar-stripes 2s linear infinite;-o-animation:progress-bar-stripes 2s linear infinite;animation:progress-bar-stripes 2s linear infinite}.progress-bar-danger{background-color:#d9534f}.progress-striped .progress-bar-danger{background-color:#d9534f;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.progress-bar-success{background-color:#5cb85c}.progress-striped .progress-bar-success{background-color:#5cb85c;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.progress-bar-warning{background-color:#f0ad4e}.progress-striped .progress-bar-warning{background-color:#f0ad4e;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.progress-bar-info{background-color:#5bc0de}.progress-striped .progress-bar-info{background-color:#5bc0de;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.accordion{margin-bottom:20px}.accordion-group{margin-bottom:2px;border:1px solid #e5e5e5;border-radius:4px}.accordion-heading{border-bottom:0}.accordion-heading .accordion-toggle{display:block;padding:8px 15px;cursor:pointer}.accordion-inner{padding:9px 15px;border-top:1px solid #e5e5e5}.carousel{position:relative}.carousel-inner{position:relative;width:100%;overflow:hidden}.carousel-inner>.item{position:relative;display:none;-webkit-transition:.6s ease-in-out left;transition:.6s ease-in-out left}.carousel-inner>.item>img,.carousel-inner>.item>a>img{display:inline-block;height:auto;max-width:100%;line-height:1}.carousel-inner>.active,.carousel-inner>.next,.carousel-inner>.prev{display:block}.carousel-inner>.active{left:0}.carousel-inner>.next,.carousel-inner>.prev{position:absolute;top:0;width:100%}.carousel-inner>.next{left:100%}.carousel-inner>.prev{left:-100%}.carousel-inner>.next.left,.carousel-inner>.prev.right{left:0}.carousel-inner>.active.left{left:-100%}.carousel-inner>.active.right{left:100%}.carousel-control{position:absolute;top:0;bottom:0;left:0;width:15%;font-size:20px;color:#fff;text-align:center;text-shadow:0 1px 2px rgba(0,0,0,0.6);opacity:.5;filter:alpha(opacity=50)}.carousel-control.left{background-color:rgba(0,0,0,0.0001);background-color:transparent;background-image:-webkit-gradient(linear,0 top,100% top,from(rgba(0,0,0,0.5)),to(rgba(0,0,0,0.0001)));background-image:-webkit-linear-gradient(left,color-stop(rgba(0,0,0,0.5) 0),color-stop(rgba(0,0,0,0.0001) 100%));background-image:-moz-linear-gradient(left,rgba(0,0,0,0.5) 0,rgba(0,0,0,0.0001) 100%);background-image:linear-gradient(to right,rgba(0,0,0,0.5) 0,rgba(0,0,0,0.0001) 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#80000000',endColorstr='#00000000',GradientType=1)}.carousel-control.right{right:0;left:auto;background-color:rgba(0,0,0,0.5);background-color:transparent;background-image:-webkit-gradient(linear,0 top,100% top,from(rgba(0,0,0,0.0001)),to(rgba(0,0,0,0.5)));background-image:-webkit-linear-gradient(left,color-stop(rgba(0,0,0,0.0001) 0),color-stop(rgba(0,0,0,0.5) 100%));background-image:-moz-linear-gradient(left,rgba(0,0,0,0.0001) 0,rgba(0,0,0,0.5) 100%);background-image:linear-gradient(to right,rgba(0,0,0,0.0001) 0,rgba(0,0,0,0.5) 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#00000000',endColorstr='#80000000',GradientType=1)}.carousel-control:hover,.carousel-control:focus{color:#fff;text-decoration:none;opacity:.9;filter:alpha(opacity=90)}.carousel-control .glyphicon,.carousel-control .icon-prev,.carousel-control .icon-next{position:absolute;top:50%;left:50%;z-index:5;display:inline-block;width:20px;height:20px;margin-top:-10px;margin-left:-10px;font-family:serif}.carousel-control .icon-prev:before{content:'\2039'}.carousel-control .icon-next:before{content:'\203a'}.carousel-indicators{position:absolute;bottom:10px;left:50%;z-index:15;width:120px;padding-left:0;margin-left:-60px;text-align:center;list-style:none}.carousel-indicators li{display:inline-block;width:10px;height:10px;margin:1px;text-indent:-999px;cursor:pointer;border:1px solid #fff;border-radius:10px}.carousel-indicators .active{width:12px;height:12px;margin:0;background-color:#fff}.carousel-caption{position:absolute;right:15%;bottom:20px;left:15%;z-index:10;padding-top:20px;padding-bottom:20px;color:#fff;text-align:center;text-shadow:0 1px 2px rgba(0,0,0,0.6)}.carousel-caption .btn{text-shadow:none}@media screen and (min-width:768px){.carousel-control .glyphicon,.carousel-control .icon-prev,.carousel-control .icon-next{width:30px;height:30px;margin-top:-15px;margin-left:-15px;font-size:30px}.carousel-caption{right:20%;left:20%;padding-bottom:30px}.carousel-indicators{bottom:20px}}.jumbotron{padding:30px;margin-bottom:30px;font-size:21px;font-weight:200;line-height:2.1428571435;color:inherit;background-color:#eee}.jumbotron h1{line-height:1;color:inherit}.jumbotron p{line-height:1.4}@media screen and (min-width:768px){.jumbotron{padding:50px 60px;border-radius:6px}.jumbotron h1{font-size:63px}}.clearfix:before,.clearfix:after{display:table;content:" "}.clearfix:after{clear:both}.pull-right{float:right}.pull-left{float:left}.hide{display:none!important}.show{display:block!important}.invisible{visibility:hidden}.text-hide{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0}.affix{position:fixed}@-ms-viewport{width:device-width}@media screen and (max-width:400px){@-ms-viewport{width:320px}}.hidden{display:none!important;visibility:hidden!important}.visible-sm{display:block!important}tr.visible-sm{display:table-row!important}th.visible-sm,td.visible-sm{display:table-cell!important}.visible-md{display:none!important}tr.visible-md{display:none!important}th.visible-md,td.visible-md{display:none!important}.visible-lg{display:none!important}tr.visible-lg{display:none!important}th.visible-lg,td.visible-lg{display:none!important}.hidden-sm{display:none!important}tr.hidden-sm{display:none!important}th.hidden-sm,td.hidden-sm{display:none!important}.hidden-md{display:block!important}tr.hidden-md{display:table-row!important}th.hidden-md,td.hidden-md{display:table-cell!important}.hidden-lg{display:block!important}tr.hidden-lg{display:table-row!important}th.hidden-lg,td.hidden-lg{display:table-cell!important}@media(min-width:768px) and (max-width:991px){.visible-sm{display:none!important}tr.visible-sm{display:none!important}th.visible-sm,td.visible-sm{display:none!important}.visible-md{display:block!important}tr.visible-md{display:table-row!important}th.visible-md,td.visible-md{display:table-cell!important}.visible-lg{display:none!important}tr.visible-lg{display:none!important}th.visible-lg,td.visible-lg{display:none!important}.hidden-sm{display:block!important}tr.hidden-sm{display:table-row!important}th.hidden-sm,td.hidden-sm{display:table-cell!important}.hidden-md{display:none!important}tr.hidden-md{display:none!important}th.hidden-md,td.hidden-md{display:none!important}.hidden-lg{display:block!important}tr.hidden-lg{display:table-row!important}th.hidden-lg,td.hidden-lg{display:table-cell!important}}@media(min-width:992px){.visible-sm{display:none!important}tr.visible-sm{display:none!important}th.visible-sm,td.visible-sm{display:none!important}.visible-md{display:none!important}tr.visible-md{display:none!important}th.visible-md,td.visible-md{display:none!important}.visible-lg{display:block!important}tr.visible-lg{display:table-row!important}th.visible-lg,td.visible-lg{display:table-cell!important}.hidden-sm{display:block!important}tr.hidden-sm{display:table-row!important}th.hidden-sm,td.hidden-sm{display:table-cell!important}.hidden-md{display:block!important}tr.hidden-md{display:table-row!important}th.hidden-md,td.hidden-md{display:table-cell!important}.hidden-lg{display:none!important}tr.hidden-lg{display:none!important}th.hidden-lg,td.hidden-lg{display:none!important}}.visible-print{display:none!important}tr.visible-print{display:none!important}th.visible-print,td.visible-print{display:none!important}@media print{.visible-print{display:block!important}tr.visible-print{display:table-row!important}th.visible-print,td.visible-print{display:table-cell!important}.hidden-print{display:none!important}tr.hidden-print{display:none!important}th.hidden-print,td.hidden-print{display:none!important}} </style> <!-- zepto --> <script type="text/javascript"> /* Zepto v1.1.2 - zepto event ajax form ie - zeptojs.com/license */ var Zepto=function(){function G(a){return a==null?String(a):z[A.call(a)]||"object"}function H(a){return G(a)=="function"}function I(a){return a!=null&&a==a.window}function J(a){return a!=null&&a.nodeType==a.DOCUMENT_NODE}function K(a){return G(a)=="object"}function L(a){return K(a)&&!I(a)&&Object.getPrototypeOf(a)==Object.prototype}function M(a){return a instanceof Array}function N(a){return typeof a.length=="number"}function O(a){return g.call(a,function(a){return a!=null})}function P(a){return a.length>0?c.fn.concat.apply([],a):a}function Q(a){return a.replace(/::/g,"/").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/_/g,"-").toLowerCase()}function R(a){return a in j?j[a]:j[a]=new RegExp("(^|\\s)"+a+"(\\s|$)")}function S(a,b){return typeof b=="number"&&!k[Q(a)]?b+"px":b}function T(a){var b,c;return i[a]||(b=h.createElement(a),h.body.appendChild(b),c=getComputedStyle(b,"").getPropertyValue("display"),b.parentNode.removeChild(b),c=="none"&&(c="block"),i[a]=c),i[a]}function U(a){return"children"in a?f.call(a.children):c.map(a.childNodes,function(a){if(a.nodeType==1)return a})}function V(c,d,e){for(b in d)e&&(L(d[b])||M(d[b]))?(L(d[b])&&!L(c[b])&&(c[b]={}),M(d[b])&&!M(c[b])&&(c[b]=[]),V(c[b],d[b],e)):d[b]!==a&&(c[b]=d[b])}function W(a,b){return b==null?c(a):c(a).filter(b)}function X(a,b,c,d){return H(b)?b.call(a,c,d):b}function Y(a,b,c){c==null?a.removeAttribute(b):a.setAttribute(b,c)}function Z(b,c){var d=b.className,e=d&&d.baseVal!==a;if(c===a)return e?d.baseVal:d;e?d.baseVal=c:b.className=c}function $(a){var b;try{return a?a=="true"||(a=="false"?!1:a=="null"?null:!/^0/.test(a)&&!isNaN(b=Number(a))?b:/^[\[\{]/.test(a)?c.parseJSON(a):a):a}catch(d){return a}}function _(a,b){b(a);for(var c in a.childNodes)_(a.childNodes[c],b)}var a,b,c,d,e=[],f=e.slice,g=e.filter,h=window.document,i={},j={},k={"column-count":1,columns:1,"font-weight":1,"line-height":1,opacity:1,"z-index":1,zoom:1},l=/^\s*<(\w+|!)[^>]*>/,m=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,n=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,o=/^(?:body|html)$/i,p=/([A-Z])/g,q=["val","css","html","text","data","width","height","offset"],r=["after","prepend","before","append"],s=h.createElement("table"),t=h.createElement("tr"),u={tr:h.createElement("tbody"),tbody:s,thead:s,tfoot:s,td:t,th:t,"*":h.createElement("div")},v=/complete|loaded|interactive/,w=/^\.([\w-]+)$/,x=/^#([\w-]*)$/,y=/^[\w-]*$/,z={},A=z.toString,B={},C,D,E=h.createElement("div"),F={tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"};return B.matches=function(a,b){if(!b||!a||a.nodeType!==1)return!1;var c=a.webkitMatchesSelector||a.mozMatchesSelector||a.oMatchesSelector||a.matchesSelector;if(c)return c.call(a,b);var d,e=a.parentNode,f=!e;return f&&(e=E).appendChild(a),d=~B.qsa(e,b).indexOf(a),f&&E.removeChild(a),d},C=function(a){return a.replace(/-+(.)?/g,function(a,b){return b?b.toUpperCase():""})},D=function(a){return g.call(a,function(b,c){return a.indexOf(b)==c})},B.fragment=function(b,d,e){var g,i,j;return m.test(b)&&(g=c(h.createElement(RegExp.$1))),g||(b.replace&&(b=b.replace(n,"<$1></$2>")),d===a&&(d=l.test(b)&&RegExp.$1),d in u||(d="*"),j=u[d],j.innerHTML=""+b,g=c.each(f.call(j.childNodes),function(){j.removeChild(this)})),L(e)&&(i=c(g),c.each(e,function(a,b){q.indexOf(a)>-1?i[a](b):i.attr(a,b)})),g},B.Z=function(a,b){return a=a||[],a.__proto__=c.fn,a.selector=b||"",a},B.isZ=function(a){return a instanceof B.Z},B.init=function(b,d){var e;if(!b)return B.Z();if(typeof b=="string"){b=b.trim();if(b[0]=="<"&&l.test(b))e=B.fragment(b,RegExp.$1,d),b=null;else{if(d!==a)return c(d).find(b);e=B.qsa(h,b)}}else{if(H(b))return c(h).ready(b);if(B.isZ(b))return b;if(M(b))e=O(b);else if(K(b))e=[b],b=null;else if(l.test(b))e=B.fragment(b.trim(),RegExp.$1,d),b=null;else{if(d!==a)return c(d).find(b);e=B.qsa(h,b)}}return B.Z(e,b)},c=function(a,b){return B.init(a,b)},c.extend=function(a){var b,c=f.call(arguments,1);return typeof a=="boolean"&&(b=a,a=c.shift()),c.forEach(function(c){V(a,c,b)}),a},B.qsa=function(a,b){var c,d=b[0]=="#",e=!d&&b[0]==".",g=d||e?b.slice(1):b,h=y.test(g);return J(a)&&h&&d?(c=a.getElementById(g))?[c]:[]:a.nodeType!==1&&a.nodeType!==9?[]:f.call(h&&!d?e?a.getElementsByClassName(g):a.getElementsByTagName(b):a.querySelectorAll(b))},c.contains=function(a,b){return a!==b&&a.contains(b)},c.type=G,c.isFunction=H,c.isWindow=I,c.isArray=M,c.isPlainObject=L,c.isEmptyObject=function(a){var b;for(b in a)return!1;return!0},c.inArray=function(a,b,c){return e.indexOf.call(b,a,c)},c.camelCase=C,c.trim=function(a){return a==null?"":String.prototype.trim.call(a)},c.uuid=0,c.support={},c.expr={},c.map=function(a,b){var c,d=[],e,f;if(N(a))for(e=0;e<a.length;e++)c=b(a[e],e),c!=null&&d.push(c);else for(f in a)c=b(a[f],f),c!=null&&d.push(c);return P(d)},c.each=function(a,b){var c,d;if(N(a)){for(c=0;c<a.length;c++)if(b.call(a[c],c,a[c])===!1)return a}else for(d in a)if(b.call(a[d],d,a[d])===!1)return a;return a},c.grep=function(a,b){return g.call(a,b)},window.JSON&&(c.parseJSON=JSON.parse),c.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){z["[object "+b+"]"]=b.toLowerCase()}),c.fn={forEach:e.forEach,reduce:e.reduce,push:e.push,sort:e.sort,indexOf:e.indexOf,concat:e.concat,map:function(a){return c(c.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return c(f.apply(this,arguments))},ready:function(a){return v.test(h.readyState)&&h.body?a(c):h.addEventListener("DOMContentLoaded",function(){a(c)},!1),this},get:function(b){return b===a?f.call(this):this[b>=0?b:b+this.length]},toArray:function(){return this.get()},size:function(){return this.length},remove:function(){return this.each(function(){this.parentNode!=null&&this.parentNode.removeChild(this)})},each:function(a){return e.every.call(this,function(b,c){return a.call(b,c,b)!==!1}),this},filter:function(a){return H(a)?this.not(this.not(a)):c(g.call(this,function(b){return B.matches(b,a)}))},add:function(a,b){return c(D(this.concat(c(a,b))))},is:function(a){return this.length>0&&B.matches(this[0],a)},not:function(b){var d=[];if(H(b)&&b.call!==a)this.each(function(a){b.call(this,a)||d.push(this)});else{var e=typeof b=="string"?this.filter(b):N(b)&&H(b.item)?f.call(b):c(b);this.forEach(function(a){e.indexOf(a)<0&&d.push(a)})}return c(d)},has:function(a){return this.filter(function(){return K(a)?c.contains(this,a):c(this).find(a).size()})},eq:function(a){return a===-1?this.slice(a):this.slice(a,+a+1)},first:function(){var a=this[0];return a&&!K(a)?a:c(a)},last:function(){var a=this[this.length-1];return a&&!K(a)?a:c(a)},find:function(a){var b,d=this;return typeof a=="object"?b=c(a).filter(function(){var a=this;return e.some.call(d,function(b){return c.contains(b,a)})}):this.length==1?b=c(B.qsa(this[0],a)):b=this.map(function(){return B.qsa(this,a)}),b},closest:function(a,b){var d=this[0],e=!1;typeof a=="object"&&(e=c(a));while(d&&!(e?e.indexOf(d)>=0:B.matches(d,a)))d=d!==b&&!J(d)&&d.parentNode;return c(d)},parents:function(a){var b=[],d=this;while(d.length>0)d=c.map(d,function(a){if((a=a.parentNode)&&!J(a)&&b.indexOf(a)<0)return b.push(a),a});return W(b,a)},parent:function(a){return W(D(this.pluck("parentNode")),a)},children:function(a){return W(this.map(function(){return U(this)}),a)},contents:function(){return this.map(function(){return f.call(this.childNodes)})},siblings:function(a){return W(this.map(function(a,b){return g.call(U(b.parentNode),function(a){return a!==b})}),a)},empty:function(){return this.each(function(){this.innerHTML=""})},pluck:function(a){return c.map(this,function(b){return b[a]})},show:function(){return this.each(function(){this.style.display=="none"&&(this.style.display=""),getComputedStyle(this,"").getPropertyValue("display")=="none"&&(this.style.display=T(this.nodeName))})},replaceWith:function(a){return this.before(a).remove()},wrap:function(a){var b=H(a);if(this[0]&&!b)var d=c(a).get(0),e=d.parentNode||this.length>1;return this.each(function(f){c(this).wrapAll(b?a.call(this,f):e?d.cloneNode(!0):d)})},wrapAll:function(a){if(this[0]){c(this[0]).before(a=c(a));var b;while((b=a.children()).length)a=b.first();c(a).append(this)}return this},wrapInner:function(a){var b=H(a);return this.each(function(d){var e=c(this),f=e.contents(),g=b?a.call(this,d):a;f.length?f.wrapAll(g):e.append(g)})},unwrap:function(){return this.parent().each(function(){c(this).replaceWith(c(this).children())}),this},clone:function(){return this.map(function(){return this.cloneNode(!0)})},hide:function(){return this.css("display","none")},toggle:function(b){return this.each(function(){var d=c(this);(b===a?d.css("display")=="none":b)?d.show():d.hide()})},prev:function(a){return c(this.pluck("previousElementSibling")).filter(a||"*")},next:function(a){return c(this.pluck("nextElementSibling")).filter(a||"*")},html:function(a){return arguments.length===0?this.length>0?this[0].innerHTML:null:this.each(function(b){var d=this.innerHTML;c(this).empty().append(X(this,a,b,d))})},text:function(b){return arguments.length===0?this.length>0?this[0].textContent:null:this.each(function(){this.textContent=b===a?"":""+b})},attr:function(c,d){var e;return typeof c=="string"&&d===a?this.length==0||this[0].nodeType!==1?a:c=="value"&&this[0].nodeName=="INPUT"?this.val():!(e=this[0].getAttribute(c))&&c in this[0]?this[0][c]:e:this.each(function(a){if(this.nodeType!==1)return;if(K(c))for(b in c)Y(this,b,c[b]);else Y(this,c,X(this,d,a,this.getAttribute(c)))})},removeAttr:function(a){return this.each(function(){this.nodeType===1&&Y(this,a)})},prop:function(b,c){return b=F[b]||b,c===a?this[0]&&this[0][b]:this.each(function(a){this[b]=X(this,c,a,this[b])})},data:function(b,c){var d=this.attr("data-"+b.replace(p,"-$1").toLowerCase(),c);return d!==null?$(d):a},val:function(a){return arguments.length===0?this[0]&&(this[0].multiple?c(this[0]).find("option").filter(function(){return this.selected}).pluck("value"):this[0].value):this.each(function(b){this.value=X(this,a,b,this.value)})},offset:function(a){if(a)return this.each(function(b){var d=c(this),e=X(this,a,b,d.offset()),f=d.offsetParent().offset(),g={top:e.top-f.top,left:e.left-f.left};d.css("position")=="static"&&(g.position="relative"),d.css(g)});if(this.length==0)return null;var b=this[0].getBoundingClientRect();return{left:b.left+window.pageXOffset,top:b.top+window.pageYOffset,width:Math.round(b.width),height:Math.round(b.height)}},css:function(a,d){if(arguments.length<2){var e=this[0],f=getComputedStyle(e,"");if(!e)return;if(typeof a=="string")return e.style[C(a)]||f.getPropertyValue(a);if(M(a)){var g={};return c.each(M(a)?a:[a],function(a,b){g[b]=e.style[C(b)]||f.getPropertyValue(b)}),g}}var h="";if(G(a)=="string")!d&&d!==0?this.each(function(){this.style.removeProperty(Q(a))}):h=Q(a)+":"+S(a,d);else for(b in a)!a[b]&&a[b]!==0?this.each(function(){this.style.removeProperty(Q(b))}):h+=Q(b)+":"+S(b,a[b])+";";return this.each(function(){this.style.cssText+=";"+h})},index:function(a){return a?this.indexOf(c(a)[0]):this.parent().children().indexOf(this[0])},hasClass:function(a){return a?e.some.call(this,function(a){return this.test(Z(a))},R(a)):!1},addClass:function(a){return a?this.each(function(b){d=[];var e=Z(this),f=X(this,a,b,e);f.split(/\s+/g).forEach(function(a){c(this).hasClass(a)||d.push(a)},this),d.length&&Z(this,e+(e?" ":"")+d.join(" "))}):this},removeClass:function(b){return this.each(function(c){if(b===a)return Z(this,"");d=Z(this),X(this,b,c,d).split(/\s+/g).forEach(function(a){d=d.replace(R(a)," ")}),Z(this,d.trim())})},toggleClass:function(b,d){return b?this.each(function(e){var f=c(this),g=X(this,b,e,Z(this));g.split(/\s+/g).forEach(function(b){(d===a?!f.hasClass(b):d)?f.addClass(b):f.removeClass(b)})}):this},scrollTop:function(b){if(!this.length)return;var c="scrollTop"in this[0];return b===a?c?this[0].scrollTop:this[0].pageYOffset:this.each(c?function(){this.scrollTop=b}:function(){this.scrollTo(this.scrollX,b)})},scrollLeft:function(b){if(!this.length)return;var c="scrollLeft"in this[0];return b===a?c?this[0].scrollLeft:this[0].pageXOffset:this.each(c?function(){this.scrollLeft=b}:function(){this.scrollTo(b,this.scrollY)})},position:function(){if(!this.length)return;var a=this[0],b=this.offsetParent(),d=this.offset(),e=o.test(b[0].nodeName)?{top:0,left:0}:b.offset();return d.top-=parseFloat(c(a).css("margin-top"))||0,d.left-=parseFloat(c(a).css("margin-left"))||0,e.top+=parseFloat(c(b[0]).css("border-top-width"))||0,e.left+=parseFloat(c(b[0]).css("border-left-width"))||0,{top:d.top-e.top,left:d.left-e.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||h.body;while(a&&!o.test(a.nodeName)&&c(a).css("position")=="static")a=a.offsetParent;return a})}},c.fn.detach=c.fn.remove,["width","height"].forEach(function(b){var d=b.replace(/./,function(a){return a[0].toUpperCase()});c.fn[b]=function(e){var f,g=this[0];return e===a?I(g)?g["inner"+d]:J(g)?g.documentElement["scroll"+d]:(f=this.offset())&&f[b]:this.each(function(a){g=c(this),g.css(b,X(this,e,a,g[b]()))})}}),r.forEach(function(a,b){var d=b%2;c.fn[a]=function(){var a,e=c.map(arguments,function(b){return a=G(b),a=="object"||a=="array"||b==null?b:B.fragment(b)}),f,g=this.length>1;return e.length<1?this:this.each(function(a,h){f=d?h:h.parentNode,h=b==0?h.nextSibling:b==1?h.firstChild:b==2?h:null,e.forEach(function(a){if(g)a=a.cloneNode(!0);else if(!f)return c(a).remove();_(f.insertBefore(a,h),function(a){a.nodeName!=null&&a.nodeName.toUpperCase()==="SCRIPT"&&(!a.type||a.type==="text/javascript")&&!a.src&&window.eval.call(window,a.innerHTML)})})})},c.fn[d?a+"To":"insert"+(b?"Before":"After")]=function(b){return c(b)[a](this),this}}),B.Z.prototype=c.fn,B.uniq=D,B.deserializeValue=$,c.zepto=B,c}();window.Zepto=Zepto,window.$===undefined&&(window.$=Zepto),function(a){function m(a){return a._zid||(a._zid=c++)}function n(a,b,c,d){b=o(b);if(b.ns)var e=p(b.ns);return(h[m(a)]||[]).filter(function(a){return a&&(!b.e||a.e==b.e)&&(!b.ns||e.test(a.ns))&&(!c||m(a.fn)===m(c))&&(!d||a.sel==d)})}function o(a){var b=(""+a).split(".");return{e:b[0],ns:b.slice(1).sort().join(" ")}}function p(a){return new RegExp("(?:^| )"+a.replace(" "," .* ?")+"(?: |$)")}function q(a,b){return a.del&&!j&&a.e in k||!!b}function r(a){return l[a]||j&&k[a]||a}function s(b,c,e,f,g,i,j){var k=m(b),n=h[k]||(h[k]=[]);c.split(/\s/).forEach(function(c){if(c=="ready")return a(document).ready(e);var h=o(c);h.fn=e,h.sel=g,h.e in l&&(e=function(b){var c=b.relatedTarget;if(!c||c!==this&&!a.contains(this,c))return h.fn.apply(this,arguments)}),h.del=i;var k=i||e;h.proxy=function(a){a=y(a);if(a.isImmediatePropagationStopped())return;a.data=f;var c=k.apply(b,a._args==d?[a]:[a].concat(a._args));return c===!1&&(a.preventDefault(),a.stopPropagation()),c},h.i=n.length,n.push(h),"addEventListener"in b&&b.addEventListener(r(h.e),h.proxy,q(h,j))})}function t(a,b,c,d,e){var f=m(a);(b||"").split(/\s/).forEach(function(b){n(a,b,c,d).forEach(function(b){delete h[f][b.i],"removeEventListener"in a&&a.removeEventListener(r(b.e),b.proxy,q(b,e))})})}function y(b,c){if(c||!b.isDefaultPrevented){c||(c=b),a.each(x,function(a,d){var e=c[a];b[a]=function(){return this[d]=u,e&&e.apply(c,arguments)},b[d]=v});if(c.defaultPrevented!==d?c.defaultPrevented:"returnValue"in c?c.returnValue===!1:c.getPreventDefault&&c.getPreventDefault())b.isDefaultPrevented=u}return b}function z(a){var b,c={originalEvent:a};for(b in a)!w.test(b)&&a[b]!==d&&(c[b]=a[b]);return y(c,a)}var b=a.zepto.qsa,c=1,d,e=Array.prototype.slice,f=a.isFunction,g=function(a){return typeof a=="string"},h={},i={},j="onfocusin"in window,k={focus:"focusin",blur:"focusout"},l={mouseenter:"mouseover",mouseleave:"mouseout"};i.click=i.mousedown=i.mouseup=i.mousemove="MouseEvents",a.event={add:s,remove:t},a.proxy=function(b,c){if(f(b)){var d=function(){return b.apply(c,arguments)};return d._zid=m(b),d}if(g(c))return a.proxy(b[c],b);throw new TypeError("expected function")},a.fn.bind=function(a,b,c){return this.on(a,b,c)},a.fn.unbind=function(a,b){return this.off(a,b)},a.fn.one=function(a,b,c,d){return this.on(a,b,c,d,1)};var u=function(){return!0},v=function(){return!1},w=/^([A-Z]|returnValue$|layer[XY]$)/,x={preventDefault:"isDefaultPrevented",stopImmediatePropagation:"isImmediatePropagationStopped",stopPropagation:"isPropagationStopped"};a.fn.delegate=function(a,b,c){return this.on(b,a,c)},a.fn.undelegate=function(a,b,c){return this.off(b,a,c)},a.fn.live=function(b,c){return a(document.body).delegate(this.selector,b,c),this},a.fn.die=function(b,c){return a(document.body).undelegate(this.selector,b,c),this},a.fn.on=function(b,c,h,i,j){var k,l,m=this;if(b&&!g(b))return a.each(b,function(a,b){m.on(a,c,h,b,j)}),m;!g(c)&&!f(i)&&i!==!1&&(i=h,h=c,c=d);if(f(h)||h===!1)i=h,h=d;return i===!1&&(i=v),m.each(function(d,f){j&&(k=function(a){return t(f,a.type,i),i.apply(this,arguments)}),c&&(l=function(b){var d,g=a(b.target).closest(c,f).get(0);if(g&&g!==f)return d=a.extend(z(b),{currentTarget:g,liveFired:f}),(k||i).apply(g,[d].concat(e.call(arguments,1)))}),s(f,b,i,h,c,l||k)})},a.fn.off=function(b,c,e){var h=this;return b&&!g(b)?(a.each(b,function(a,b){h.off(a,c,b)}),h):(!g(c)&&!f(e)&&e!==!1&&(e=c,c=d),e===!1&&(e=v),h.each(function(){t(this,b,e,c)}))},a.fn.trigger=function(b,c){return b=g(b)||a.isPlainObject(b)?a.Event(b):y(b),b._args=c,this.each(function(){"dispatchEvent"in this?this.dispatchEvent(b):a(this).triggerHandler(b,c)})},a.fn.triggerHandler=function(b,c){var d,e;return this.each(function(f,h){d=z(g(b)?a.Event(b):b),d._args=c,d.target=h,a.each(n(h,b.type||b),function(a,b){e=b.proxy(d);if(d.isImmediatePropagationStopped())return!1})}),e},"focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select keydown keypress keyup error".split(" ").forEach(function(b){a.fn[b]=function(a){return a?this.bind(b,a):this.trigger(b)}}),["focus","blur"].forEach(function(b){a.fn[b]=function(a){return a?this.bind(b,a):this.each(function(){try{this[b]()}catch(a){}}),this}}),a.Event=function(a,b){g(a)||(b=a,a=b.type);var c=document.createEvent(i[a]||"Events"),d=!0;if(b)for(var e in b)e=="bubbles"?d=!!b[e]:c[e]=b[e];return c.initEvent(a,d,!0),y(c)}}(Zepto),function($){function triggerAndReturn(a,b,c){var d=$.Event(b);return $(a).trigger(d,c),!d.isDefaultPrevented()}function triggerGlobal(a,b,c,d){if(a.global)return triggerAndReturn(b||document,c,d)}function ajaxStart(a){a.global&&$.active++===0&&triggerGlobal(a,null,"ajaxStart")}function ajaxStop(a){a.global&&!--$.active&&triggerGlobal(a,null,"ajaxStop")}function ajaxBeforeSend(a,b){var c=b.context;if(b.beforeSend.call(c,a,b)===!1||triggerGlobal(b,c,"ajaxBeforeSend",[a,b])===!1)return!1;triggerGlobal(b,c,"ajaxSend",[a,b])}function ajaxSuccess(a,b,c,d){var e=c.context,f="success";c.success.call(e,a,f,b),d&&d.resolveWith(e,[a,f,b]),triggerGlobal(c,e,"ajaxSuccess",[b,c,a]),ajaxComplete(f,b,c)}function ajaxError(a,b,c,d,e){var f=d.context;d.error.call(f,c,b,a),e&&e.rejectWith(f,[c,b,a]),triggerGlobal(d,f,"ajaxError",[c,d,a||b]),ajaxComplete(b,c,d)}function ajaxComplete(a,b,c){var d=c.context;c.complete.call(d,b,a),triggerGlobal(c,d,"ajaxComplete",[b,c]),ajaxStop(c)}function empty(){}function mimeToDataType(a){return a&&(a=a.split(";",2)[0]),a&&(a==htmlType?"html":a==jsonType?"json":scriptTypeRE.test(a)?"script":xmlTypeRE.test(a)&&"xml")||"text"}function appendQuery(a,b){return b==""?a:(a+"&"+b).replace(/[&?]{1,2}/,"?")}function serializeData(a){a.processData&&a.data&&$.type(a.data)!="string"&&(a.data=$.param(a.data,a.traditional)),a.data&&(!a.type||a.type.toUpperCase()=="GET")&&(a.url=appendQuery(a.url,a.data),a.data=undefined)}function parseArguments(a,b,c,d){var e=!$.isFunction(b);return{url:a,data:e?b:undefined,success:e?$.isFunction(c)?c:undefined:b,dataType:e?d||c:c}}function serialize(a,b,c,d){var e,f=$.isArray(b),g=$.isPlainObject(b);$.each(b,function(b,h){e=$.type(h),d&&(b=c?d:d+"["+(g||e=="object"||e=="array"?b:"")+"]"),!d&&f?a.add(h.name,h.value):e=="array"||!c&&e=="object"?serialize(a,h,c,b):a.add(b,h)})}var jsonpID=0,document=window.document,key,name,rscript=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,scriptTypeRE=/^(?:text|application)\/javascript/i,xmlTypeRE=/^(?:text|application)\/xml/i,jsonType="application/json",htmlType="text/html",blankRE=/^\s*$/;$.active=0,$.ajaxJSONP=function(a,b){if("type"in a){var c=a.jsonpCallback,d=($.isFunction(c)?c():c)||"jsonp"+ ++jsonpID,e=document.createElement("script"),f=window[d],g,h=function(a){$(e).triggerHandler("error",a||"abort")},i={abort:h},j;return b&&b.promise(i),$(e).on("load error",function(c,h){clearTimeout(j),$(e).off().remove(),c.type=="error"||!g?ajaxError(null,h||"error",i,a,b):ajaxSuccess(g[0],i,a,b),window[d]=f,g&&$.isFunction(f)&&f(g[0]),f=g=undefined}),ajaxBeforeSend(i,a)===!1?(h("abort"),i):(window[d]=function(){g=arguments},e.src=a.url.replace(/=\?/,"="+d),document.head.appendChild(e),a.timeout>0&&(j=setTimeout(function(){h("timeout")},a.timeout)),i)}return $.ajax(a)},$.ajaxSettings={type:"GET",beforeSend:empty,success:empty,error:empty,complete:empty,context:null,global:!0,xhr:function(){return new window.XMLHttpRequest},accepts:{script:"text/javascript, application/javascript, application/x-javascript",json:jsonType,xml:"application/xml, text/xml",html:htmlType,text:"text/plain"},crossDomain:!1,timeout:0,processData:!0,cache:!0},$.ajax=function(options){var settings=$.extend({},options||{}),deferred=$.Deferred&&$.Deferred();for(key in $.ajaxSettings)settings[key]===undefined&&(settings[key]=$.ajaxSettings[key]);ajaxStart(settings),settings.crossDomain||(settings.crossDomain=/^([\w-]+:)?\/\/([^\/]+)/.test(settings.url)&&RegExp.$2!=window.location.host),settings.url||(settings.url=window.location.toString()),serializeData(settings),settings.cache===!1&&(settings.url=appendQuery(settings.url,"_="+Date.now()));var dataType=settings.dataType,hasPlaceholder=/=\?/.test(settings.url);if(dataType=="jsonp"||hasPlaceholder)return hasPlaceholder||(settings.url=appendQuery(settings.url,settings.jsonp?settings.jsonp+"=?":settings.jsonp===!1?"":"callback=?")),$.ajaxJSONP(settings,deferred);var mime=settings.accepts[dataType],headers={},setHeader=function(a,b){headers[a.toLowerCase()]=[a,b]},protocol=/^([\w-]+:)\/\//.test(settings.url)?RegExp.$1:window.location.protocol,xhr=settings.xhr(),nativeSetHeader=xhr.setRequestHeader,abortTimeout;deferred&&deferred.promise(xhr),settings.crossDomain||setHeader("X-Requested-With","XMLHttpRequest"),setHeader("Accept",mime||"*/*");if(mime=settings.mimeType||mime)mime.indexOf(",")>-1&&(mime=mime.split(",",2)[0]),xhr.overrideMimeType&&xhr.overrideMimeType(mime);(settings.contentType||settings.contentType!==!1&&settings.data&&settings.type.toUpperCase()!="GET")&&setHeader("Content-Type",settings.contentType||"application/x-www-form-urlencoded");if(settings.headers)for(name in settings.headers)setHeader(name,settings.headers[name]);xhr.setRequestHeader=setHeader,xhr.onreadystatechange=function(){if(xhr.readyState==4){xhr.onreadystatechange=empty,clearTimeout(abortTimeout);var result,error=!1;if(xhr.status>=200&&xhr.status<300||xhr.status==304||xhr.status==0&&protocol=="file:"){dataType=dataType||mimeToDataType(settings.mimeType||xhr.getResponseHeader("content-type")),result=xhr.responseText;try{dataType=="script"?(1,eval)(result):dataType=="xml"?result=xhr.responseXML:dataType=="json"&&(result=blankRE.test(result)?null:$.parseJSON(result))}catch(e){error=e}error?ajaxError(error,"parsererror",xhr,settings,deferred):ajaxSuccess(result,xhr,settings,deferred)}else ajaxError(xhr.statusText||null,xhr.status?"error":"abort",xhr,settings,deferred)}};if(ajaxBeforeSend(xhr,settings)===!1)return xhr.abort(),ajaxError(null,"abort",xhr,settings,deferred),xhr;if(settings.xhrFields)for(name in settings.xhrFields)xhr[name]=settings.xhrFields[name];var async="async"in settings?settings.async:!0;xhr.open(settings.type,settings.url,async,settings.username,settings.password);for(name in headers)nativeSetHeader.apply(xhr,headers[name]);return settings.timeout>0&&(abortTimeout=setTimeout(function(){xhr.onreadystatechange=empty,xhr.abort(),ajaxError(null,"timeout",xhr,settings,deferred)},settings.timeout)),xhr.send(settings.data?settings.data:null),xhr},$.get=function(a,b,c,d){return $.ajax(parseArguments.apply(null,arguments))},$.post=function(a,b,c,d){var e=parseArguments.apply(null,arguments);return e.type="POST",$.ajax(e)},$.getJSON=function(a,b,c){var d=parseArguments.apply(null,arguments);return d.dataType="json",$.ajax(d)},$.fn.load=function(a,b,c){if(!this.length)return this;var d=this,e=a.split(/\s/),f,g=parseArguments(a,b,c),h=g.success;return e.length>1&&(g.url=e[0],f=e[1]),g.success=function(a){d.html(f?$("<div>").html(a.replace(rscript,"")).find(f):a),h&&h.apply(d,arguments)},$.ajax(g),this};var escape=encodeURIComponent;$.param=function(a,b){var c=[];return c.add=function(a,b){this.push(escape(a)+"="+escape(b))},serialize(c,a,b),c.join("&").replace(/%20/g,"+")}}(Zepto),function(a){a.fn.serializeArray=function(){var b=[],c;return a([].slice.call(this.get(0).elements)).each(function(){c=a(this);var d=c.attr("type");this.nodeName.toLowerCase()!="fieldset"&&!this.disabled&&d!="submit"&&d!="reset"&&d!="button"&&(d!="radio"&&d!="checkbox"||this.checked)&&b.push({name:c.attr("name"),value:c.val()})}),b},a.fn.serialize=function(){var a=[];return this.serializeArray().forEach(function(b){a.push(encodeURIComponent(b.name)+"="+encodeURIComponent(b.value))}),a.join("&")},a.fn.submit=function(b){if(b)this.bind("submit",b);else if(this.length){var c=a.Event("submit");this.eq(0).trigger(c),c.isDefaultPrevented()||this.get(0).submit()}return this}}(Zepto),function(a){"__proto__"in{}||a.extend(a.zepto,{Z:function(b,c){return b=b||[],a.extend(b,a.fn),b.selector=c||"",b.__Z=!0,b},isZ:function(b){return a.type(b)==="array"&&"__Z"in b}});try{getComputedStyle(undefined)}catch(b){var c=getComputedStyle;window.getComputedStyle=function(a){try{return c(a)}catch(b){return null}}}}(Zepto) </script> <style type="text/css"> body { background: #F9F9F9; font-size: 14px; line-height: 22px; font-family: Helvetica Neue, Helvetica, Arial; } a { color: #000; text-decoration: underline; } li ul, li ol{ margin: 0; } .anchor { cursor: pointer; } .anchor .anchor_char{ visibility: hidden; padding-left: 0.2em; font-size: 0.9em; opacity: 0.5; } .anchor:hover .anchor_char{ visibility: visible; } .sidebar{ background: #FFF; position: fixed; z-index: 10; top: 0; left: 0; bottom: 0; width: 230px; overflow-y: auto; overflow-x: hidden; padding: 15px 0 30px 30px; border-right: 1px solid #bbb; font-family: "Lucida Grande", "Lucida Sans Unicode", Helvetica, Arial, sans-serif !important; } .sidebar ul{ margin: 0; list-style: none; padding: 0; } .sidebar ul a:hover { text-decoration: underline; color: #333; } .sidebar > ul > li { margin-top: 15px; } .sidebar > ul > li > a { font-weight: bold; } .sidebar ul ul { margin-top: 5px; font-size: 11px; line-height: 14px; } .sidebar ul ul li:before { content: "- "; } .sidebar ul ul li { margin-bottom: 3px; } .sidebar ul ul li a { text-decoration: none; } .toggle_sidebar_button{ display: none; position: fixed; z-index: 11; top: 0; width: 44px; height: 44px; background: #000; background: rgba(0,0,0,0.7); margin-left: 230px; } .toggle_sidebar_button:hover { background: rgba(0,0,0,1); cursor: pointer; } .toggle_sidebar_button .line{ height: 2px; width: 21px; margin-left: 11px; margin-top: 5px; background: #FFF; } .toggle_sidebar_button .line:first-child { margin-top: 15px; } .main_container { width: 100%; padding-left: 260px; margin: 30px; margin-left: 0px; padding-right: 30px; } .main_container p, ul{ margin: 25px 0; } .main_container ul { list-style: circle; font-size: 13px; line-height: 18px; padding-left: 15px; } pre { font-size: 12px; border: 4px solid #bbb; border-top: 0; border-bottom: 0; margin: 0px 0 25px; padding-top: 0px; padding-bottom: 0px; font-family: Monaco, Consolas, "Lucida Console", monospace; line-height: 18px; font-style: normal; background: none; border-radius: 0px; overflow-x: scroll; word-wrap: normal; white-space: pre; } .main_container { width: 840px; } .main_container p, ul, pre { width: 100%; } code { padding: 0px 3px; color: #333; background: #fff; border: 1px solid #ddd; zoom: 1; white-space: nowrap; border-radius: 0; font-family: Monaco, Consolas, "Lucida Console", monospace; font-size: 12px; line-height: 18px; font-style: normal; } em { font-size: 12px; line-height: 18px; } @media (max-width: 820px) { .sidebar { display: none; } .main_container { padding: 0px; width: 100%; } .main_container > *{ padding-left: 10px; padding-right: 10px; } .main_container > ul, .main_container > ol { padding-left: 27px; } .force_show_sidebar .main_container { display: none; } .force_show_sidebar .sidebar { width: 100%; } .force_show_sidebar .sidebar a{ font-size: 1.5em; line-height: 1.5em; } .force_show_sidebar .toggle_sidebar_button { right: 0; } .force_show_sidebar .toggle_sidebar_button .line:first-child, .force_show_sidebar .toggle_sidebar_button .line:last-child { visibility: hidden; } .toggle_sidebar_button { margin-left: 0px; display: block; } pre { font-size: 12px; border: 1px solid #bbb; border-left: 0; border-right: 0; padding: 9px; background: #FFF; } code { word-wrap: break-word; white-space: normal; } } .force_show_sidebar .sidebar { display: block; } .force_show_sidebar .main_container { padding-left: 260px; } .force_show_sidebar .toggle_sidebar_button{ margin-left: 230px; } </style> <script type="text/javascript"> $(function(){ $('.toggle_sidebar_button').on('click', function(){ $('body').toggleClass('force_show_sidebar'); }); // hide sidebar on every click in menu (if small screen) $('.sidebar').find('a').on('click', function(){ $('body').removeClass('force_show_sidebar'); }); // add anchors $.each($('.main_container').find('h1,h2,h3,h4,h5,h6'), function(key, item){ if ($(item).attr('id')) { $(item).addClass('anchor'); $(item).append($('<span class="anchor_char">¶</span>')) $(item).on('click', function(){ window.location = '#' + $(item).attr('id'); }) } }); // remove <code> tag inside of <pre> $.each($('pre > code'), function(key, item){ $(item).parent().html($(item).html()) }) }) </script> </head> <body> <a class="toggle_sidebar_button"> <div class="line"></div> <div class="line"></div> <div class="line"></div> </a> <div class="sidebar"> <!-- toc --> </div> <div class="main_container"> <!-- main_content --> </div> </body> </html>''' def force_text(text): if isinstance(text, unicode): return text else: return text.decode('utf-8') class BackDoc(object): def __init__(self, markdown_converter, template_html, stdin, stdout): self.markdown_converter = markdown_converter self.template_html = force_text(template_html) self.stdin = stdin self.stdout = stdout self.parser = self.get_parser() def run(self, argv): kwargs = self.get_kwargs(argv) self.stdout.write(self.get_result_html(**kwargs)) def get_kwargs(self, argv): parsed = dict(self.parser.parse_args(argv)._get_kwargs()) return self.prepare_kwargs_from_parsed_data(parsed) def prepare_kwargs_from_parsed_data(self, parsed): kwargs = {} kwargs['title'] = force_text(parsed.get('title') or 'Documentation') if parsed.get('source'): kwargs['markdown_src'] = open(parsed['source'], 'r').read() else: kwargs['markdown_src'] = self.stdin.read() kwargs['markdown_src'] = force_text(kwargs['markdown_src'] or '') return kwargs def get_result_html(self, title, markdown_src): response = self.get_converted_to_html_response(markdown_src) return ( self.template_html.replace('<!-- title -->', title) .replace('<!-- toc -->', response.toc_html and force_text(response.toc_html) or '') .replace('<!-- main_content -->', force_text(response)) ) def get_converted_to_html_response(self, markdown_src): return self.markdown_converter.convert(markdown_src) def get_parser(self): parser = argparse.ArgumentParser() parser.add_argument( '-t', '--title', help='Documentation title header', required=False, ) parser.add_argument( '-s', '--source', help='Markdown source file path', required=False, ) return parser if __name__ == '__main__': BackDoc( markdown_converter=Markdown(extras=['toc']), template_html=template_html, stdin=sys.stdin, stdout=sys.stdout ).run(argv=sys.argv[1:])
chibisov/drf-extensions
docs/backdoc.py
Markdown.convert
python
def convert(self, text): # Main function. The order in which other subs are called here is # essential. Link and image substitutions need to happen before # _EscapeSpecialChars(), so that any *'s or _'s in the <a> # and <img> tags get encoded. # Clear the global hashes. If we don't clear these, you get conflicts # from other articles when generating a page which contains more than # one article (e.g. an index page that shows the N most recent # articles): self.reset() if not isinstance(text, unicode): #TODO: perhaps shouldn't presume UTF-8 for string input? text = unicode(text, 'utf-8') if self.use_file_vars: # Look for emacs-style file variable hints. emacs_vars = self._get_emacs_vars(text) if "markdown-extras" in emacs_vars: splitter = re.compile("[ ,]+") for e in splitter.split(emacs_vars["markdown-extras"]): if '=' in e: ename, earg = e.split('=', 1) try: earg = int(earg) except ValueError: pass else: ename, earg = e, None self.extras[ename] = earg # Standardize line endings: text = re.sub("\r\n|\r", "\n", text) # Make sure $text ends with a couple of newlines: text += "\n\n" # Convert all tabs to spaces. text = self._detab(text) # Strip any lines consisting only of spaces and tabs. # This makes subsequent regexen easier to write, because we can # match consecutive blank lines with /\n+/ instead of something # contorted like /[ \t]*\n+/ . text = self._ws_only_line_re.sub("", text) # strip metadata from head and extract if "metadata" in self.extras: text = self._extract_metadata(text) text = self.preprocess(text) if self.safe_mode: text = self._hash_html_spans(text) # Turn block-level HTML blocks into hash entries text = self._hash_html_blocks(text, raw=True) # Strip link definitions, store in hashes. if "footnotes" in self.extras: # Must do footnotes first because an unlucky footnote defn # looks like a link defn: # [^4]: this "looks like a link defn" text = self._strip_footnote_definitions(text) text = self._strip_link_definitions(text) text = self._run_block_gamut(text) if "footnotes" in self.extras: text = self._add_footnotes(text) text = self.postprocess(text) text = self._unescape_special_chars(text) if self.safe_mode: text = self._unhash_html_spans(text) if "nofollow" in self.extras: text = self._a_nofollow.sub(r'<\1 rel="nofollow"\2', text) text += "\n" rv = UnicodeWithAttrs(text) if "toc" in self.extras: rv._toc = self._toc if "metadata" in self.extras: rv.metadata = self.metadata return rv
Convert the given text.
train
https://github.com/chibisov/drf-extensions/blob/1d28a4b28890eab5cd19e93e042f8590c8c2fb8b/docs/backdoc.py#L267-L357
[ "def reset(self):\n self.urls = {}\n self.titles = {}\n self.html_blocks = {}\n self.html_spans = {}\n self.list_level = 0\n self.extras = self._instance_extras.copy()\n if \"footnotes\" in self.extras:\n self.footnotes = {}\n self.footnote_ids = []\n if \"header-ids\" in self.extras:\n self._count_from_header_id = {} # no `defaultdict` in Python 2.4\n if \"metadata\" in self.extras:\n self.metadata = {}\n", "def postprocess(self, text):\n \"\"\"A hook for subclasses to do some postprocessing of the html, if\n desired. This is called before unescaping of special chars and\n unhashing of raw HTML spans.\n \"\"\"\n return text\n", "def preprocess(self, text):\n \"\"\"A hook for subclasses to do some preprocessing of the Markdown, if\n desired. This is called after basic formatting of the text, but prior\n to any extras, safe mode, etc. processing.\n \"\"\"\n return text\n", "def _extract_metadata(self, text):\n # fast test\n if not text.startswith(\"---\"):\n return text\n match = self._metadata_pat.match(text)\n if not match:\n return text\n\n tail = text[len(match.group(0)):]\n metadata_str = match.group(1).strip()\n for line in metadata_str.split('\\n'):\n key, value = line.split(':', 1)\n self.metadata[key.strip()] = value.strip()\n\n return tail\n", "def _get_emacs_vars(self, text):\n \"\"\"Return a dictionary of emacs-style local variables.\n\n Parsing is done loosely according to this spec (and according to\n some in-practice deviations from this):\n http://www.gnu.org/software/emacs/manual/html_node/emacs/Specifying-File-Variables.html#Specifying-File-Variables\n \"\"\"\n emacs_vars = {}\n SIZE = pow(2, 13) # 8kB\n\n # Search near the start for a '-*-'-style one-liner of variables.\n head = text[:SIZE]\n if \"-*-\" in head:\n match = self._emacs_oneliner_vars_pat.search(head)\n if match:\n emacs_vars_str = match.group(1)\n assert '\\n' not in emacs_vars_str\n emacs_var_strs = [s.strip() for s in emacs_vars_str.split(';')\n if s.strip()]\n if len(emacs_var_strs) == 1 and ':' not in emacs_var_strs[0]:\n # While not in the spec, this form is allowed by emacs:\n # -*- Tcl -*-\n # where the implied \"variable\" is \"mode\". This form\n # is only allowed if there are no other variables.\n emacs_vars[\"mode\"] = emacs_var_strs[0].strip()\n else:\n for emacs_var_str in emacs_var_strs:\n try:\n variable, value = emacs_var_str.strip().split(':', 1)\n except ValueError:\n log.debug(\"emacs variables error: malformed -*- \"\n \"line: %r\", emacs_var_str)\n continue\n # Lowercase the variable name because Emacs allows \"Mode\"\n # or \"mode\" or \"MoDe\", etc.\n emacs_vars[variable.lower()] = value.strip()\n\n tail = text[-SIZE:]\n if \"Local Variables\" in tail:\n match = self._emacs_local_vars_pat.search(tail)\n if match:\n prefix = match.group(\"prefix\")\n suffix = match.group(\"suffix\")\n lines = match.group(\"content\").splitlines(0)\n #print \"prefix=%r, suffix=%r, content=%r, lines: %s\"\\\n # % (prefix, suffix, match.group(\"content\"), lines)\n\n # Validate the Local Variables block: proper prefix and suffix\n # usage.\n for i, line in enumerate(lines):\n if not line.startswith(prefix):\n log.debug(\"emacs variables error: line '%s' \"\n \"does not use proper prefix '%s'\"\n % (line, prefix))\n return {}\n # Don't validate suffix on last line. Emacs doesn't care,\n # neither should we.\n if i != len(lines)-1 and not line.endswith(suffix):\n log.debug(\"emacs variables error: line '%s' \"\n \"does not use proper suffix '%s'\"\n % (line, suffix))\n return {}\n\n # Parse out one emacs var per line.\n continued_for = None\n for line in lines[:-1]: # no var on the last line (\"PREFIX End:\")\n if prefix: line = line[len(prefix):] # strip prefix\n if suffix: line = line[:-len(suffix)] # strip suffix\n line = line.strip()\n if continued_for:\n variable = continued_for\n if line.endswith('\\\\'):\n line = line[:-1].rstrip()\n else:\n continued_for = None\n emacs_vars[variable] += ' ' + line\n else:\n try:\n variable, value = line.split(':', 1)\n except ValueError:\n log.debug(\"local variables error: missing colon \"\n \"in local variables entry: '%s'\" % line)\n continue\n # Do NOT lowercase the variable name, because Emacs only\n # allows \"mode\" (and not \"Mode\", \"MoDe\", etc.) in this block.\n value = value.strip()\n if value.endswith('\\\\'):\n value = value[:-1].rstrip()\n continued_for = variable\n else:\n continued_for = None\n emacs_vars[variable] = value\n\n # Unquote values.\n for var, val in list(emacs_vars.items()):\n if len(val) > 1 and (val.startswith('\"') and val.endswith('\"')\n or val.startswith('\"') and val.endswith('\"')):\n emacs_vars[var] = val[1:-1]\n\n return emacs_vars\n", "def _detab(self, text):\n r\"\"\"Remove (leading?) tabs from a file.\n\n >>> m = Markdown()\n >>> m._detab(\"\\tfoo\")\n ' foo'\n >>> m._detab(\" \\tfoo\")\n ' foo'\n >>> m._detab(\"\\t foo\")\n ' foo'\n >>> m._detab(\" foo\")\n ' foo'\n >>> m._detab(\" foo\\n\\tbar\\tblam\")\n ' foo\\n bar blam'\n \"\"\"\n if '\\t' not in text:\n return text\n return self._detab_re.subn(self._detab_sub, text)[0]\n", "def _hash_html_blocks(self, text, raw=False):\n \"\"\"Hashify HTML blocks\n\n We only want to do this for block-level HTML tags, such as headers,\n lists, and tables. That's because we still want to wrap <p>s around\n \"paragraphs\" that are wrapped in non-block-level tags, such as anchors,\n phrase emphasis, and spans. The list of tags we're looking for is\n hard-coded.\n\n @param raw {boolean} indicates if these are raw HTML blocks in\n the original source. It makes a difference in \"safe\" mode.\n \"\"\"\n if '<' not in text:\n return text\n\n # Pass `raw` value into our calls to self._hash_html_block_sub.\n hash_html_block_sub = _curry(self._hash_html_block_sub, raw=raw)\n\n # First, look for nested blocks, e.g.:\n # <div>\n # <div>\n # tags for inner block must be indented.\n # </div>\n # </div>\n #\n # The outermost tags must start at the left margin for this to match, and\n # the inner nested divs must be indented.\n # We need to do this before the next, more liberal match, because the next\n # match will start at the first `<div>` and stop at the first `</div>`.\n text = self._strict_tag_block_re.sub(hash_html_block_sub, text)\n\n # Now match more liberally, simply from `\\n<tag>` to `</tag>\\n`\n text = self._liberal_tag_block_re.sub(hash_html_block_sub, text)\n\n # Special case just for <hr />. It was easier to make a special\n # case than to make the other regex more complicated.\n if \"<hr\" in text:\n _hr_tag_re = _hr_tag_re_from_tab_width(self.tab_width)\n text = _hr_tag_re.sub(hash_html_block_sub, text)\n\n # Special case for standalone HTML comments:\n if \"<!--\" in text:\n start = 0\n while True:\n # Delimiters for next comment block.\n try:\n start_idx = text.index(\"<!--\", start)\n except ValueError:\n break\n try:\n end_idx = text.index(\"-->\", start_idx) + 3\n except ValueError:\n break\n\n # Start position for next comment block search.\n start = end_idx\n\n # Validate whitespace before comment.\n if start_idx:\n # - Up to `tab_width - 1` spaces before start_idx.\n for i in range(self.tab_width - 1):\n if text[start_idx - 1] != ' ':\n break\n start_idx -= 1\n if start_idx == 0:\n break\n # - Must be preceded by 2 newlines or hit the start of\n # the document.\n if start_idx == 0:\n pass\n elif start_idx == 1 and text[0] == '\\n':\n start_idx = 0 # to match minute detail of Markdown.pl regex\n elif text[start_idx-2:start_idx] == '\\n\\n':\n pass\n else:\n break\n\n # Validate whitespace after comment.\n # - Any number of spaces and tabs.\n while end_idx < len(text):\n if text[end_idx] not in ' \\t':\n break\n end_idx += 1\n # - Must be following by 2 newlines or hit end of text.\n if text[end_idx:end_idx+2] not in ('', '\\n', '\\n\\n'):\n continue\n\n # Escape and hash (must match `_hash_html_block_sub`).\n html = text[start_idx:end_idx]\n if raw and self.safe_mode:\n html = self._sanitize_html(html)\n key = _hash_text(html)\n self.html_blocks[key] = html\n text = text[:start_idx] + \"\\n\\n\" + key + \"\\n\\n\" + text[end_idx:]\n\n if \"xml\" in self.extras:\n # Treat XML processing instructions and namespaced one-liner\n # tags as if they were block HTML tags. E.g., if standalone\n # (i.e. are their own paragraph), the following do not get\n # wrapped in a <p> tag:\n # <?foo bar?>\n #\n # <xi:include xmlns:xi=\"http://www.w3.org/2001/XInclude\" href=\"chapter_1.md\"/>\n _xml_oneliner_re = _xml_oneliner_re_from_tab_width(self.tab_width)\n text = _xml_oneliner_re.sub(hash_html_block_sub, text)\n\n return text\n", "def _strip_link_definitions(self, text):\n # Strips link definitions from text, stores the URLs and titles in\n # hash references.\n less_than_tab = self.tab_width - 1\n\n # Link defs are in the form:\n # [id]: url \"optional title\"\n _link_def_re = re.compile(r\"\"\"\n ^[ ]{0,%d}\\[(.+)\\]: # id = \\1\n [ \\t]*\n \\n? # maybe *one* newline\n [ \\t]*\n <?(.+?)>? # url = \\2\n [ \\t]*\n (?:\n \\n? # maybe one newline\n [ \\t]*\n (?<=\\s) # lookbehind for whitespace\n ['\"(]\n ([^\\n]*) # title = \\3\n ['\")]\n [ \\t]*\n )? # title is optional\n (?:\\n+|\\Z)\n \"\"\" % less_than_tab, re.X | re.M | re.U)\n return _link_def_re.sub(self._extract_link_def_sub, text)\n", "def _strip_footnote_definitions(self, text):\n \"\"\"A footnote definition looks like this:\n\n [^note-id]: Text of the note.\n\n May include one or more indented paragraphs.\n\n Where,\n - The 'note-id' can be pretty much anything, though typically it\n is the number of the footnote.\n - The first paragraph may start on the next line, like so:\n\n [^note-id]:\n Text of the note.\n \"\"\"\n less_than_tab = self.tab_width - 1\n footnote_def_re = re.compile(r'''\n ^[ ]{0,%d}\\[\\^(.+)\\]: # id = \\1\n [ \\t]*\n ( # footnote text = \\2\n # First line need not start with the spaces.\n (?:\\s*.*\\n+)\n (?:\n (?:[ ]{%d} | \\t) # Subsequent lines must be indented.\n .*\\n+\n )*\n )\n # Lookahead for non-space at line-start, or end of doc.\n (?:(?=^[ ]{0,%d}\\S)|\\Z)\n ''' % (less_than_tab, self.tab_width, self.tab_width),\n re.X | re.M)\n return footnote_def_re.sub(self._extract_footnote_def_sub, text)\n", "def _run_block_gamut(self, text):\n # These are all the transformations that form block-level\n # tags like paragraphs, headers, and list items.\n\n if \"fenced-code-blocks\" in self.extras:\n text = self._do_fenced_code_blocks(text)\n\n text = self._do_headers(text)\n\n # Do Horizontal Rules:\n # On the number of spaces in horizontal rules: The spec is fuzzy: \"If\n # you wish, you may use spaces between the hyphens or asterisks.\"\n # Markdown.pl 1.0.1's hr regexes limit the number of spaces between the\n # hr chars to one or two. We'll reproduce that limit here.\n hr = \"\\n<hr\"+self.empty_element_suffix+\"\\n\"\n for ch, regex in self._hr_data:\n if ch in text:\n for m in reversed(list(regex.finditer(text))):\n tail = m.group(1).rstrip()\n if not tail.strip(ch + ' ') and tail.count(\" \") == 0:\n start, end = m.span()\n text = text[:start] + hr + text[end:]\n\n text = self._do_lists(text)\n\n if \"pyshell\" in self.extras:\n text = self._prepare_pyshell_blocks(text)\n if \"wiki-tables\" in self.extras:\n text = self._do_wiki_tables(text)\n\n text = self._do_code_blocks(text)\n\n text = self._do_block_quotes(text)\n\n # We already ran _HashHTMLBlocks() before, in Markdown(), but that\n # was to escape raw HTML in the original Markdown source. This time,\n # we're escaping the markup we've just created, so that we don't wrap\n # <p> tags around block-level tags.\n text = self._hash_html_blocks(text)\n\n text = self._form_paragraphs(text)\n\n return text\n", "def _hash_html_spans(self, text):\n # Used for safe_mode.\n\n def _is_auto_link(s):\n if ':' in s and self._auto_link_re.match(s):\n return True\n elif '@' in s and self._auto_email_link_re.match(s):\n return True\n return False\n\n tokens = []\n is_html_markup = False\n for token in self._sorta_html_tokenize_re.split(text):\n if is_html_markup and not _is_auto_link(token):\n sanitized = self._sanitize_html(token)\n key = _hash_text(sanitized)\n self.html_spans[key] = sanitized\n tokens.append(key)\n else:\n tokens.append(token)\n is_html_markup = not is_html_markup\n return ''.join(tokens)\n", "def _unhash_html_spans(self, text):\n for key, sanitized in list(self.html_spans.items()):\n text = text.replace(key, sanitized)\n return text\n", "def _add_footnotes(self, text):\n if self.footnotes:\n footer = [\n '<div class=\"footnotes\">',\n '<hr' + self.empty_element_suffix,\n '<ol>',\n ]\n for i, id in enumerate(self.footnote_ids):\n if i != 0:\n footer.append('')\n footer.append('<li id=\"fn-%s\">' % id)\n footer.append(self._run_block_gamut(self.footnotes[id]))\n backlink = ('<a href=\"#fnref-%s\" '\n 'class=\"footnoteBackLink\" '\n 'title=\"Jump back to footnote %d in the text.\">'\n '&#8617;</a>' % (id, i+1))\n if footer[-1].endswith(\"</p>\"):\n footer[-1] = footer[-1][:-len(\"</p>\")] \\\n + '&nbsp;' + backlink + \"</p>\"\n else:\n footer.append(\"\\n<p>%s</p>\" % backlink)\n footer.append('</li>')\n footer.append('</ol>')\n footer.append('</div>')\n return text + '\\n\\n' + '\\n'.join(footer)\n else:\n return text\n", "def _unescape_special_chars(self, text):\n # Swap back in all the special characters we've hidden.\n for ch, hash in list(self._escape_table.items()):\n text = text.replace(hash, ch)\n return text\n" ]
class Markdown(object): # The dict of "extras" to enable in processing -- a mapping of # extra name to argument for the extra. Most extras do not have an # argument, in which case the value is None. # # This can be set via (a) subclassing and (b) the constructor # "extras" argument. extras = None urls = None titles = None html_blocks = None html_spans = None html_removed_text = "[HTML_REMOVED]" # for compat with markdown.py # Used to track when we're inside an ordered or unordered list # (see _ProcessListItems() for details): list_level = 0 _ws_only_line_re = re.compile(r"^[ \t]+$", re.M) def __init__(self, html4tags=False, tab_width=4, safe_mode=None, extras=None, link_patterns=None, use_file_vars=False): if html4tags: self.empty_element_suffix = ">" else: self.empty_element_suffix = " />" self.tab_width = tab_width # For compatibility with earlier markdown2.py and with # markdown.py's safe_mode being a boolean, # safe_mode == True -> "replace" if safe_mode is True: self.safe_mode = "replace" else: self.safe_mode = safe_mode # Massaging and building the "extras" info. if self.extras is None: self.extras = {} elif not isinstance(self.extras, dict): self.extras = dict([(e, None) for e in self.extras]) if extras: if not isinstance(extras, dict): extras = dict([(e, None) for e in extras]) self.extras.update(extras) assert isinstance(self.extras, dict) if "toc" in self.extras and not "header-ids" in self.extras: self.extras["header-ids"] = None # "toc" implies "header-ids" self._instance_extras = self.extras.copy() self.link_patterns = link_patterns self.use_file_vars = use_file_vars self._outdent_re = re.compile(r'^(\t|[ ]{1,%d})' % tab_width, re.M) self._escape_table = g_escape_table.copy() if "smarty-pants" in self.extras: self._escape_table['"'] = _hash_text('"') self._escape_table["'"] = _hash_text("'") def reset(self): self.urls = {} self.titles = {} self.html_blocks = {} self.html_spans = {} self.list_level = 0 self.extras = self._instance_extras.copy() if "footnotes" in self.extras: self.footnotes = {} self.footnote_ids = [] if "header-ids" in self.extras: self._count_from_header_id = {} # no `defaultdict` in Python 2.4 if "metadata" in self.extras: self.metadata = {} # Per <https://developer.mozilla.org/en-US/docs/HTML/Element/a> "rel" # should only be used in <a> tags with an "href" attribute. _a_nofollow = re.compile(r"<(a)([^>]*href=)", re.IGNORECASE) def postprocess(self, text): """A hook for subclasses to do some postprocessing of the html, if desired. This is called before unescaping of special chars and unhashing of raw HTML spans. """ return text def preprocess(self, text): """A hook for subclasses to do some preprocessing of the Markdown, if desired. This is called after basic formatting of the text, but prior to any extras, safe mode, etc. processing. """ return text # Is metadata if the content starts with '---'-fenced `key: value` # pairs. E.g. (indented for presentation): # --- # foo: bar # another-var: blah blah # --- _metadata_pat = re.compile("""^---[ \t]*\n((?:[ \t]*[^ \t:]+[ \t]*:[^\n]*\n)+)---[ \t]*\n""") def _extract_metadata(self, text): # fast test if not text.startswith("---"): return text match = self._metadata_pat.match(text) if not match: return text tail = text[len(match.group(0)):] metadata_str = match.group(1).strip() for line in metadata_str.split('\n'): key, value = line.split(':', 1) self.metadata[key.strip()] = value.strip() return tail _emacs_oneliner_vars_pat = re.compile(r"-\*-\s*([^\r\n]*?)\s*-\*-", re.UNICODE) # This regular expression is intended to match blocks like this: # PREFIX Local Variables: SUFFIX # PREFIX mode: Tcl SUFFIX # PREFIX End: SUFFIX # Some notes: # - "[ \t]" is used instead of "\s" to specifically exclude newlines # - "(\r\n|\n|\r)" is used instead of "$" because the sre engine does # not like anything other than Unix-style line terminators. _emacs_local_vars_pat = re.compile(r"""^ (?P<prefix>(?:[^\r\n|\n|\r])*?) [\ \t]*Local\ Variables:[\ \t]* (?P<suffix>.*?)(?:\r\n|\n|\r) (?P<content>.*?\1End:) """, re.IGNORECASE | re.MULTILINE | re.DOTALL | re.VERBOSE) def _get_emacs_vars(self, text): """Return a dictionary of emacs-style local variables. Parsing is done loosely according to this spec (and according to some in-practice deviations from this): http://www.gnu.org/software/emacs/manual/html_node/emacs/Specifying-File-Variables.html#Specifying-File-Variables """ emacs_vars = {} SIZE = pow(2, 13) # 8kB # Search near the start for a '-*-'-style one-liner of variables. head = text[:SIZE] if "-*-" in head: match = self._emacs_oneliner_vars_pat.search(head) if match: emacs_vars_str = match.group(1) assert '\n' not in emacs_vars_str emacs_var_strs = [s.strip() for s in emacs_vars_str.split(';') if s.strip()] if len(emacs_var_strs) == 1 and ':' not in emacs_var_strs[0]: # While not in the spec, this form is allowed by emacs: # -*- Tcl -*- # where the implied "variable" is "mode". This form # is only allowed if there are no other variables. emacs_vars["mode"] = emacs_var_strs[0].strip() else: for emacs_var_str in emacs_var_strs: try: variable, value = emacs_var_str.strip().split(':', 1) except ValueError: log.debug("emacs variables error: malformed -*- " "line: %r", emacs_var_str) continue # Lowercase the variable name because Emacs allows "Mode" # or "mode" or "MoDe", etc. emacs_vars[variable.lower()] = value.strip() tail = text[-SIZE:] if "Local Variables" in tail: match = self._emacs_local_vars_pat.search(tail) if match: prefix = match.group("prefix") suffix = match.group("suffix") lines = match.group("content").splitlines(0) #print "prefix=%r, suffix=%r, content=%r, lines: %s"\ # % (prefix, suffix, match.group("content"), lines) # Validate the Local Variables block: proper prefix and suffix # usage. for i, line in enumerate(lines): if not line.startswith(prefix): log.debug("emacs variables error: line '%s' " "does not use proper prefix '%s'" % (line, prefix)) return {} # Don't validate suffix on last line. Emacs doesn't care, # neither should we. if i != len(lines)-1 and not line.endswith(suffix): log.debug("emacs variables error: line '%s' " "does not use proper suffix '%s'" % (line, suffix)) return {} # Parse out one emacs var per line. continued_for = None for line in lines[:-1]: # no var on the last line ("PREFIX End:") if prefix: line = line[len(prefix):] # strip prefix if suffix: line = line[:-len(suffix)] # strip suffix line = line.strip() if continued_for: variable = continued_for if line.endswith('\\'): line = line[:-1].rstrip() else: continued_for = None emacs_vars[variable] += ' ' + line else: try: variable, value = line.split(':', 1) except ValueError: log.debug("local variables error: missing colon " "in local variables entry: '%s'" % line) continue # Do NOT lowercase the variable name, because Emacs only # allows "mode" (and not "Mode", "MoDe", etc.) in this block. value = value.strip() if value.endswith('\\'): value = value[:-1].rstrip() continued_for = variable else: continued_for = None emacs_vars[variable] = value # Unquote values. for var, val in list(emacs_vars.items()): if len(val) > 1 and (val.startswith('"') and val.endswith('"') or val.startswith('"') and val.endswith('"')): emacs_vars[var] = val[1:-1] return emacs_vars # Cribbed from a post by Bart Lateur: # <http://www.nntp.perl.org/group/perl.macperl.anyperl/154> _detab_re = re.compile(r'(.*?)\t', re.M) def _detab_sub(self, match): g1 = match.group(1) return g1 + (' ' * (self.tab_width - len(g1) % self.tab_width)) def _detab(self, text): r"""Remove (leading?) tabs from a file. >>> m = Markdown() >>> m._detab("\tfoo") ' foo' >>> m._detab(" \tfoo") ' foo' >>> m._detab("\t foo") ' foo' >>> m._detab(" foo") ' foo' >>> m._detab(" foo\n\tbar\tblam") ' foo\n bar blam' """ if '\t' not in text: return text return self._detab_re.subn(self._detab_sub, text)[0] # I broke out the html5 tags here and add them to _block_tags_a and # _block_tags_b. This way html5 tags are easy to keep track of. _html5tags = '|article|aside|header|hgroup|footer|nav|section|figure|figcaption' _block_tags_a = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del' _block_tags_a += _html5tags _strict_tag_block_re = re.compile(r""" ( # save in \1 ^ # start of line (with re.M) <(%s) # start tag = \2 \b # word break (.*\n)*? # any number of lines, minimally matching </\2> # the matching end tag [ \t]* # trailing spaces/tabs (?=\n+|\Z) # followed by a newline or end of document ) """ % _block_tags_a, re.X | re.M) _block_tags_b = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math' _block_tags_b += _html5tags _liberal_tag_block_re = re.compile(r""" ( # save in \1 ^ # start of line (with re.M) <(%s) # start tag = \2 \b # word break (.*\n)*? # any number of lines, minimally matching .*</\2> # the matching end tag [ \t]* # trailing spaces/tabs (?=\n+|\Z) # followed by a newline or end of document ) """ % _block_tags_b, re.X | re.M) _html_markdown_attr_re = re.compile( r'''\s+markdown=("1"|'1')''') def _hash_html_block_sub(self, match, raw=False): html = match.group(1) if raw and self.safe_mode: html = self._sanitize_html(html) elif 'markdown-in-html' in self.extras and 'markdown=' in html: first_line = html.split('\n', 1)[0] m = self._html_markdown_attr_re.search(first_line) if m: lines = html.split('\n') middle = '\n'.join(lines[1:-1]) last_line = lines[-1] first_line = first_line[:m.start()] + first_line[m.end():] f_key = _hash_text(first_line) self.html_blocks[f_key] = first_line l_key = _hash_text(last_line) self.html_blocks[l_key] = last_line return ''.join(["\n\n", f_key, "\n\n", middle, "\n\n", l_key, "\n\n"]) key = _hash_text(html) self.html_blocks[key] = html return "\n\n" + key + "\n\n" def _hash_html_blocks(self, text, raw=False): """Hashify HTML blocks We only want to do this for block-level HTML tags, such as headers, lists, and tables. That's because we still want to wrap <p>s around "paragraphs" that are wrapped in non-block-level tags, such as anchors, phrase emphasis, and spans. The list of tags we're looking for is hard-coded. @param raw {boolean} indicates if these are raw HTML blocks in the original source. It makes a difference in "safe" mode. """ if '<' not in text: return text # Pass `raw` value into our calls to self._hash_html_block_sub. hash_html_block_sub = _curry(self._hash_html_block_sub, raw=raw) # First, look for nested blocks, e.g.: # <div> # <div> # tags for inner block must be indented. # </div> # </div> # # The outermost tags must start at the left margin for this to match, and # the inner nested divs must be indented. # We need to do this before the next, more liberal match, because the next # match will start at the first `<div>` and stop at the first `</div>`. text = self._strict_tag_block_re.sub(hash_html_block_sub, text) # Now match more liberally, simply from `\n<tag>` to `</tag>\n` text = self._liberal_tag_block_re.sub(hash_html_block_sub, text) # Special case just for <hr />. It was easier to make a special # case than to make the other regex more complicated. if "<hr" in text: _hr_tag_re = _hr_tag_re_from_tab_width(self.tab_width) text = _hr_tag_re.sub(hash_html_block_sub, text) # Special case for standalone HTML comments: if "<!--" in text: start = 0 while True: # Delimiters for next comment block. try: start_idx = text.index("<!--", start) except ValueError: break try: end_idx = text.index("-->", start_idx) + 3 except ValueError: break # Start position for next comment block search. start = end_idx # Validate whitespace before comment. if start_idx: # - Up to `tab_width - 1` spaces before start_idx. for i in range(self.tab_width - 1): if text[start_idx - 1] != ' ': break start_idx -= 1 if start_idx == 0: break # - Must be preceded by 2 newlines or hit the start of # the document. if start_idx == 0: pass elif start_idx == 1 and text[0] == '\n': start_idx = 0 # to match minute detail of Markdown.pl regex elif text[start_idx-2:start_idx] == '\n\n': pass else: break # Validate whitespace after comment. # - Any number of spaces and tabs. while end_idx < len(text): if text[end_idx] not in ' \t': break end_idx += 1 # - Must be following by 2 newlines or hit end of text. if text[end_idx:end_idx+2] not in ('', '\n', '\n\n'): continue # Escape and hash (must match `_hash_html_block_sub`). html = text[start_idx:end_idx] if raw and self.safe_mode: html = self._sanitize_html(html) key = _hash_text(html) self.html_blocks[key] = html text = text[:start_idx] + "\n\n" + key + "\n\n" + text[end_idx:] if "xml" in self.extras: # Treat XML processing instructions and namespaced one-liner # tags as if they were block HTML tags. E.g., if standalone # (i.e. are their own paragraph), the following do not get # wrapped in a <p> tag: # <?foo bar?> # # <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="chapter_1.md"/> _xml_oneliner_re = _xml_oneliner_re_from_tab_width(self.tab_width) text = _xml_oneliner_re.sub(hash_html_block_sub, text) return text def _strip_link_definitions(self, text): # Strips link definitions from text, stores the URLs and titles in # hash references. less_than_tab = self.tab_width - 1 # Link defs are in the form: # [id]: url "optional title" _link_def_re = re.compile(r""" ^[ ]{0,%d}\[(.+)\]: # id = \1 [ \t]* \n? # maybe *one* newline [ \t]* <?(.+?)>? # url = \2 [ \t]* (?: \n? # maybe one newline [ \t]* (?<=\s) # lookbehind for whitespace ['"(] ([^\n]*) # title = \3 ['")] [ \t]* )? # title is optional (?:\n+|\Z) """ % less_than_tab, re.X | re.M | re.U) return _link_def_re.sub(self._extract_link_def_sub, text) def _extract_link_def_sub(self, match): id, url, title = match.groups() key = id.lower() # Link IDs are case-insensitive self.urls[key] = self._encode_amps_and_angles(url) if title: self.titles[key] = title return "" def _extract_footnote_def_sub(self, match): id, text = match.groups() text = _dedent(text, skip_first_line=not text.startswith('\n')).strip() normed_id = re.sub(r'\W', '-', id) # Ensure footnote text ends with a couple newlines (for some # block gamut matches). self.footnotes[normed_id] = text + "\n\n" return "" def _strip_footnote_definitions(self, text): """A footnote definition looks like this: [^note-id]: Text of the note. May include one or more indented paragraphs. Where, - The 'note-id' can be pretty much anything, though typically it is the number of the footnote. - The first paragraph may start on the next line, like so: [^note-id]: Text of the note. """ less_than_tab = self.tab_width - 1 footnote_def_re = re.compile(r''' ^[ ]{0,%d}\[\^(.+)\]: # id = \1 [ \t]* ( # footnote text = \2 # First line need not start with the spaces. (?:\s*.*\n+) (?: (?:[ ]{%d} | \t) # Subsequent lines must be indented. .*\n+ )* ) # Lookahead for non-space at line-start, or end of doc. (?:(?=^[ ]{0,%d}\S)|\Z) ''' % (less_than_tab, self.tab_width, self.tab_width), re.X | re.M) return footnote_def_re.sub(self._extract_footnote_def_sub, text) _hr_data = [ ('*', re.compile(r"^[ ]{0,3}\*(.*?)$", re.M)), ('-', re.compile(r"^[ ]{0,3}\-(.*?)$", re.M)), ('_', re.compile(r"^[ ]{0,3}\_(.*?)$", re.M)), ] def _run_block_gamut(self, text): # These are all the transformations that form block-level # tags like paragraphs, headers, and list items. if "fenced-code-blocks" in self.extras: text = self._do_fenced_code_blocks(text) text = self._do_headers(text) # Do Horizontal Rules: # On the number of spaces in horizontal rules: The spec is fuzzy: "If # you wish, you may use spaces between the hyphens or asterisks." # Markdown.pl 1.0.1's hr regexes limit the number of spaces between the # hr chars to one or two. We'll reproduce that limit here. hr = "\n<hr"+self.empty_element_suffix+"\n" for ch, regex in self._hr_data: if ch in text: for m in reversed(list(regex.finditer(text))): tail = m.group(1).rstrip() if not tail.strip(ch + ' ') and tail.count(" ") == 0: start, end = m.span() text = text[:start] + hr + text[end:] text = self._do_lists(text) if "pyshell" in self.extras: text = self._prepare_pyshell_blocks(text) if "wiki-tables" in self.extras: text = self._do_wiki_tables(text) text = self._do_code_blocks(text) text = self._do_block_quotes(text) # We already ran _HashHTMLBlocks() before, in Markdown(), but that # was to escape raw HTML in the original Markdown source. This time, # we're escaping the markup we've just created, so that we don't wrap # <p> tags around block-level tags. text = self._hash_html_blocks(text) text = self._form_paragraphs(text) return text def _pyshell_block_sub(self, match): lines = match.group(0).splitlines(0) _dedentlines(lines) indent = ' ' * self.tab_width s = ('\n' # separate from possible cuddled paragraph + indent + ('\n'+indent).join(lines) + '\n\n') return s def _prepare_pyshell_blocks(self, text): """Ensure that Python interactive shell sessions are put in code blocks -- even if not properly indented. """ if ">>>" not in text: return text less_than_tab = self.tab_width - 1 _pyshell_block_re = re.compile(r""" ^([ ]{0,%d})>>>[ ].*\n # first line ^(\1.*\S+.*\n)* # any number of subsequent lines ^\n # ends with a blank line """ % less_than_tab, re.M | re.X) return _pyshell_block_re.sub(self._pyshell_block_sub, text) def _wiki_table_sub(self, match): ttext = match.group(0).strip() #print 'wiki table: %r' % match.group(0) rows = [] for line in ttext.splitlines(0): line = line.strip()[2:-2].strip() row = [c.strip() for c in re.split(r'(?<!\\)\|\|', line)] rows.append(row) #pprint(rows) hlines = ['<table>', '<tbody>'] for row in rows: hrow = ['<tr>'] for cell in row: hrow.append('<td>') hrow.append(self._run_span_gamut(cell)) hrow.append('</td>') hrow.append('</tr>') hlines.append(''.join(hrow)) hlines += ['</tbody>', '</table>'] return '\n'.join(hlines) + '\n' def _do_wiki_tables(self, text): # Optimization. if "||" not in text: return text less_than_tab = self.tab_width - 1 wiki_table_re = re.compile(r''' (?:(?<=\n\n)|\A\n?) # leading blank line ^([ ]{0,%d})\|\|.+?\|\|[ ]*\n # first line (^\1\|\|.+?\|\|\n)* # any number of subsequent lines ''' % less_than_tab, re.M | re.X) return wiki_table_re.sub(self._wiki_table_sub, text) def _run_span_gamut(self, text): # These are all the transformations that occur *within* block-level # tags like paragraphs, headers, and list items. text = self._do_code_spans(text) text = self._escape_special_chars(text) # Process anchor and image tags. text = self._do_links(text) # Make links out of things like `<http://example.com/>` # Must come after _do_links(), because you can use < and > # delimiters in inline links like [this](<url>). text = self._do_auto_links(text) if "link-patterns" in self.extras: text = self._do_link_patterns(text) text = self._encode_amps_and_angles(text) text = self._do_italics_and_bold(text) if "smarty-pants" in self.extras: text = self._do_smart_punctuation(text) # Do hard breaks: text = re.sub(r" {2,}\n", " <br%s\n" % self.empty_element_suffix, text) return text # "Sorta" because auto-links are identified as "tag" tokens. _sorta_html_tokenize_re = re.compile(r""" ( # tag </? (?:\w+) # tag name (?:\s+(?:[\w-]+:)?[\w-]+=(?:".*?"|'.*?'))* # attributes \s*/?> | # auto-link (e.g., <http://www.activestate.com/>) <\w+[^>]*> | <!--.*?--> # comment | <\?.*?\?> # processing instruction ) """, re.X) def _escape_special_chars(self, text): # Python markdown note: the HTML tokenization here differs from # that in Markdown.pl, hence the behaviour for subtle cases can # differ (I believe the tokenizer here does a better job because # it isn't susceptible to unmatched '<' and '>' in HTML tags). # Note, however, that '>' is not allowed in an auto-link URL # here. escaped = [] is_html_markup = False for token in self._sorta_html_tokenize_re.split(text): if is_html_markup: # Within tags/HTML-comments/auto-links, encode * and _ # so they don't conflict with their use in Markdown for # italics and strong. We're replacing each such # character with its corresponding MD5 checksum value; # this is likely overkill, but it should prevent us from # colliding with the escape values by accident. escaped.append(token.replace('*', self._escape_table['*']) .replace('_', self._escape_table['_'])) else: escaped.append(self._encode_backslash_escapes(token)) is_html_markup = not is_html_markup return ''.join(escaped) def _hash_html_spans(self, text): # Used for safe_mode. def _is_auto_link(s): if ':' in s and self._auto_link_re.match(s): return True elif '@' in s and self._auto_email_link_re.match(s): return True return False tokens = [] is_html_markup = False for token in self._sorta_html_tokenize_re.split(text): if is_html_markup and not _is_auto_link(token): sanitized = self._sanitize_html(token) key = _hash_text(sanitized) self.html_spans[key] = sanitized tokens.append(key) else: tokens.append(token) is_html_markup = not is_html_markup return ''.join(tokens) def _unhash_html_spans(self, text): for key, sanitized in list(self.html_spans.items()): text = text.replace(key, sanitized) return text def _sanitize_html(self, s): if self.safe_mode == "replace": return self.html_removed_text elif self.safe_mode == "escape": replacements = [ ('&', '&amp;'), ('<', '&lt;'), ('>', '&gt;'), ] for before, after in replacements: s = s.replace(before, after) return s else: raise MarkdownError("invalid value for 'safe_mode': %r (must be " "'escape' or 'replace')" % self.safe_mode) _tail_of_inline_link_re = re.compile(r''' # Match tail of: [text](/url/) or [text](/url/ "title") \( # literal paren [ \t]* (?P<url> # \1 <.*?> | .*? ) [ \t]* ( # \2 (['"]) # quote char = \3 (?P<title>.*?) \3 # matching quote )? # title is optional \) ''', re.X | re.S) _tail_of_reference_link_re = re.compile(r''' # Match tail of: [text][id] [ ]? # one optional space (?:\n[ ]*)? # one optional newline followed by spaces \[ (?P<id>.*?) \] ''', re.X | re.S) def _do_links(self, text): """Turn Markdown link shortcuts into XHTML <a> and <img> tags. This is a combination of Markdown.pl's _DoAnchors() and _DoImages(). They are done together because that simplified the approach. It was necessary to use a different approach than Markdown.pl because of the lack of atomic matching support in Python's regex engine used in $g_nested_brackets. """ MAX_LINK_TEXT_SENTINEL = 3000 # markdown2 issue 24 # `anchor_allowed_pos` is used to support img links inside # anchors, but not anchors inside anchors. An anchor's start # pos must be `>= anchor_allowed_pos`. anchor_allowed_pos = 0 curr_pos = 0 while True: # Handle the next link. # The next '[' is the start of: # - an inline anchor: [text](url "title") # - a reference anchor: [text][id] # - an inline img: ![text](url "title") # - a reference img: ![text][id] # - a footnote ref: [^id] # (Only if 'footnotes' extra enabled) # - a footnote defn: [^id]: ... # (Only if 'footnotes' extra enabled) These have already # been stripped in _strip_footnote_definitions() so no # need to watch for them. # - a link definition: [id]: url "title" # These have already been stripped in # _strip_link_definitions() so no need to watch for them. # - not markup: [...anything else... try: start_idx = text.index('[', curr_pos) except ValueError: break text_length = len(text) # Find the matching closing ']'. # Markdown.pl allows *matching* brackets in link text so we # will here too. Markdown.pl *doesn't* currently allow # matching brackets in img alt text -- we'll differ in that # regard. bracket_depth = 0 for p in range(start_idx+1, min(start_idx+MAX_LINK_TEXT_SENTINEL, text_length)): ch = text[p] if ch == ']': bracket_depth -= 1 if bracket_depth < 0: break elif ch == '[': bracket_depth += 1 else: # Closing bracket not found within sentinel length. # This isn't markup. curr_pos = start_idx + 1 continue link_text = text[start_idx+1:p] # Possibly a footnote ref? if "footnotes" in self.extras and link_text.startswith("^"): normed_id = re.sub(r'\W', '-', link_text[1:]) if normed_id in self.footnotes: self.footnote_ids.append(normed_id) result = '<sup class="footnote-ref" id="fnref-%s">' \ '<a href="#fn-%s">%s</a></sup>' \ % (normed_id, normed_id, len(self.footnote_ids)) text = text[:start_idx] + result + text[p+1:] else: # This id isn't defined, leave the markup alone. curr_pos = p+1 continue # Now determine what this is by the remainder. p += 1 if p == text_length: return text # Inline anchor or img? if text[p] == '(': # attempt at perf improvement match = self._tail_of_inline_link_re.match(text, p) if match: # Handle an inline anchor or img. is_img = start_idx > 0 and text[start_idx-1] == "!" if is_img: start_idx -= 1 url, title = match.group("url"), match.group("title") if url and url[0] == '<': url = url[1:-1] # '<url>' -> 'url' # We've got to encode these to avoid conflicting # with italics/bold. url = url.replace('*', self._escape_table['*']) \ .replace('_', self._escape_table['_']) if title: title_str = ' title="%s"' % ( _xml_escape_attr(title) .replace('*', self._escape_table['*']) .replace('_', self._escape_table['_'])) else: title_str = '' if is_img: result = '<img src="%s" alt="%s"%s%s' \ % (url.replace('"', '&quot;'), _xml_escape_attr(link_text), title_str, self.empty_element_suffix) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) curr_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] elif start_idx >= anchor_allowed_pos: result_head = '<a href="%s"%s>' % (url, title_str) result = '%s%s</a>' % (result_head, link_text) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) # <img> allowed from curr_pos on, <a> from # anchor_allowed_pos on. curr_pos = start_idx + len(result_head) anchor_allowed_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] else: # Anchor not allowed here. curr_pos = start_idx + 1 continue # Reference anchor or img? else: match = self._tail_of_reference_link_re.match(text, p) if match: # Handle a reference-style anchor or img. is_img = start_idx > 0 and text[start_idx-1] == "!" if is_img: start_idx -= 1 link_id = match.group("id").lower() if not link_id: link_id = link_text.lower() # for links like [this][] if link_id in self.urls: url = self.urls[link_id] # We've got to encode these to avoid conflicting # with italics/bold. url = url.replace('*', self._escape_table['*']) \ .replace('_', self._escape_table['_']) title = self.titles.get(link_id) if title: before = title title = _xml_escape_attr(title) \ .replace('*', self._escape_table['*']) \ .replace('_', self._escape_table['_']) title_str = ' title="%s"' % title else: title_str = '' if is_img: result = '<img src="%s" alt="%s"%s%s' \ % (url.replace('"', '&quot;'), link_text.replace('"', '&quot;'), title_str, self.empty_element_suffix) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) curr_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] elif start_idx >= anchor_allowed_pos: result = '<a href="%s"%s>%s</a>' \ % (url, title_str, link_text) result_head = '<a href="%s"%s>' % (url, title_str) result = '%s%s</a>' % (result_head, link_text) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) # <img> allowed from curr_pos on, <a> from # anchor_allowed_pos on. curr_pos = start_idx + len(result_head) anchor_allowed_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] else: # Anchor not allowed here. curr_pos = start_idx + 1 else: # This id isn't defined, leave the markup alone. curr_pos = match.end() continue # Otherwise, it isn't markup. curr_pos = start_idx + 1 return text def header_id_from_text(self, text, prefix, n): """Generate a header id attribute value from the given header HTML content. This is only called if the "header-ids" extra is enabled. Subclasses may override this for different header ids. @param text {str} The text of the header tag @param prefix {str} The requested prefix for header ids. This is the value of the "header-ids" extra key, if any. Otherwise, None. @param n {int} The <hN> tag number, i.e. `1` for an <h1> tag. @returns {str} The value for the header tag's "id" attribute. Return None to not have an id attribute and to exclude this header from the TOC (if the "toc" extra is specified). """ header_id = _slugify(text) if prefix and isinstance(prefix, base_string_type): header_id = prefix + '-' + header_id if header_id in self._count_from_header_id: self._count_from_header_id[header_id] += 1 header_id += '-%s' % self._count_from_header_id[header_id] else: self._count_from_header_id[header_id] = 1 return header_id _toc = None def _toc_add_entry(self, level, id, name): if self._toc is None: self._toc = [] self._toc.append((level, id, self._unescape_special_chars(name))) _setext_h_re = re.compile(r'^(.+)[ \t]*\n(=+|-+)[ \t]*\n+', re.M) def _setext_h_sub(self, match): n = {"=": 1, "-": 2}[match.group(2)[0]] demote_headers = self.extras.get("demote-headers") if demote_headers: n = min(n + demote_headers, 6) header_id_attr = "" if "header-ids" in self.extras: header_id = self.header_id_from_text(match.group(1), self.extras["header-ids"], n) if header_id: header_id_attr = ' id="%s"' % header_id html = self._run_span_gamut(match.group(1)) if "toc" in self.extras and header_id: self._toc_add_entry(n, header_id, html) return "<h%d%s>%s</h%d>\n\n" % (n, header_id_attr, html, n) _atx_h_re = re.compile(r''' ^(\#{1,6}) # \1 = string of #'s [ \t]+ (.+?) # \2 = Header text [ \t]* (?<!\\) # ensure not an escaped trailing '#' \#* # optional closing #'s (not counted) \n+ ''', re.X | re.M) def _atx_h_sub(self, match): n = len(match.group(1)) demote_headers = self.extras.get("demote-headers") if demote_headers: n = min(n + demote_headers, 6) header_id_attr = "" if "header-ids" in self.extras: header_id = self.header_id_from_text(match.group(2), self.extras["header-ids"], n) if header_id: header_id_attr = ' id="%s"' % header_id html = self._run_span_gamut(match.group(2)) if "toc" in self.extras and header_id: self._toc_add_entry(n, header_id, html) return "<h%d%s>%s</h%d>\n\n" % (n, header_id_attr, html, n) def _do_headers(self, text): # Setext-style headers: # Header 1 # ======== # # Header 2 # -------- text = self._setext_h_re.sub(self._setext_h_sub, text) # atx-style headers: # # Header 1 # ## Header 2 # ## Header 2 with closing hashes ## # ... # ###### Header 6 text = self._atx_h_re.sub(self._atx_h_sub, text) return text _marker_ul_chars = '*+-' _marker_any = r'(?:[%s]|\d+\.)' % _marker_ul_chars _marker_ul = '(?:[%s])' % _marker_ul_chars _marker_ol = r'(?:\d+\.)' def _list_sub(self, match): lst = match.group(1) lst_type = match.group(3) in self._marker_ul_chars and "ul" or "ol" result = self._process_list_items(lst) if self.list_level: return "<%s>\n%s</%s>\n" % (lst_type, result, lst_type) else: return "<%s>\n%s</%s>\n\n" % (lst_type, result, lst_type) def _do_lists(self, text): # Form HTML ordered (numbered) and unordered (bulleted) lists. # Iterate over each *non-overlapping* list match. pos = 0 while True: # Find the *first* hit for either list style (ul or ol). We # match ul and ol separately to avoid adjacent lists of different # types running into each other (see issue #16). hits = [] for marker_pat in (self._marker_ul, self._marker_ol): less_than_tab = self.tab_width - 1 whole_list = r''' ( # \1 = whole list ( # \2 [ ]{0,%d} (%s) # \3 = first list item marker [ \t]+ (?!\ *\3\ ) # '- - - ...' isn't a list. See 'not_quite_a_list' test case. ) (?:.+?) ( # \4 \Z | \n{2,} (?=\S) (?! # Negative lookahead for another list item marker [ \t]* %s[ \t]+ ) ) ) ''' % (less_than_tab, marker_pat, marker_pat) if self.list_level: # sub-list list_re = re.compile("^"+whole_list, re.X | re.M | re.S) else: list_re = re.compile(r"(?:(?<=\n\n)|\A\n?)"+whole_list, re.X | re.M | re.S) match = list_re.search(text, pos) if match: hits.append((match.start(), match)) if not hits: break hits.sort() match = hits[0][1] start, end = match.span() text = text[:start] + self._list_sub(match) + text[end:] pos = end return text _list_item_re = re.compile(r''' (\n)? # leading line = \1 (^[ \t]*) # leading whitespace = \2 (?P<marker>%s) [ \t]+ # list marker = \3 ((?:.+?) # list item text = \4 (\n{1,2})) # eols = \5 (?= \n* (\Z | \2 (?P<next_marker>%s) [ \t]+)) ''' % (_marker_any, _marker_any), re.M | re.X | re.S) _last_li_endswith_two_eols = False def _list_item_sub(self, match): item = match.group(4) leading_line = match.group(1) leading_space = match.group(2) if leading_line or "\n\n" in item or self._last_li_endswith_two_eols: item = self._run_block_gamut(self._outdent(item)) else: # Recursion for sub-lists: item = self._do_lists(self._outdent(item)) if item.endswith('\n'): item = item[:-1] item = self._run_span_gamut(item) self._last_li_endswith_two_eols = (len(match.group(5)) == 2) return "<li>%s</li>\n" % item def _process_list_items(self, list_str): # Process the contents of a single ordered or unordered list, # splitting it into individual list items. # The $g_list_level global keeps track of when we're inside a list. # Each time we enter a list, we increment it; when we leave a list, # we decrement. If it's zero, we're not in a list anymore. # # We do this because when we're not inside a list, we want to treat # something like this: # # I recommend upgrading to version # 8. Oops, now this line is treated # as a sub-list. # # As a single paragraph, despite the fact that the second line starts # with a digit-period-space sequence. # # Whereas when we're inside a list (or sub-list), that line will be # treated as the start of a sub-list. What a kludge, huh? This is # an aspect of Markdown's syntax that's hard to parse perfectly # without resorting to mind-reading. Perhaps the solution is to # change the syntax rules such that sub-lists must start with a # starting cardinal number; e.g. "1." or "a.". self.list_level += 1 self._last_li_endswith_two_eols = False list_str = list_str.rstrip('\n') + '\n' list_str = self._list_item_re.sub(self._list_item_sub, list_str) self.list_level -= 1 return list_str def _get_pygments_lexer(self, lexer_name): try: from pygments import lexers, util except ImportError: return None try: return lexers.get_lexer_by_name(lexer_name) except util.ClassNotFound: return None def _color_with_pygments(self, codeblock, lexer, **formatter_opts): import pygments import pygments.formatters class HtmlCodeFormatter(pygments.formatters.HtmlFormatter): def _wrap_code(self, inner): """A function for use in a Pygments Formatter which wraps in <code> tags. """ yield 0, "<code>" for tup in inner: yield tup yield 0, "</code>" def wrap(self, source, outfile): """Return the source with a code, pre, and div.""" return self._wrap_div(self._wrap_pre(self._wrap_code(source))) formatter_opts.setdefault("cssclass", "codehilite") formatter = HtmlCodeFormatter(**formatter_opts) return pygments.highlight(codeblock, lexer, formatter) def _code_block_sub(self, match, is_fenced_code_block=False): lexer_name = None if is_fenced_code_block: lexer_name = match.group(1) if lexer_name: formatter_opts = self.extras['fenced-code-blocks'] or {} codeblock = match.group(2) codeblock = codeblock[:-1] # drop one trailing newline else: codeblock = match.group(1) codeblock = self._outdent(codeblock) codeblock = self._detab(codeblock) codeblock = codeblock.lstrip('\n') # trim leading newlines codeblock = codeblock.rstrip() # trim trailing whitespace # Note: "code-color" extra is DEPRECATED. if "code-color" in self.extras and codeblock.startswith(":::"): lexer_name, rest = codeblock.split('\n', 1) lexer_name = lexer_name[3:].strip() codeblock = rest.lstrip("\n") # Remove lexer declaration line. formatter_opts = self.extras['code-color'] or {} if lexer_name: lexer = self._get_pygments_lexer(lexer_name) if lexer: colored = self._color_with_pygments(codeblock, lexer, **formatter_opts) return "\n\n%s\n\n" % colored codeblock = self._encode_code(codeblock) pre_class_str = self._html_class_str_from_tag("pre") code_class_str = self._html_class_str_from_tag("code") return "\n\n<pre%s><code%s>%s\n</code></pre>\n\n" % ( pre_class_str, code_class_str, codeblock) def _html_class_str_from_tag(self, tag): """Get the appropriate ' class="..."' string (note the leading space), if any, for the given tag. """ if "html-classes" not in self.extras: return "" try: html_classes_from_tag = self.extras["html-classes"] except TypeError: return "" else: if tag in html_classes_from_tag: return ' class="%s"' % html_classes_from_tag[tag] return "" def _do_code_blocks(self, text): """Process Markdown `<pre><code>` blocks.""" code_block_re = re.compile(r''' (?:\n\n|\A\n?) ( # $1 = the code block -- one or more lines, starting with a space/tab (?: (?:[ ]{%d} | \t) # Lines must start with a tab or a tab-width of spaces .*\n+ )+ ) ((?=^[ ]{0,%d}\S)|\Z) # Lookahead for non-space at line-start, or end of doc ''' % (self.tab_width, self.tab_width), re.M | re.X) return code_block_re.sub(self._code_block_sub, text) _fenced_code_block_re = re.compile(r''' (?:\n\n|\A\n?) ^```([\w+-]+)?[ \t]*\n # opening fence, $1 = optional lang (.*?) # $2 = code block content ^```[ \t]*\n # closing fence ''', re.M | re.X | re.S) def _fenced_code_block_sub(self, match): return self._code_block_sub(match, is_fenced_code_block=True); def _do_fenced_code_blocks(self, text): """Process ```-fenced unindented code blocks ('fenced-code-blocks' extra).""" return self._fenced_code_block_re.sub(self._fenced_code_block_sub, text) # Rules for a code span: # - backslash escapes are not interpreted in a code span # - to include one or or a run of more backticks the delimiters must # be a longer run of backticks # - cannot start or end a code span with a backtick; pad with a # space and that space will be removed in the emitted HTML # See `test/tm-cases/escapes.text` for a number of edge-case # examples. _code_span_re = re.compile(r''' (?<!\\) (`+) # \1 = Opening run of ` (?!`) # See Note A test/tm-cases/escapes.text (.+?) # \2 = The code block (?<!`) \1 # Matching closer (?!`) ''', re.X | re.S) def _code_span_sub(self, match): c = match.group(2).strip(" \t") c = self._encode_code(c) return "<code>%s</code>" % c def _do_code_spans(self, text): # * Backtick quotes are used for <code></code> spans. # # * You can use multiple backticks as the delimiters if you want to # include literal backticks in the code span. So, this input: # # Just type ``foo `bar` baz`` at the prompt. # # Will translate to: # # <p>Just type <code>foo `bar` baz</code> at the prompt.</p> # # There's no arbitrary limit to the number of backticks you # can use as delimters. If you need three consecutive backticks # in your code, use four for delimiters, etc. # # * You can use spaces to get literal backticks at the edges: # # ... type `` `bar` `` ... # # Turns to: # # ... type <code>`bar`</code> ... return self._code_span_re.sub(self._code_span_sub, text) def _encode_code(self, text): """Encode/escape certain characters inside Markdown code runs. The point is that in code, these characters are literals, and lose their special Markdown meanings. """ replacements = [ # Encode all ampersands; HTML entities are not # entities within a Markdown code span. ('&', '&amp;'), # Do the angle bracket song and dance: ('<', '&lt;'), ('>', '&gt;'), ] for before, after in replacements: text = text.replace(before, after) hashed = _hash_text(text) self._escape_table[text] = hashed return hashed _strong_re = re.compile(r"(\*\*|__)(?=\S)(.+?[*_]*)(?<=\S)\1", re.S) _em_re = re.compile(r"(\*|_)(?=\S)(.+?)(?<=\S)\1", re.S) _code_friendly_strong_re = re.compile(r"\*\*(?=\S)(.+?[*_]*)(?<=\S)\*\*", re.S) _code_friendly_em_re = re.compile(r"\*(?=\S)(.+?)(?<=\S)\*", re.S) def _do_italics_and_bold(self, text): # <strong> must go first: if "code-friendly" in self.extras: text = self._code_friendly_strong_re.sub(r"<strong>\1</strong>", text) text = self._code_friendly_em_re.sub(r"<em>\1</em>", text) else: text = self._strong_re.sub(r"<strong>\2</strong>", text) text = self._em_re.sub(r"<em>\2</em>", text) return text # "smarty-pants" extra: Very liberal in interpreting a single prime as an # apostrophe; e.g. ignores the fact that "round", "bout", "twer", and # "twixt" can be written without an initial apostrophe. This is fine because # using scare quotes (single quotation marks) is rare. _apostrophe_year_re = re.compile(r"'(\d\d)(?=(\s|,|;|\.|\?|!|$))") _contractions = ["tis", "twas", "twer", "neath", "o", "n", "round", "bout", "twixt", "nuff", "fraid", "sup"] def _do_smart_contractions(self, text): text = self._apostrophe_year_re.sub(r"&#8217;\1", text) for c in self._contractions: text = text.replace("'%s" % c, "&#8217;%s" % c) text = text.replace("'%s" % c.capitalize(), "&#8217;%s" % c.capitalize()) return text # Substitute double-quotes before single-quotes. _opening_single_quote_re = re.compile(r"(?<!\S)'(?=\S)") _opening_double_quote_re = re.compile(r'(?<!\S)"(?=\S)') _closing_single_quote_re = re.compile(r"(?<=\S)'") _closing_double_quote_re = re.compile(r'(?<=\S)"(?=(\s|,|;|\.|\?|!|$))') def _do_smart_punctuation(self, text): """Fancifies 'single quotes', "double quotes", and apostrophes. Converts --, ---, and ... into en dashes, em dashes, and ellipses. Inspiration is: <http://daringfireball.net/projects/smartypants/> See "test/tm-cases/smarty_pants.text" for a full discussion of the support here and <http://code.google.com/p/python-markdown2/issues/detail?id=42> for a discussion of some diversion from the original SmartyPants. """ if "'" in text: # guard for perf text = self._do_smart_contractions(text) text = self._opening_single_quote_re.sub("&#8216;", text) text = self._closing_single_quote_re.sub("&#8217;", text) if '"' in text: # guard for perf text = self._opening_double_quote_re.sub("&#8220;", text) text = self._closing_double_quote_re.sub("&#8221;", text) text = text.replace("---", "&#8212;") text = text.replace("--", "&#8211;") text = text.replace("...", "&#8230;") text = text.replace(" . . . ", "&#8230;") text = text.replace(". . .", "&#8230;") return text _block_quote_re = re.compile(r''' ( # Wrap whole match in \1 ( ^[ \t]*>[ \t]? # '>' at the start of a line .+\n # rest of the first line (.+\n)* # subsequent consecutive lines \n* # blanks )+ ) ''', re.M | re.X) _bq_one_level_re = re.compile('^[ \t]*>[ \t]?', re.M); _html_pre_block_re = re.compile(r'(\s*<pre>.+?</pre>)', re.S) def _dedent_two_spaces_sub(self, match): return re.sub(r'(?m)^ ', '', match.group(1)) def _block_quote_sub(self, match): bq = match.group(1) bq = self._bq_one_level_re.sub('', bq) # trim one level of quoting bq = self._ws_only_line_re.sub('', bq) # trim whitespace-only lines bq = self._run_block_gamut(bq) # recurse bq = re.sub('(?m)^', ' ', bq) # These leading spaces screw with <pre> content, so we need to fix that: bq = self._html_pre_block_re.sub(self._dedent_two_spaces_sub, bq) return "<blockquote>\n%s\n</blockquote>\n\n" % bq def _do_block_quotes(self, text): if '>' not in text: return text return self._block_quote_re.sub(self._block_quote_sub, text) def _form_paragraphs(self, text): # Strip leading and trailing lines: text = text.strip('\n') # Wrap <p> tags. grafs = [] for i, graf in enumerate(re.split(r"\n{2,}", text)): if graf in self.html_blocks: # Unhashify HTML blocks grafs.append(self.html_blocks[graf]) else: cuddled_list = None if "cuddled-lists" in self.extras: # Need to put back trailing '\n' for `_list_item_re` # match at the end of the paragraph. li = self._list_item_re.search(graf + '\n') # Two of the same list marker in this paragraph: a likely # candidate for a list cuddled to preceding paragraph # text (issue 33). Note the `[-1]` is a quick way to # consider numeric bullets (e.g. "1." and "2.") to be # equal. if (li and len(li.group(2)) <= 3 and li.group("next_marker") and li.group("marker")[-1] == li.group("next_marker")[-1]): start = li.start() cuddled_list = self._do_lists(graf[start:]).rstrip("\n") assert cuddled_list.startswith("<ul>") or cuddled_list.startswith("<ol>") graf = graf[:start] # Wrap <p> tags. graf = self._run_span_gamut(graf) grafs.append("<p>" + graf.lstrip(" \t") + "</p>") if cuddled_list: grafs.append(cuddled_list) return "\n\n".join(grafs) def _add_footnotes(self, text): if self.footnotes: footer = [ '<div class="footnotes">', '<hr' + self.empty_element_suffix, '<ol>', ] for i, id in enumerate(self.footnote_ids): if i != 0: footer.append('') footer.append('<li id="fn-%s">' % id) footer.append(self._run_block_gamut(self.footnotes[id])) backlink = ('<a href="#fnref-%s" ' 'class="footnoteBackLink" ' 'title="Jump back to footnote %d in the text.">' '&#8617;</a>' % (id, i+1)) if footer[-1].endswith("</p>"): footer[-1] = footer[-1][:-len("</p>")] \ + '&nbsp;' + backlink + "</p>" else: footer.append("\n<p>%s</p>" % backlink) footer.append('</li>') footer.append('</ol>') footer.append('</div>') return text + '\n\n' + '\n'.join(footer) else: return text # Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin: # http://bumppo.net/projects/amputator/ _ampersand_re = re.compile(r'&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)') _naked_lt_re = re.compile(r'<(?![a-z/?\$!])', re.I) _naked_gt_re = re.compile(r'''(?<![a-z0-9?!/'"-])>''', re.I) def _encode_amps_and_angles(self, text): # Smart processing for ampersands and angle brackets that need # to be encoded. text = self._ampersand_re.sub('&amp;', text) # Encode naked <'s text = self._naked_lt_re.sub('&lt;', text) # Encode naked >'s # Note: Other markdown implementations (e.g. Markdown.pl, PHP # Markdown) don't do this. text = self._naked_gt_re.sub('&gt;', text) return text def _encode_backslash_escapes(self, text): for ch, escape in list(self._escape_table.items()): text = text.replace("\\"+ch, escape) return text _auto_link_re = re.compile(r'<((https?|ftp):[^\'">\s]+)>', re.I) def _auto_link_sub(self, match): g1 = match.group(1) return '<a href="%s">%s</a>' % (g1, g1) _auto_email_link_re = re.compile(r""" < (?:mailto:)? ( [-.\w]+ \@ [-\w]+(\.[-\w]+)*\.[a-z]+ ) > """, re.I | re.X | re.U) def _auto_email_link_sub(self, match): return self._encode_email_address( self._unescape_special_chars(match.group(1))) def _do_auto_links(self, text): text = self._auto_link_re.sub(self._auto_link_sub, text) text = self._auto_email_link_re.sub(self._auto_email_link_sub, text) return text def _encode_email_address(self, addr): # Input: an email address, e.g. "foo@example.com" # # Output: the email address as a mailto link, with each character # of the address encoded as either a decimal or hex entity, in # the hopes of foiling most address harvesting spam bots. E.g.: # # <a href="&#x6D;&#97;&#105;&#108;&#x74;&#111;:&#102;&#111;&#111;&#64;&#101; # x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;">&#102;&#111;&#111; # &#64;&#101;x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;</a> # # Based on a filter by Matthew Wickline, posted to the BBEdit-Talk # mailing list: <http://tinyurl.com/yu7ue> chars = [_xml_encode_email_char_at_random(ch) for ch in "mailto:" + addr] # Strip the mailto: from the visible part. addr = '<a href="%s">%s</a>' \ % (''.join(chars), ''.join(chars[7:])) return addr def _do_link_patterns(self, text): """Caveat emptor: there isn't much guarding against link patterns being formed inside other standard Markdown links, e.g. inside a [link def][like this]. Dev Notes: *Could* consider prefixing regexes with a negative lookbehind assertion to attempt to guard against this. """ link_from_hash = {} for regex, repl in self.link_patterns: replacements = [] for match in regex.finditer(text): if hasattr(repl, "__call__"): href = repl(match) else: href = match.expand(repl) replacements.append((match.span(), href)) for (start, end), href in reversed(replacements): escaped_href = ( href.replace('"', '&quot;') # b/c of attr quote # To avoid markdown <em> and <strong>: .replace('*', self._escape_table['*']) .replace('_', self._escape_table['_'])) link = '<a href="%s">%s</a>' % (escaped_href, text[start:end]) hash = _hash_text(link) link_from_hash[hash] = link text = text[:start] + hash + text[end:] for hash, link in list(link_from_hash.items()): text = text.replace(hash, link) return text def _unescape_special_chars(self, text): # Swap back in all the special characters we've hidden. for ch, hash in list(self._escape_table.items()): text = text.replace(hash, ch) return text def _outdent(self, text): # Remove one level of line-leading tabs or spaces return self._outdent_re.sub('', text)