Code Examples
- Code Examples
This article provides a comprehensive guide to using code examples within MediaWiki, specifically tailored for beginners. We'll cover various methods for displaying code, proper formatting, syntax highlighting, and best practices for ensuring readability and maintainability. Understanding how to effectively present code snippets is crucial for technical documentation, tutorials, and collaborative projects hosted on a wiki. This guide will assume you're using MediaWiki version 1.40 or later, which provides robust support for code formatting.
- Why Use Code Examples?
Code examples are vital for several reasons:
- **Clarity:** They illustrate concepts in a concrete way, making abstract explanations easier to grasp. A well-chosen example can replace pages of prose.
- **Reproducibility:** Users can copy and paste code examples to test and experiment, fostering a deeper understanding.
- **Accuracy:** Code provides a precise, unambiguous definition of what's being explained.
- **Collaboration:** Shared code examples facilitate collaboration and knowledge sharing among users.
- **Troubleshooting:** Examples can help users identify and resolve issues in their own code.
- **Demonstration:** Showing a working solution reinforces learning and provides a practical application of theory. Consider how crucial examples are in understanding Technical Analysis.
- Basic Code Display: The `<source>` Tag
The most fundamental way to display code in MediaWiki is using the `<source>` tag. This tag simply renders the enclosed text in a monospace font, preserving whitespace and line breaks.
Syntax:
```wiki <source> // This is a simple JavaScript example function greet(name) {
console.log("Hello, " + name + "!");
} greet("World"); </source> ```
Result:
<source> // This is a simple JavaScript example function greet(name) {
console.log("Hello, " + name + "!");
} greet("World"); </source>
The `<source>` tag is useful for short snippets and when syntax highlighting isn't necessary. However, for larger or more complex code blocks, it can become difficult to read.
- Syntax Highlighting with `<syntaxhighlight>`
MediaWiki provides the `<syntaxhighlight>` tag for adding syntax highlighting to code examples. This dramatically improves readability by coloring keywords, comments, strings, and other code elements. The `<syntaxhighlight>` tag relies on the GeSHi (Generic Syntax Highlighter) extension, which needs to be installed and configured on your MediaWiki site. Most standard MediaWiki installations include GeSHi.
Syntax:
```wiki <syntaxhighlight lang="javascript"> // This is a simple JavaScript example function greet(name) {
console.log("Hello, " + name + "!");
} greet("World"); </syntaxhighlight> ```
Result:
<syntaxhighlight lang="javascript"> // This is a simple JavaScript example function greet(name) {
console.log("Hello, " + name + "!");
} greet("World"); </syntaxhighlight>
- Important:** The `lang` attribute specifies the programming language. GeSHi supports a wide range of languages. If the language is not supported, the code will be displayed without highlighting. Refer to the GeSHi website for a complete list of supported languages.
- Supported Languages
Here's a partial list of languages commonly used with `<syntaxhighlight>`:
- `javascript`
- `python`
- `java`
- `c`
- `cpp`
- `csharp`
- `php`
- `html`
- `css`
- `sql`
- `bash`
- `perl`
- `ruby`
- `xml`
- `json`
- `go`
- `swift`
- `kotlin`
Knowing the correct `lang` identifier is crucial. Incorrect identifiers will result in unhighlighted code.
- Advanced `<syntaxhighlight>` Options
The `<syntaxhighlight>` tag offers several advanced options:
- **`line-numbers`:** Displays line numbers.
```wiki <syntaxhighlight lang="python" line-numbers> # A simple Python example def square(x): return x * x print(square(5)) </syntaxhighlight> ```
- **`collapse`:** Collapses the code block by default, allowing users to expand it. This is useful for long code examples.
```wiki <syntaxhighlight lang="java" collapse> // A long Java example... </syntaxhighlight> ```
- **`first-line`:** Specifies the first line number to display (if `line-numbers` is used).
```wiki <syntaxhighlight lang="c" line-numbers first-line="10"> // Code with line numbers starting from 10 </syntaxhighlight> ```
- **`tabsize`:** Sets the tab size in spaces. Defaults to 4.
```wiki <syntaxhighlight lang="python" tabsize="2"> # Python code with tabs set to 2 spaces </syntaxhighlight> ```
- **`brush`:** Allows you to specify a custom brush if the default highlighting for a language is not satisfactory. This is an advanced feature requiring knowledge of GeSHi brush configuration.
- Using Templates for Consistent Formatting
For complex projects, creating a template for displaying code examples can significantly improve consistency. A template encapsulates the `<syntaxhighlight>` tag and its options, allowing you to apply the same formatting to all code examples.
Example Template (Template:CodeExample):
```wiki
```
Usage:
```wiki Template:CodeExample ```
This template takes four parameters:
1. `lang`: The programming language. 2. `line-numbers`: `true` or `false` to enable line numbers. 3. `collapse`: `true` or `false` to collapse the code block. 4. `code`: The code itself.
Templates make it easy to change the formatting of all code examples on your wiki by modifying the template definition. This is especially beneficial for large-scale documentation projects. Consider how this relates to managing Trading Strategies.
- Best Practices for Code Examples
- **Keep it concise:** Focus on illustrating a specific concept. Avoid including unnecessary code.
- **Comment your code:** Explain what the code does, especially if it's complex. Clear comments are essential for understanding.
- **Use meaningful variable names:** Choose names that clearly indicate the purpose of the variables.
- **Format your code consistently:** Use consistent indentation and spacing. Tools like linters can help with this.
- **Test your code:** Ensure that the code examples actually work before publishing them.
- **Provide context:** Explain the purpose of the code example and how it relates to the surrounding text. This is crucial when discussing Market Trends.
- **Use appropriate language:** Choose a language that is relevant to the topic and the audience.
- **Consider accessibility:** Ensure that the code is accessible to users with disabilities. Using clear and descriptive comments can help.
- **Avoid excessively long lines:** Long lines can be difficult to read. Break them up into smaller lines.
- **Use proper escaping:** If your code contains MediaWiki markup characters (e.g., ``, ``, ``), escape them using backslashes (`\\`). This prevents the wiki from interpreting them as markup.
- Dealing with Complex Code and External Files
For very large or complex code examples, it's often impractical to include them directly in the wiki page. Consider these alternatives:
- **Linking to external files:** Store the code in a separate file (e.g., on GitHub, GitLab, or a similar code repository) and link to it from the wiki page.
- **Using `pre` and `code` tags:** While `<syntaxhighlight>` is preferred, you can use the `pre` and `code` tags for simple code display without syntax highlighting.
- **Embedding code using iframes:** This allows you to display code from external sources in a sandboxed environment.
- Integrating Code Examples with Other Wiki Content
Code examples are most effective when integrated with other wiki content. For example:
- **Tutorials:** Use code examples to illustrate the steps in a tutorial. Relate these steps to Candlestick Patterns.
- **Documentation:** Provide code examples to demonstrate how to use functions, classes, and APIs.
- **API references:** Include code examples to show how to call API endpoints.
- **Troubleshooting guides:** Use code examples to illustrate common errors and how to fix them. Relate to common errors in Algorithmic Trading.
- **Comparison tables:** Use code examples to compare different approaches to solving a problem.
- Troubleshooting Syntax Highlighting Issues
If syntax highlighting isn't working as expected, consider these potential causes:
- **GeSHi extension not installed:** Verify that the GeSHi extension is installed and enabled on your MediaWiki site.
- **Incorrect language identifier:** Double-check that you're using the correct `lang` attribute.
- **Unsupported language:** The language you're trying to highlight may not be supported by GeSHi.
- **Syntax errors in the code:** Syntax errors can sometimes interfere with syntax highlighting.
- **Caching issues:** Clear your browser cache and the MediaWiki cache.
- **Conflicting extensions:** Other extensions may be interfering with GeSHi. Try disabling other extensions temporarily to see if that resolves the issue.
- Resources for Further Learning
- MediaWiki Help:Formatting code: [1]
- GeSHi Website: [2]
- GitHub: [3]
- GitLab: [4]
- Technical Analysis Basics: [5]
- Candlestick Patterns: [6]
- Moving Averages: [7]
- Bollinger Bands: [8]
- Fibonacci Retracement: [9]
- MACD: [10]
- RSI: [11]
- Trading Strategies: [12]
- Day Trading: [13]
- Swing Trading: [14]
- Scalping: [15]
- Algorithmic Trading: [16]
- Risk Management in Trading: [17]
- Market Sentiment: [18]
- Support and Resistance Levels: [19]
- Trendlines: [20]
- Chart Patterns: [21]
- Elliott Wave Theory: [22]
- Ichimoku Cloud: [23]
- Volume Analysis: [24]
- Forex Trading: [25]
- Options Trading: [26]
Help:Contents
MediaWiki syntax
Templates
GeSHi
Extension:GeSHi
Help:Formatting
Help:Editing
MediaWiki
Manual:Configuration settings
Special:AllPages
Main Page
Start Trading Now
Sign up at IQ Option (Minimum deposit $10) Open an account at Pocket Option (Minimum deposit $5)
Join Our Community
Subscribe to our Telegram channel @strategybin to receive: ✓ Daily trading signals ✓ Exclusive strategy analysis ✓ Market trend alerts ✓ Educational materials for beginners