Visual Studio Code CheatSheet
Visual Studio Code text editorGo to video for this category
User Interface
Activity Bar
Icon | Shortcut | Action |
---|---|---|
Shift+Cmd+E | Explorer (File Tree) | |
Shift+Cmd+F | Search | |
Shift+Cmd+G | Source Control (Git) | |
Shift+Cmd+D | Run and Debug (Code Debugger) | |
Shift+Cmd+X | Extensions (Install 3rd party extensions) | |
Manage (Settings, Shortcuts, Snippets, Themes) |
Run Terminal
Terminal menu > New Terminal
Add Extensions
Click the Extensions icon > Type in the extension name > click Install
Examples
Live Server:
- Find and install the Live Server extension. This allows you to run a web server that automatically reloads every time you save a file in your web project:
Click the Extensions icon on the Activity Bar > type "Live Server" in the search box > click Install
- To use Live Server: Open an HTML document in VS Code > Right click in the Editor > select "Open with Live Server". The HTML page will automatically open in your default web browser.
JavaScript ES6 Code Snippets:
- Find and install the JavaScript ES6 Code Snippets extension.
Click the Extensions icon on the Activity Bar > type "JavaScript ES6 Code Snippets" in the search box > Click install
- To use ES6 Snippets: Type in a shortcut followed by tab and the snippet will be added.
Launch Live Server
Rt click on HTML page > Open with Live Server
The page will open in the browser at http://127.0.0.1:5500
Stop Live Server:
Rt click page in VS Code > Stop Live Server
Command Pallet
Cmd+Shift+P Open Command Pallet.Access all available commands based on your current context.
code.visualstudio.com/docs/getstarted/tips-and-tricks#_command-palette
code.visualstudio.com/docs/getstarted/tips-and-tricks#_command-palette
Change Color Theme
Code menu > Preferences > Color Theme > Select theme
Change Settings
File/Code menu > Preferences > Settings
or clickManage icon > Settings
- Type in settings property name in the search box.
Examples
- Tab size: Search for
Tab Size
> value:2
or4
- Word wrap: Search for
Word wrap
> value:on
oroff
- Minimap: Search for
minimap
> check or uncheckMinimap: Enabled
. - Enable Preview: Search for
enable preview
> check or uncheckEditor: Enable Preview
. - Vertical Rulers: Search for
rulers
> clickEdit in settings.json
> set "editor.rulers" to"editor.rulers": [80, 100],
or some other number(s) > Save the file. - Optionally, disable popup hints/suggestions and breadcrumbs:
- Quick suggestions: Search for
quick suggestions
> "other" valueoff
. - Hover (shows hints when hovering over your code): Search for
hover
> uncheckHover: Enabled
. - Parameter hints: Search for
parameter hints
> uncheckParameter Hints: Enabled
. - Suggest on trigger characters: Search for
Suggest on trigger characters
> uncheckEditor: Suggest on trigger characters
. - Breadcrumbs: Search for
breadcrumbs
> uncheckBreadcrumbs: Enabled
.
Keyboard Shortcuts
Action | Mac | Windows |
---|---|---|
Full list | MacOS.pdf | Windows.pdf |
Cut | Cmd+X | Ctrl+X |
Copy | Cmd+C | Ctrl+C |
Paste | Cmd+V | Ctrl+V |
Undo | Cmd+Z | Ctrl+Z |
Redo | Cmd+Shift+Z | Ctrl+Y |
Indent | Tab | Tab |
Unindent | Shift+Tab | Shift+Tab |
Toggle comment | Cmd+/ | Ctrl+/ |
Toggle block comment | Shift+Alt+A | Shift+Alt+A |
Scroll to bottom | Cmd+DownArrow | Ctrl+DownArrow |
Scroll to top | Cmd+UpArrow | Ctrl+UpArrow |
Move line down | Alt+DownArrow | Alt+DownArrow |
Move line up | Alt+UpArrow | Alt+UpArrow |
Copy line down | Shift+Alt+DownArrow | Shift+Alt+DownArrow |
Copy line up | Shift+Alt+UpArrow | Shift+Alt+UpArrow |
Find | Cmd+F | Ctrl+F |
Find and Replace | Cmd+Alt+F | Ctrl+H |
Search all files in project | Shift+Cmd+F | Shift+Ctrl+F |
Quick Open, Go to File… | Cmd+P | Ctrl+P |
Toggle sidebar visibility | Cmd+B | Ctrl+B |
Collapses selected file list | LeftArrow | LeftArrow |
Collapse all file lists | Cmd+LeftArrow | Ctrl+LeftArrow |
Change Shortcut Keys
Code > Preferences > Keyboard Shortcuts > Search Box: Type in command
View all customized keyboard shortcuts:
Code > Preferences > Keyboard Shortcuts > Click Open Keyboard Shortcuts icon
Example Changes
Redo: Cmd+Y
Replace: Cmd+H
BlockComment: Shift+Alt+/
Replace: Cmd+H
BlockComment: Shift+Alt+/
Snippets
List all snippets:Shift+Cmd+P > Insert Snippet > Select a snippet
Emmet abbreviations and snippets (HTML and CSS)
Instructions: code.visualstudio.com/docs/editor/emmetFull list docs.emmet.io/cheat-sheet
HTML Snippets
!→ Generate a skeleton HTML document.</ Auto closes open tag.
tag→ Generate tags
<tag></tag>
tag#id→ Generate tags with id
<tag id="id"></tag>
tag.className→ Generate tags with class
<tag class="className"></tag>
tag.class1.class2→ Generate tags with two classes
<tag class="class1 class2"></tag>
tag#id.class→ Generate tags with id and class
<tag id="id" class="class"></tag>
Examples
p→ Generate p tags
h1#main-heading→ Generate h1 tags with id
h2.text-center→ Generate h2 tags with class
img.rounded.float-start→ Generate tag with two classes
div#ex-1.border Generate div tags with id and class
<p></p>
h1#main-heading→ Generate h1 tags with id
<h1 id="main-heading"></h1>
h2.text-center→ Generate h2 tags with class
<h2 class="text-center"></p>
img.rounded.float-start→ Generate tag with two classes
<img class="rounded float-start">
div#ex-1.border Generate div tags with id and class
<div id="ex-1" class="border"></div>
Built-in JavaScript Snippets
if↓→ if statement.
ife→ if else statement.
switch↓→ switch statement.
tryc→ try catch block.
function↓→ function declaration.
new↓→ Instantiate new object.
foreach→ arr.forEach iterator.
for↓→ for loop.
forof→ for ...of loop (array).
forin→ for ...in loop (object).
while↓→ while loop.
dowhile→ do while loop.
log→ console.log().
error→ console.error().
warn→ console.warn().
setTimeout→ setTimeout function.
setInterval→ setInterval function.
ife→ if else statement.
switch↓→ switch statement.
tryc→ try catch block.
function↓→ function declaration.
new↓→ Instantiate new object.
foreach→ arr.forEach iterator.
for↓→ for loop.
forof→ for ...of loop (array).
forin→ for ...in loop (object).
while↓→ while loop.
dowhile→ do while loop.
log→ console.log().
error→ console.error().
warn→ console.warn().
setTimeout→ setTimeout function.
setInterval→ setInterval function.
JavaScript (ES6) code snippets
Import and export
imp→ imports entire module
imn→ imports entire module without module name
imd→ imports only a portion of the module using destructing
ime→ imports everything as alias from the module
ima→ imports a portion of the module as alias
rqr→ require package
req→ require package to const
mde→ default module.exports
env→ exports name variable export
enf→ exports name function export
edf→ exports default fn
ecl→ exports default class
ece→ exports default class by extending a base one
import fs from 'fs';
imn→ imports entire module without module name
import 'animate.css'
imd→ imports only a portion of the module using destructing
import {rename} from 'fs';
ime→ imports everything as alias from the module
import * as localAlias from 'fs';
ima→ imports a portion of the module as alias
import { rename as localRename } from 'fs';
rqr→ require package
require('');
req→ require package to const
const packageName = require('packageName');
mde→ default module.exports
module.exports = {};
env→ exports name variable export
const nameVariable = localVariable;
enf→ exports name function export
const log = (parameter) => { console.log(parameter);};
edf→ exports default fn
export default function fileName (parameter){ console.log(parameter);};
ecl→ exports default class
export default class Calculator { };
ece→ exports default class by extending a base one
export default class Calculator extends BaseClass { };
Class Helpers
con→ adds default constructor in the class
met→ creates a method inside a class
pge→ creates a getter property
pse→ creates a setter property
constructor() {}
met→ creates a method inside a class
add() {}
pge→ creates a getter property
get propertyName() {return value;}
pse→ creates a setter property
set propertyName(value) {}
Various Methods
fre→
fof→ for ... of loop
fin→ for ... in loop
anfn→ anonymous function
nfn→ named function
dob→ destructing object syntax
dar→ destructing array syntax
sti→ set interval helper method
sto→ set timeout helper method
prom→ creates a new Promise
thenc→ adds then and catch declaration to a promise
array.forEach(currentItem => {})
fof→ for ... of loop
for(const item of object) {}
fin→ for ... in loop
for(const item in object) {}
anfn→ anonymous function
(params) => {}
nfn→ named function
const add = (params) => {}
dob→ destructing object syntax
const {rename} = fs
dar→ destructing array syntax
const [first, second] = [1,2]
sti→ set interval helper method
setInterval(() => {});
sto→ set timeout helper method
setTimeout(() => {});
prom→ creates a new Promise
return new Promise((resolve, reject) => {});
thenc→ adds then and catch declaration to a promise
.then((res) => {}).catch((err) => {});
console.log(object)
cer→
console.error(object)
Create your own snippets
Ref: code.visualstudio.com/docs/editor/userdefinedsnippets#_create-your-own-snippets
"New Global Snippets file" applies to all languages.
Code/File > Preferences > User Snippets > select the language for which the snippets should appear.
"New Global Snippets file" applies to all languages.
JavaScript snippet example - Console-log-with-filename
- cl+Tab generates console.log that lists the file name.
{
"Console-log-with-filename": {
"prefix": "cl",
"body": "console.log('$TM_FILENAME:', $1);",
"description": "Log output to console with file name"
}
}
VS Code DebuggerGo to video for this category
More details
- Run menu: Most used Debugger commands.
- Open LiveServer: In the Status bar, click Go Live.
- This will launch the local development server (Live Server) and open the index.html document.
- Use to launch the chrome debugger when you have a launch.json configuration file.
- Launch Debugger: Click the button to launch the Debugger.
- If you have multiple configurations, use the dropdown box to select the appropriate configuration.
- Debug Sidebar: Has panels for Variables, Watch, CallStack, Breakpoints.
- ... Views and More Actions: Show/Hide panels and Debug console.
- Gear icon: Create/Open launch.json file.
- Debug Console: Displays console logs.
- Clear console icon: clears console.
- X: Closes console.
- Breakpoint: Red dot in the Editor margin.
Install non-JS Debuggers
Run menu > Install additional debuggers > Select Extension > Click installLaunch Debugger
Without a launch.json configuration file:
Run and Debug (⇧⌘F5) > Run and Debug button
With a launch.json configuration file: Node.js environment
- Initial setup:
Run and Debug > create a launch.json file > Node.js
- Launch debugger: Start Debugging button | F5 | Status bar: Launch program.
With a launch.json configuration file: Web Browser environment
- Initial setup:
Run and Debug > create a launch.json file > Web App
- Configuration: "url": "http://localhost:5500"
- Launch Debugger:
- Open with LiveServer or Status Bar: Go Live.
- Start Debugging button | F5 | Status Bar: Launch Chrome against localhost.
Breakpoints
debugger
JavaScript keyword creates a breakpoint.Toggle breakpoint (red dot): Click on editor margin left of line number
Advanced Breakpoints
Toggle Breakpoint (red dot):
- click on editor margin
- Run Menu > Toggle Breakpoint | F9
- Right click editor margin > Add Breakpoint
- Run menu > New Breakpoint > Inline Breakpoint | ⇧F9
- Right click breakpoint > Disable breakpoint
- Breakpoints panel > Toggle Activate all Breakpoints toolbar
- Breakpoints panel > Uncheck breakpoint
- Run menu > Disable All Breakpoints
- Click red dot
- Right click breakpoint > Remove breakpoint
- Breakpoints panel > Remove All Breakpoints toolbar
- Breakpoints panel > X (Remove Breakpoint)
- Run menu > Remove All Breakpoints
Console log a message. Put expressions in {}
- Right click editor margin > Logpoint
- Run menu > New Breakpoint > Logpoint
- Right click existing breakpoint > Edit breakpoint > Dropdown > Log Message
- Run menu > New Breakpoint > Conditional Breakpoint
- Right click existing breakpoint > Edit breakpoint > Dropdown > Expression
Expression condition: The breakpoint will be hit whenever the expression evaluates to true. i < 10
Add Exceptions Breakpoint: Debug Sidebar: Breakpoints panel:
Caught ExceptionsUncaught Exceptions
Examples
Uncaught exception: not thrown in a try/catch block
Caught exception: thrown in a try/catch block
throw new Error('This is an uncaught exception.');
Caught exception: thrown in a try/catch block
try {
throw new Error('This is a caught exception.')
}
catch(err) {
console.log(err.message);
}
Debug Toolbar:
Icon | Action | Explanation |
---|---|---|
Continue F5 | Resume normal program/script execution (up to the next breakpoint). | |
Step Over F10 | Execute the next method as a single command without inspecting or following its component steps. | |
Step Into F11 | Enter the next method to follow its execution line-by-line. | |
Step Out ⇧F11 | When inside a method or subroutine, return to the earlier execution context by completing remaining lines of the current method as though it were a single command. | |
Restart ⇧⌘F5 | Terminate the current program execution and start debugging again using the current run configuration. | |
Stop ⇧F5 | Terminate the current program execution. |
Debug Sidebar
Move debug sidebar: View menu > appearance > Move primary sidebar rightVariables:
- Local: variables in the current function's scope.
- Script: variables in the script scope.
- Global: methods and properties attached to the global object.
Call Stack: Stack of currently open functions.
Breakpoints: Lists all breakpoints. Uncheck to disable.
Debug Console
Open Debug console: View menu > Debug console
Move Debug console: View menu > appearance > panel position > bottom | right | left
Align Debug console: View menu > appearance > align panel > left | right
Move Debug console: View menu > appearance > panel position > bottom | right | left
Align Debug console: View menu > appearance > align panel > left | right
Chrome Dev Tools - Debugger
Open Dev Tools (Fn F12) > Sources tab
ESLintGo to video for this category
JS Style Guides (on GitHub): AirBnB | Google
Add ESLint to project
From the Terminal in the project root directory:
npm init -y Create a package.json file if not already installed. Requires Node.js.
npm init @eslint/config Add ESLint to the project.npm init -y Create a package.json file if not already installed. Requires Node.js.
Install packages? yConfig file: .eslintrc.json
How would you like to use ESLint? check syntax, find probs, enforce style
Type of modules? JS Modules | CommonJS
Framework? React | Vue | None of these
Uses TypeScript? No | Yes
Where does code run? Browser | Node | a all
How to define style? popular style guide > AirBnB
What format for config file? JSON
Install eslint-config-airbnb-base, eslint-plugin-import? Yes
Package Manager? npm | yarn | pnpm
Set/modify rules
Customize severity: off | warn | error
Set severity and options.
"rules": {
"rule-name": "off"|"warn"|"error", "rule-name": ["warn"|"error", { "option" }]
}
Examples
1. Turn off rule that disallows use of console.
2. Change severity of "no-plusplus" rule violation from error (red) to warning (yellow).
3. Add option "ignoreComments" to "max-len" rule. First element, severity, is required.
2. Change severity of "no-plusplus" rule violation from error (red) to warning (yellow).
3. Add option "ignoreComments" to "max-len" rule. First element, severity, is required.
.eslintrc.json
"rules": {
"no-console": "off", "no-plusplus": "warn", "max-len": ["error", { "ignoreComments": true }]
}
Run ESLint from the Terminal (VS Code ESLint extension not required)
./node_modules/.bin/eslint filename.jsDisable ESLint or specific rule in a file
/* eslint-disable */
Disable ESLint for entire file. Place at top of file./* eslint-disable rule-name */
Disable specific rule for whole file. Place at top.// eslint-disable-next-line rule-name
Disable specific rule for next line.// eslint-disable-line rule-name
Disable specific rule for current line.VS Code ESLint Extension
Ref: marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint
Install the extension:
Install the extension:
- Install ESLint Extension: Activity bar: Settings ⚙ > Search box: ESLint > Install btn.
- Install the ESLint npm package globally if not already installed: npm install -g eslint
- Enable ESLint: Activity bar: Extensions toolbar > select ESLint: Settings ⚙ > Enable.
- Disable ESLint: Activity bar: Extensions toolbar > ESLint: Settings ⚙ > Disable.
- Install ESLint in the project: eslint --init
- Answer the questions to install it.
- This installs ESLint and extension packages locally.
- And creates the .eslintrc.json. file and places it in the project root directory.
- To make .eslintrc.json the default for all projects, move it to: /Users/<username>
Disable ESLint for a particular project:
- Activity bar: Extensions toolbar > select ESLint: Settings ⚙ > Disable (workspace).
- Click squiggly underlined issues > Click lightbulb > Select option
- Terminal Panel > Problems tab: Lists all the Linter warnings and errors
Beginning GitGo to video for this category
General
What is Git? Define Version Control System
- Git is a free, open-source version control system (VCS).
- A VCS:
- Allows multiple developers to work on the same project simultaneously.
- Prevents changes from being overwritten.
- Maintains a retrievable history of each version.
- Git is also referred to as a source code manager since it is used to manage the source code for development projects.
- Git was developed by Linus Torvalds, the creator of Linux, in 2005.
- There are two types of VCSs: centralized and distributed. Git is distributed.
- Collaborators check out the full project from the central repository. They work on their changes independently, then changes are reviewed and committed.
- You create a repository and periodically store a version of your project by making a commit with the latest changes to the repository.
- Changes not committed can be discarded.
Install or Update Git on your computer
Check version and/or location:
git --version | -v Shows which version is installed.
which git returns the path of the git executable file.
git --version | -v Shows which version is installed.
which git returns the path of the git executable file.
View/download latest available version: git-scm.com/downloads
Under Downloads, click on your operating system.Mac example
If you have a Mac, check if Git is installed and up to date by checking the version:
- From the terminal run: git -v
- Compare it with the latest version available. See: git-scm.com
- If it is a minor version behind (major.minor.patch) you should update it.
- If you have XCode installed it includes a binary version of Git.
- If you use Homebrew as your Mac installer, it will install the latest version.
- There is an installer link here installs an older version.
- Check that Homebrew is installed: which brew
- Homebrew reference and installation instructions: brew.sh
- If you have homebrew installed: brew install git
Documentation/Help:
Online Docs: git-scm.com/docs | For a specific command: git-scm.com/docs/git-command-nameCommand line help:
git help command-name Help page for the command.Unix Less paging program: used by Git commands that return lots of text
Git help, log, show, diff use Less. To navigate the pages use the following keys:↑/↓ up/down line, g/G go to start/end.
u/d up/down half a screen, (f | space)/b forward/back one full screen
/search-term search for a term, n/N next/previous instance.
q Quit Less.
Git Text Editor
In some situations, Git may open your Unix text editor requesting you to add a message.
git var GIT_EDITOR Show the text editor used by Git.
git config --global core.editor 'code --wait' Set VS Code as your Git text editor.
If your Git text editor is Vi or Vim, use the following commands:
i insert text mode | esc key exits write mode | :wq writes the changes and quits the editor.
git var GIT_EDITOR Show the text editor used by Git.
git config --global core.editor 'code --wait' Set VS Code as your Git text editor.
If your Git text editor is Vi or Vim, use the following commands:
i insert text mode | esc key exits write mode | :wq writes the changes and quits the editor.
Config - Get and set repository or global options and aliases
git config --global init.defaultBranch main Set "main" as the default initial branch name.
git config --global user.name 'my-username' Set global git variable for user name.
git config --global user.email name@example.com Set email global git variable.
git config --global --unset variableName Remove global variable
git config --global --list List all global git variables.
With the global option --global or -g it applies to all repositories.
To override global variables: Set project config variables without the global option.
git config --global user.name 'my-username' Set global git variable for user name.
git config --global user.email name@example.com Set email global git variable.
git config --global --unset variableName Remove global variable
git config --global --list List all global git variables.
With the global option --global or -g it applies to all repositories.
To override global variables: Set project config variables without the global option.
Docs and examples
Docs: git-scm.com/docs/git-config | git help config
On Mac, git configuration is saved in your home directory in file: .gitconfig
Set and get global name and email:
git config --global user.email joey@example.com Quotes optional since there are no spaces.
git config --global user.name Get user name value.
git config --global user.email Get user email value.
git config --global --list Get all global variables.
Set name and email specifically for a local project (leave out the global option):
git config user.name 'Joey R.'
git config user.email joey@example.com
git config user.name Get user name value.
git config user,email Get user email value.
On Mac, git configuration is saved in your home directory in file: .gitconfig
Set and get global name and email:
- When you make Git commits, the meta data in each commit will include the user name and email of who made the commit.
- Set the global git variables for user name and email to Joey R. and joey@example.com.
git config --global user.email joey@example.com Quotes optional since there are no spaces.
git config --global user.name Get user name value.
git config --global user.email Get user email value.
git config --global --list Get all global variables.
Set name and email specifically for a local project (leave out the global option):
git config user.name 'Joey R.'
git config user.email joey@example.com
git config user.name Get user name value.
git config user,email Get user email value.
git config --global alias.name 'git command' Set alias for a git command. Run: git alias
git config --global alias.olog 'log --oneline' Set alias for oneline. git olog
git config --global alias.glog 'log --graph --oneline' Set alias for graph log. git glog
Set up a Local Git Repository
.gitignore
Create a .gitignore file. Add files/directories to it to exclude them from git.
Git ignore templates: github.com/github/gitignore
Git ignore templates: github.com/github/gitignore
.gitignore
node_modules/
.env
.DS_Store
Docs and more details
Docs: docs.github.com/../ignoring-files
.gitignore file lists all files and directories that should not be added to the git repository for security reasons (e.g., usernames and passwords), to conserve space (e.g., node_modules), or because they are not relevant to the project (e.g., MacOS .DS_store files).
.gitignore file lists all files and directories that should not be added to the git repository for security reasons (e.g., usernames and passwords), to conserve space (e.g., node_modules), or because they are not relevant to the project (e.g., MacOS .DS_store files).
Pattern | Explanation and Examples |
---|---|
# comment | Comments are prefaced with # |
name | A name by itself means all files and directories with this name. Ex: .DS_Store, .env, node_modules, notes |
directoryName/ | When the name ends with a slash it means all directories with this name. Ex: node_modules/, notes/ |
/name | File or directory in the project root directory. Ex: /.env, /node_modules/ |
*.ext | All files ending with the extension. Ex: *.md, *.test.js |
More details
If you add a file to .gitignore that has already been tracked, you must clear the cache to stop tracking it:
git rm --cached filename
If it is a directory, add the -r recursive option:
git rm -r --cached dirname
Note: It will still be in the previous git commits.
git rm --cached filename
If it is a directory, add the -r recursive option:
git rm -r --cached dirname
Note: It will still be in the previous git commits.
VS Code Source Control (Git integration)
Green U: new file untracked, A: added to staging area.
Yellow M: modified file.
Source Control toolbar
- If there are modified files to commit, the number of files will appear on the Source Control toolbar.
- Click the Source Control toolbar to view, stage, commit modified files.
- Modified files are grouped under "changes".
- Select a modified file to review/stage it:
- The file differences since last commit will appear in the editor.
- To add the changes to the staging area, click the + sign.
- To discard the changes since the last commit, click the looping arrow icon.
- To commit staged files, enter a commit message in the Message box then click the commit button.
Initiate a local Git repository and make your first commit
click Initialize Repository button
git add . Add all project files (not in .gitignore) to the staging area.
git commit -m 'First commit' Make the first commit.
Commits
You can save small groups of meaningful changes as commits.
A git commit holds a snapshot of your project files at the time of the commit.
Each commit includes:
A git commit holds a snapshot of your project files at the time of the commit.
Each commit includes:
- Meta information: Author name and email, commit message, date, commit id (SHA-1 number), parent commitId.
- A tree with the names and locations of files in the repository.
- Each file listed in the tree has a corresponding blob (binary large object) file.
The blob stores a compressed snapshot of the file contents.
The commit id (SHA-1 number), atomic commits
The Commit ID: is a 40-digit hexadecimal number generated with the SHA-1 cryptographic hash function.
It is both an identifier and a security device. All the important information from the commit are included in the hash. If any of it is changed, the hash will no longer match the underlying data.
Atomic commits:
There is no rule on how often should you make commits.
One popular strategy is called atomic commits.
Focus each commit around a specific completed coding task (e.g., bug fix, minor feature), rather than one commit for multiple unrelated changes. This makes it easier to search for the commit and review a particular coding task.
It is both an identifier and a security device. All the important information from the commit are included in the hash. If any of it is changed, the hash will no longer match the underlying data.
Atomic commits:
There is no rule on how often should you make commits.
One popular strategy is called atomic commits.
Focus each commit around a specific completed coding task (e.g., bug fix, minor feature), rather than one commit for multiple unrelated changes. This makes it easier to search for the commit and review a particular coding task.
The Git Environment
Graph explanation
When you initiate a local git repository with the git init command, it creates a folder called .git that stores the changes you commit.
Additionally, you may have a remote repository like Github to share or collaborate on projects, or for production (e.g., heroku).
Git has three areas:
Optionally, you may have a remote repository (e.g., Github, Bitbucket, Gitlab, Source Forge) used to backup, share, or collaborate on projects.
Commands:
Additionally, you may have a remote repository like Github to share or collaborate on projects, or for production (e.g., heroku).
Git has three areas:
- The working directory (git calls this the "working tree"): consists of files that you are currently working on.
- The staging area (git calls this the "index"): a temporary area where you queue up changed files before committing them. Git compares staged files to the same files in the repo. Files with changes are marked as modified.
- The repository: When you commit the staged modified files, they are added to the repository as a permanent, retrievable record. The commit is a snapshot of all your tracked files at that point in time.
Optionally, you may have a remote repository (e.g., Github, Bitbucket, Gitlab, Source Forge) used to backup, share, or collaborate on projects.
Commands:
- Git add adds the files in your working directory to the temporary staging area (except .gitignore files).
- Git commit permanently stores the files to the local git repository.
- Git checkout: If you have multiple git branches, git checkout will checkout the specified branch to your working directory.
- If you have a remote repository (e.g., github, heroku):
- Git push adds the commit to the remote repository.
- Git clone copies a remote repository to your local environment for the first time.
- Git fetch gets meta information about any changes committed by collaborators to a remote repository you are collaborating on.
- Git pull pulls the changes from a remote repository you are collaborating on.
Graph explanation
Your local Git repository maintains an index of files from your project. Files can be in one of the below states:
- Untracked files have not been committed. Git doesn't know about them yet.
- Tracked files exist in the Git repository from a previous commit.
- Tracked files can be either modified or unmodified since the last commit. Modified files can be added to the staging area to be committed.
- Staged files are files added to the staging area. Once you commit these files to the git repository, they become unmodified tracked files.
File State | Git Area | Explorer filename color | Source Control heading |
---|---|---|---|
Ignored: In the .gitignore file | n/a | Gray | n/a |
Untracked: New file/Not in Git
| Working_Directory Staging Area | Green U Green A | Changes Staged_Changes |
Tracked: Previously committed to Git
| n/a Working_Directory Staging Area | White Yellow M Yellow M | n/a Changes Staged_Changes |
Stage and Commit changes to Git
Stage files:
+
| ⋯ > Changes > Stage All Changes
git add <file1> <file2> <file3> Stage only specified files.
git add -u Stage only modified and deleted files (exclude new/untracked files).
Commit staged files:
Enter message in box > ✓
| ⋯ > Commit > Commit Staged
Difference between git add . and git add -A
You can stage all files with either:
- git add . Stages all files starting with the current directory. "." is the path to the current directory. If you are in the root directory, it will stage all files.
- git add -A | git add --all stages files in the project regardless of what directory you are currently in.
Stage and commit files in one command:
Commit button > Stage and commit all changes? Yes
| ⋯ > Commit > Commit All
Commit message
Suggested guidelines from git-scm.com
Commit message: Explain what you did.
Ref: https://git-scm.com/book/en/v2/Distributed-Git-Contributing-to-a-Project
Ref: https://git-scm.com/book/en/v2/Distributed-Git-Contributing-to-a-Project
- Capitalize first word (not each word).
- Don't end with a period
- Use present tense imperative mood: "Fix bug". Not: "Fixed bug" or "Fixes bug."
- Short messages: One line with max of 50 characters.
- Long messages: First line is a summary following the same rules as above.
- After the summary add a blank line.
- Then add the detailed explanation. Describe what was done and why, but not how.
- Wrap the body at 72 characters.
- Optionally prepend feat: if the commit is a feature. fix: if it is a bug fix. Ref: conventionalcommits.org
View status and file differences since since last commit
git status List branch name and which files are staged, unstaged, and untracked.
git diff [filename] Show differences in working directory files since last commit. Uses Unix Less to navigate.
git diff [filename] Show differences in working directory files since last commit. Uses Unix Less to navigate.
Examples. Color the specific words that changed with --color-words
git diff Show the differences in all files in the working directory since the last commit.
git diff --cached Show the differences in all files in the staging area since the last commit.
git diff app.js Show the differences in the app.js file since the last commit.
git diff --color-words Show word changes on same line. Green words added, red removed.
git diff --cached Show the differences in all files in the staging area since the last commit.
git diff app.js Show the differences in the app.js file since the last commit.
git diff --color-words Show word changes on same line. Green words added, red removed.
Previous Commits
Log - Print list of commits for the current branch
git log Returns all commits in reverse chronological order. Uses Unix Less to navigate.
Docs and log options
Docs: git-scm.com/docs/git-log | git help log
git log -<number> goes back n commits.
git log --since=YYYY-MM-DD commits since the specified date.
git log --until=YYYY-MM-DD commits until the specified date
git log --since="<number> <days | weeks> ago"
git log --since=<number>.<days | weeks>
git log <commit> commits up to the given commit (use all/part of the hash number)
git log <commit>.. commits since the given commit (use all/part of the hash number)
git log --grep="<pattern>" -i Log all commits containing the given keyword/phrase. -i makes it case insensitive.
git log <path> commits affecting a given path or filename.
git log --oneline Logs each commit on one line.
git log --graph --oneline Logs each commit on one line and graphically shows merges.
git log -p The --patch option shows the changes as diffs.
git log -L <start line number>,<end line number>:<filename> Log line range in specified file.
git log -<number> goes back n commits.
git log --since=YYYY-MM-DD commits since the specified date.
git log --until=YYYY-MM-DD commits until the specified date
git log --since="<number> <days | weeks> ago"
git log --since=<number>.<days | weeks>
git log <commit> commits up to the given commit (use all/part of the hash number)
git log <commit>.. commits since the given commit (use all/part of the hash number)
git log --grep="<pattern>" -i Log all commits containing the given keyword/phrase. -i makes it case insensitive.
git log <path> commits affecting a given path or filename.
git log --oneline Logs each commit on one line.
git log --graph --oneline Logs each commit on one line and graphically shows merges.
git log -p The --patch option shows the changes as diffs.
git log -L <start line number>,<end line number>:<filename> Log line range in specified file.
Show - Show metadata and content changes of a commit
git show commitID Uses Unix Less to navigate.Docs and examples
Docs: git-scm.com/docs/git-show | git help show
git show a25247f Shows details of commit with id that starts with a25247f. Can use as few as the first 4 characters.
git show HEAD Shows the latest commit.
git show HEAD^ Shows parent of the HEAD
git show HEAD^^ Shows grandparent of the HEAD
git show HEAD~3 Shows 3 generations back from the HEAD
git show a25247f Shows details of commit with id that starts with a25247f. Can use as few as the first 4 characters.
git show HEAD Shows the latest commit.
git show HEAD^ Shows parent of the HEAD
git show HEAD^^ Shows grandparent of the HEAD
git show HEAD~3 Shows 3 generations back from the HEAD
Branches - Use branches to work on new features and bug fixes
git branch Show all branches. Current branch has an asterisk in front of it.
git checkout <branchname> Switch to branch.
git checkout -b <branchname> Create a new branch and switch to it.
git diff main <branchname> Show differences between main and specified branch.
git merge <branchname> Merge branch into the branch you are in.
git branch -d <branchname> Delete a branch you no longer need. If conflicts use -D
⋯ > Check out to... branchName
⋯ > Branch > Create Branch
git diff main <branchname> Show differences between main and specified branch.
⋯ > Branch > Merge Branch > select branchName
⋯ > Branch > Delete Branch > select branchName
Docs and example
Docs: git-scm.com/docs/git-branch | git help branch
Step1: Create and checkout a new branch called "users" to add users to the application:
git checkout -b users
Step 2: Add, modify, delete files until the branch is complete.
Step 3: Stage and commit changes:
git add .
git commit -m 'Complete users resource'
Step 4: Switch back to the main branch:
git checkout main
Step 5: Merge users branch into main:
git merge users
Step 6: Delete the users branch if you no longer need it:
git branch -d users
Push the commit to the remote repository:
git push
Step1: Create and checkout a new branch called "users" to add users to the application:
git checkout -b users
Step 2: Add, modify, delete files until the branch is complete.
Step 3: Stage and commit changes:
git add .
git commit -m 'Complete users resource'
Step 4: Switch back to the main branch:
git checkout main
Step 5: Merge users branch into main:
git merge users
Step 6: Delete the users branch if you no longer need it:
git branch -d users
Push the commit to the remote repository:
git push
Intermediate GitGo to video for this category
Resolve Branch Merge conflicts
Conflicts occur when the main and current branch have commits with differences on the same line of a file.
After running git merge <branch>, if there is a conflict you can:
After running git merge <branch>, if there is a conflict you can:
- git merge --abort Abort the merge.
- Fix the conflict manually (see below).
- Fix the conflict using a built-in merge tool (git help mergetool).
Fix the conflict manually
Manually Fix Conflicts:
If there is a conflict during the merge, the merge will be paused and the file will appear in the working directory with the conflicting lines highlighted.
If there is a conflict during the merge, the merge will be paused and the file will appear in the working directory with the conflicting lines highlighted.
- Both versions will be shown separated by markers.
- Fix the code and remove the markers. VS Code facilitates this with buttons above the two versions:
- If you want to accept both changes click "Accept Both Changes".
- You can manually fix the top version then click "Accept Current Change".
- Or manually fix the bottom version then click "Accept Incoming Change".
- To see the differences side-by-side click "Compare Changes".
- Save the file.
- git status shows the unmerged file path. Then create a new commit that fixes the merge conflict.
- git add <filename> Stage the conflicting file.
- git commit -m 'Fix merge with branchname' Commit the fix.
- git log -3 View the last 3 commits. The Fix merge commit will be at the top.
Tags - Create tag names for important commits (e.g., version release, feature addition)
⋯ > Tags > Create Tag > Enter tag name > Optionally enter tag message
git tag -am 'message' <tagname> <commit> Create tag for a commit with optional message.
git push origin <tagname> Push a tag to the remote repository. --tags pushes all tags.
Use tags for releases. Semantic versioning: vMajor.Minor.Patch
Docs, semantic versioning, examples
Ref: git-scm.com/book/en/v2/Git-Basics-Tagging | git help tag
Semantic Versioning: semver.org
Create a tag:
Create tag named users-resource for the latest commit (which is the default):
git tag users-resource
Create tag named users-resource for commitId that starts with abcde:
git tag users-resource abcde
Create tag for release version 2.1.0. The commitId starts with abcde. Use the -am flags to annotate the message "Version 2.1.0 release":
git tag -am 'Version 2.1.0 release' v2.1.0 abcde
Push tag(s) to remote:
git push origin v2.1.0 Push the tag name "v2.1.0" to your remote named "origin".
git push origin --tags Push all tags to your remote server
Semantic Versioning: semver.org
Given a version number MAJOR.MINOR.PATCH, increment the:
- MAJOR version when you make incompatible API changes.
- MINOR version when you add functionality in a backwards compatible manner.
- PATCH version when you make backwards compatible bug fixes.
Create a tag:
Create tag named users-resource for the latest commit (which is the default):
git tag users-resource
Create tag named users-resource for commitId that starts with abcde:
git tag users-resource abcde
Create tag for release version 2.1.0. The commitId starts with abcde. Use the -am flags to annotate the message "Version 2.1.0 release":
git tag -am 'Version 2.1.0 release' v2.1.0 abcde
Push tag(s) to remote:
git push origin v2.1.0 Push the tag name "v2.1.0" to your remote named "origin".
git push origin --tags Push all tags to your remote server
Examples
List tags:
git tag -l List all tags without their annotation. --list is the option long version.
git tag -ln List all tags with their annotation.
git tag -l "v*" List all tags that begin with "v". Use wildcard "*".
git tag -l List all tags without their annotation. --list is the option long version.
git tag -ln List all tags with their annotation.
git tag -l "v*" List all tags that begin with "v". Use wildcard "*".
⋯ > Tags > Delete Tag > Select tag name
git push --delete origin <tagname> Delete tag from remote repository.
Refs
A ref is a human readable name that references a Git commit ID.It can be a branch name (for the head commit), a tag name, a remote name, a stash index.
Examples
Show the details of the latest commit for the articles branch:
git show articles
Show the details of the commit with the tag "Users-resource"
git show Users-resource
Show the details of the latest stash:
git show stash
Show the details of the second stash (i.e., with index 1):
git show stash 1
git show articles
Show the details of the commit with the tag "Users-resource"
git show Users-resource
Show the details of the latest stash:
git show stash
Show the details of the second stash (i.e., with index 1):
git show stash 1
Delete | Rename files
git rm <filename> Deletes the file.git mv oldname newname Renames the file
Example. Why delete/rename using git?
Delete the myfile.txt file.
git rm myfile.txt
Rename the index.html file to home.html from the command line:
git mv index.html home.html
Why delete/rename using git?
You could alternatively delete and rename files using your text editor's GUI or using Unix commands. However:
git rm myfile.txt
Rename the index.html file to home.html from the command line:
git mv index.html home.html
Why delete/rename using git?
You could alternatively delete and rename files using your text editor's GUI or using Unix commands. However:
- On deletion, you have to stage the deletion first before committing it.
- On renaming, git treats it as two operations. Deleting index.html and adding a new file home.html.
Git Undo/Redo
Table: Action -> Command
Action | Command |
---|---|
Move file(s) from staging area to Working Directory | git reset [path(s)] git restore -S path(s) |
Discard changes in Working Directory Delete untracked files from Working Directory | git restore [path(s)] git clean -f |
Amend last commit (new commit, remove previous) | git commit --amend -m 'msg' |
Reverse a prior commit with a new commit | git revert <commitId> |
Remove commits after specified commitId (Code since commitId moved to Working Directory) | git reset <commitId> |
Remove commits after specified commitId (Code since commitId deleted) | git reset --hard <commitId> |
Restore - Remove files from staging area | Discard changes
-
| ⋯ > Changes > Unstage All Changes
⟲
| ⋯ > Changes > Discard All Changes
Docs and examples
Docs: git-scm.com/docs/git-restore | git help restore
Move file(s) from the staging area back to the working directory:
Multiple files were added to the staging area. Move the app.js file back to the working directory:
git restore -S app.js
Move both the app.js and assets/styles.css files back to the working directory:
git restore -S app.js assets/styles.css
Move all files back to the working directory:
git restore -S .
Notes:
Discard changes since last commit:
Discard the changes to tracked files from the current directory since last commit:
git restore .
Discard any untracked files in the working directory (except those in gitignore):
git clean -f
Discard only the changes to the app.js file since your last commit:
git restore app.js
Move file(s) from the staging area back to the working directory:
Multiple files were added to the staging area. Move the app.js file back to the working directory:
git restore -S app.js
Move both the app.js and assets/styles.css files back to the working directory:
git restore -S app.js assets/styles.css
Move all files back to the working directory:
git restore -S .
Notes:
- The long version of the -S option is --staged.
- The git reset [filename] command can also be used to move all (or specified) staged files back to the working directory.
Discard changes since last commit:
Discard the changes to tracked files from the current directory since last commit:
git restore .
Discard any untracked files in the working directory (except those in gitignore):
git clean -f
Discard only the changes to the app.js file since your last commit:
git restore app.js
Clean - Remove untracked files from your working directory
git clean -n Show what files would be deleted, without deleting them.git clean -f --force deletes untracked files not in gitignore.
Amend - Combine this commit with last commit
Optionally enter new commit msg > ⋯ > Commit > Commit Staged (Amend)
git commit --amend --no-edit Leave the prior commit message unchanged.
Docs and examples
Docs: git-scm.com/docs/git-commit#Documentation/git-commit.txt---amend
Amend prior commit with new changes without changing the prior commit message:
Amend prior commit message without changing the files:
Amend prior commit with new changes without changing the prior commit message:
- After modifying and staging several files, committing them with the amend option combines the changes with your prior commit.
- The prior commit is deleted and replaced with the new amended commit.
- The --no-edit option uses the prior commit message for this commit.
Amend prior commit message without changing the files:
- Do not stage any changed files.
- Make a commit with the --amend option and new message: "Add users resource".
Commit identifiers:
<commit> can be a commitId, tag, branch, or relative reference to HEAD.Head (last commit), head^ (1 before last commit), head~n (n before last commit).
Revert - Undo the changes from a specified commit with a new commit
git revert <commit> Add a new commit that undoes all the changes made in commitId.
Docs and example
Docs: git-scm.com/docs/git-revert | git help revert
Find a specific commit, then add a new commit that undoes the changes from that commit.
git log -2 Log your last 2 commits. Copy the first 5 or more digits of the commitId you want (e.g., a4c652)
git revert a4c652
To revert the changes made in the last commit you can use "head" instead of the commitId.
git revert head
Find a specific commit, then add a new commit that undoes the changes from that commit.
git log -2 Log your last 2 commits. Copy the first 5 or more digits of the commitId you want (e.g., a4c652)
git revert a4c652
To revert the changes made in the last commit you can use "head" instead of the commitId.
git revert head
Reset - Remove files from staging area | Undo prior commits
⋯ > Commit > Undo Last Commit
git reset <commit> Remove commits after <commit>. Changes since then are placed in working directory.
git reset --hard <commit> Remove commits after <commit>. Changes since then are lost.
Docs and examples
Docs: git-scm.com/docs/git-reset | git help reset
Example 1 (unstage): Remove files from staging area back to the working directory examples.
Multiple files were added to the staging area. Move all of them back to the working directory:
git reset
Move the app.js file back to the working directory:
git reset app.js
Move both the app.js and assets/styles.css files back to the working directory:
git reset app.js assets/styles.css
Note: The git restore --staged filename command will also move the specified file(s) back to the working directory.
Example 2 (Combine prior commits): Combine all commits in the current branch "new-feature" into one commit:
git reset --soft main Move head back to the main branch. Delete all commits in the current branch. Changes from the deleted commits are in the staging area.
git commit -m 'Mssg' Make a single commit for all the changes in the branch.
From here you can checkout the main branch then merge the feature branch in as one single commit:
git checkout main
git merge new-feature
Example 3 (Modify prior commits): Modify last 2 commits, make new commit, delete the 2 old commits:
git reset head~3 Move head to 3 commits ago, delete last 2 commits, changes from deleted commits are in the Working Directory.
Make the needed changes to the files in the Working Directory.
git add . Stage the modified/added/deleted files.
git commit -m 'Mssg' Commit the changes.
Example 4 (Delete prior commits): Find a specific commit. Undo the changes since that commit and delete them.
git log -5 --oneline Log the last 5 commits. Find the commit message you are looking for. Copy the commitId (the first 4 or more characters).
git reset --hard commitId Move head to commitId. Delete the commits since commitId. All changes are discarded.
Example 1 (unstage): Remove files from staging area back to the working directory examples.
Multiple files were added to the staging area. Move all of them back to the working directory:
git reset
Move the app.js file back to the working directory:
git reset app.js
Move both the app.js and assets/styles.css files back to the working directory:
git reset app.js assets/styles.css
Note: The git restore --staged filename command will also move the specified file(s) back to the working directory.
Example 2 (Combine prior commits): Combine all commits in the current branch "new-feature" into one commit:
git reset --soft main Move head back to the main branch. Delete all commits in the current branch. Changes from the deleted commits are in the staging area.
git commit -m 'Mssg' Make a single commit for all the changes in the branch.
From here you can checkout the main branch then merge the feature branch in as one single commit:
git checkout main
git merge new-feature
Example 3 (Modify prior commits): Modify last 2 commits, make new commit, delete the 2 old commits:
git reset head~3 Move head to 3 commits ago, delete last 2 commits, changes from deleted commits are in the Working Directory.
Make the needed changes to the files in the Working Directory.
git add . Stage the modified/added/deleted files.
git commit -m 'Mssg' Commit the changes.
Example 4 (Delete prior commits): Find a specific commit. Undo the changes since that commit and delete them.
git log -5 --oneline Log the last 5 commits. Find the commit message you are looking for. Copy the commitId (the first 4 or more characters).
git reset --hard commitId Move head to commitId. Delete the commits since commitId. All changes are discarded.
Rebase Interactive - Reorder, combine, edit, delete previous commits
git rebase -i <commit> Place commits since <commit> in your text editor to rebase.
git rebase --abort Abort rebase and get back to the state before "git rebase".
⋯ > Commit > Abort Rebase
Docs and more info
Docs: git-scm.com/docs/git-rebase | official_tutorial | git help rebase
git rebase -i main Gets all commits in the current branch (if "main" is the parent branch).
Puts all your branch's commits in your text editor, in order with oldest first. Each is prefaced with "pick".
Follow the instructions printed in the editor.
git rebase -i <parentBranch> Gets all commits in the current branch.
git rebase -i HEAD~3 Gets last 3 commits.
git rebase -i commitId Gets commit after commitId.
git rebase -i --root Gets all your commits.
Note: When collaborating on a project, don't rebase commits once they've been pushed to the shared repository.
git rebase -i main Gets all commits in the current branch (if "main" is the parent branch).
Puts all your branch's commits in your text editor, in order with oldest first. Each is prefaced with "pick".
Follow the instructions printed in the editor.
- Pick: Use the commit as is.
- Reorder: Cut and paste to reorder the commits.
- Squash: To combine a commit with the one above it, change
pick
tosquash
|s
. - Fixup: Like squash but uses message from prev commit. Change
pick
tofixup
|f
. - Reword: To change the commit message, change
pick
toreword
|r
. - Edit: To edit the changes in a commit change
pick
toedit
|e
>git add filePath
>git commit --amend
>git rebase --continue
- Drop: To delete a commit, change
pick
todelete
|d
, or just delete the line. Note: This will cause all commits that follow it to be rewritten.
git rebase -i <parentBranch> Gets all commits in the current branch.
git rebase -i HEAD~3 Gets last 3 commits.
git rebase -i commitId Gets commit after commitId.
git rebase -i --root Gets all your commits.
Note: When collaborating on a project, don't rebase commits once they've been pushed to the shared repository.
Stash code
⋯ > Stash > Stash
| ⋯ > Stash > Stash (include untracked)
git stash [-um 'mssg'] Stash working directory changes with untracked files.
git stash list List any stash items you have. Most recent stash is on top.
git stash show [index] List files in latest or specified stash.
git stash show [index] -p List files in latest or specified stash. Show the changes.
⋯ > Stash > Apply Latest Stash
| ⋯ > Stash > Apply Stash
⋯ > Stash > Pop Latest Stash
| ⋯ > Stash > Pop Stash
⋯ > Stash > Drop Stash
| ⋯ > Stash > Drop All Stashes
git stash clear Delete all stashes.
Docs and examples
Docs: git-scm.com/docs/git-stash | git help stash
Example - Quick stash:
Example - try out new feature:
Notes:
Example - Quick stash:
- Temporarily stash your code so you can do a task in a different branch: git stash
- Change branches. Complete the task. Then change back to the original branch.
- Retrieve and delete the stash to continue working on it: git stash pop
Example - try out new feature:
- Experiment with a new feature idea called Feature X without making it a branch yet.
- Create your files. Then stash them with message 'Feature X': git stash -um 'Feature X'
- Later you want to work on the feature some more. Retrieve the files: git stash pop
- After working on it some more you can either:
- Create a new stash: git stash -um 'Feature X'
- Discard the files and changes: git restore .
- Make the changes into a branch git checkout -b feature-x
Notes:
- If the stash index is not provided with the command, the most recent stash is selected (i.e., index 0).
- To retrieve stashes use git stash pop (deletes the stash), unless you want to make the stash available to multiple branches. In that case use git stash apply (does not delete the stash).
- You can create a branch directly from a stash with the command: git stash branch <branchname> <index>
Beginning Github / RemotesGo to video for this category
User Interface
Interface descriptions
- Public/Private: The repository is either Public or Private
- Watch/Unwatch: Receive/configure notifications from this repo.
- Fork: Existing forks on this repo | Create a new fork.
- Code view: Shows file tree. Displays Readme file at the bottom.
- Issues view: Lists open issues. You can switch to view closed issues.
- Pull requests view: Lists open pull requests. You can switch to view closed PRs.
- Settings view: View and modify the repository's settings. Add collaborators.
- Current branch/tag button: In code view, shows the current branch or tag name. Dropdown menu lets you change your code view to a different branch or tagged commit.
- Code button: Copy the repo's URL or download the repo code as a zip file.
- Commits: The number of commits on this repo. Clicking the number will open the commit history view.
- File list: Code view displays the repository's file names and last commit affecting each file. Clicking a file will display the content.
- README.md: Code view displays the readme file at the bottom.
- Releases: Shows the number of releases on this repo with a link to the latest release.
Github Authentication
Authentication Docs: docs.github.com/authenticationAuthenticate with the command line using HTTPS and git-credential-manager
Options for accessing GitHub from the command line over HTTPS:
Git Credential Manager:
Homebrew:
- Create a personal access token.
- Use GitHub CLI.
- Use Git Credential Manager.
Git Credential Manager:
- GCM is a credential helper built on .NET that runs on Windows, macOS, and Linux. You can use it instead of generating a personal access token.
- Ref: github.com/GitCredentialManager/git-credential-manager/blob/main/README.md
- See if git-credential-manager-core is installed: which git-credential-manager-core
- Latest installation instructions: github.com/GitCredentialManager/git-credential-manager/blob/release/docs/install.md
- Install with HomeBrew on MacOS (see Homebrew below):
- brew tap microsoft/git
- brew install --cask git-credential-manager-core
- See if it is up-to-date: brew outdated git-credential-manager-core
- If outdated: brew upgrade git-credential-manager-core
- Uninstall: brew uninstall --cask git-credential-manager-core
Homebrew:
- Homebrew is a Mac or Linux third-party command line utility for installing applications.
- See if homebrew is installed: brew --version or which brew
- If not, go to their website and follow the installation instructions: brew.sh
Create Github remote repository
Create a github repository: github.com/new or on the navbar far right, click "+".
- Use the project folder name as the github repository name.
- Add an optional description.
- Select public (anyone can access it) or private (only people you select can access it).
- [If not importing an existing repository: Add readme, .gitignore, license.]
- Click Create Repository button.
Docs
Delete this repository
buttonSteps to: create local Git repository, add remote, initial push to remote
Create local Git repository:In your project make sure you have a README.md file and .gitignore.
Create a local git repository and commit your project files to it:
git init
git add .
git commit -m 'First commit'
git branch -M main If your default branch name is "master", rename it to "main".
Add remote to local git repository:
After creating a Github repository, add it as a remote URL named "origin".
⋯ > Remote > Add Remote > enter the URL > enter a name: "origin"
Set the upstream link and make initial push:
git push -u origin main Set upstream default location for main to the URL alias "origin". Git-demo example
From empty directory named git-demo:
- Create README.md and .gitignore files (.DS_Store relates to Macs).
- Add a local git repository, stage and commit the new files.
- Rename the current branch to "main".
- Add a remote URL to your project named "origin"
- Push your local repository to the remote. Set the "origin" as the default upstream location. Set main as the default branch to push.
echo "# git-demo" >> README.md
echo ".DS_Store" >> .gitignore
git init
git add README.md .gitignore
git commit -m "first commit"
git branch -M main
git remote add origin https://github.com/your-username/git-demo.git
git push -u origin main
git remote List the project's remote repository name(s).
git remote -v | --verbose List remote repository name(s) and url(s).
git branch -r Show your remote branches.
⋯ > Remote > Remove Remote > Select remote name
Push branch to remote
click Sync Changes button
| ⋯ > Push
git push [remote-name] <tagname> Push tag to remote. --tags push all tags
git push -f Force a push to override what is in the remote repository.
Docs and example with two repositories
Docs: git-scm.com/docs/git-push | git help push
Example: Add a users resource to your app. Create a branch, code it, commit it, merge it into main, push it to GitHub.
You are hosting your site on the web hosting platform Heroku and have a second remote set up named "heroku". After pushing to GutHub, push the commit to heroku.
Steps:
Example: Add a users resource to your app. Create a branch, code it, commit it, merge it into main, push it to GitHub.
You are hosting your site on the web hosting platform Heroku and have a second remote set up named "heroku". After pushing to GutHub, push the commit to heroku.
Steps:
- git checkout -b users Create and switch to users branch.
- Add, modify, delete files until the branch is complete.
- git add . Add completed files to the staging area.
- git commit -m 'Add users resource' Make your final commit.
- git branch main Switch back to the main branch.
- git merge users Merge in the users branch.
- git push Push the main branch to the remote repository.
- git push heroku Push the main branch to heroku.
- git branch -d users Delete the users branch.
Clone a repository - Copy another user's GitHub repository to your computer
⋯ > Clone
rm -rf .git Optionally, delete it's local Git repository.
Docs and example
Ref: git-scm.com/docs/git-clone | git help clone
Example:
1. Clone repository https://github.com/someuser/some-example-app, renaming it to example-app. Assume this is a Node.js example app you are using for learning a new feature.
git clone https://github.com/someuser/some-example-app.git example-app
2. Cloned repositories include the local .git repository including branches and the commit history. You can remove the local git repository with the Unix rm command. Option -r makes the command recursive and -f forces the removal.
rm -rf .git
3. Node projects generally include 3rd party packages which are not stored on GitHub. Install the packages using the Node Package Manager:
npm install
Example:
1. Clone repository https://github.com/someuser/some-example-app, renaming it to example-app. Assume this is a Node.js example app you are using for learning a new feature.
git clone https://github.com/someuser/some-example-app.git example-app
2. Cloned repositories include the local .git repository including branches and the commit history. You can remove the local git repository with the Unix rm command. Option -r makes the command recursive and -f forces the removal.
rm -rf .git
3. Node projects generally include 3rd party packages which are not stored on GitHub. Install the packages using the Node Package Manager:
npm install
Intermediate Github / RemotesGo to video for this category
Github repo settings for collaboration
Add Collaborators:
⚙ Settings
> Collaborators and Teams
> Add people
> Choose roleCollaborator roles
Ref: docs.github.com/../repository-roles-for-an-organization
Organization level roles: docs.github.com/../roles-in-an-organization
Organization owners have complete administrative access to your organization. This role should be limited, but to no less than two people, in your organization.
Role | Permissions | Recommended for |
---|---|
Read (base role) |
|
Triage |
|
Write |
|
Maintain |
|
Admin |
|
Organization Owner |
|
Organization level roles: docs.github.com/../roles-in-an-organization
Organization owners have complete administrative access to your organization. This role should be limited, but to no less than two people, in your organization.
View/change default branch:
⚙ Settings
> Branches
> Default branch: "main".Protect Branch:
⚙ Settings
> Branches
> Add branch protection rule
> Branch name pattern:
"main" > Select rules Branch Protection Rules. Require pull requests. Require reviews on pull requests.
- By default, protected branches prevent collaborators from deleting the branch and prevents forced (i.e., overriding) pushes.
- You can change this at the bottom of the branch protection rule page to allow users with push access to force push and/or delete the branch.
- You can require commits to be submitted as pull requests.
- Then require pull requests be approved before they can be merged.
Docs, change notification settings, default subscriptions
Ref: docs.github.com/.../subscriptions-and-notifications
Change notification settings: github.com/settings/notifications
Default subscriptions:
In general, you are automatically subscribed to conversations by default when you have:
Change notification settings: github.com/settings/notifications
Default subscriptions:
In general, you are automatically subscribed to conversations by default when you have:
- Not disabled automatic watching for repositories or teams you've joined in your notification settings. This setting is enabled by default.
- Been assigned to an issue or pull request.
- Opened a pull request, issue, or created a team discussion post.
- Commented on a thread.
- Subscribed to a thread manually by clicking Watch or Subscribe.
- Had your username @mentioned.
- Changed the state of a thread, such as by closing an issue or merging a pull request.
- Had a team you're a member of @mentioned.
- By default, you also automatically watch all repositories that you create and are owned by your personal account.
Releases
> Draft a new release
> Choose a tag
> Add title (semantic version), description (changes since last release), binaries (if any) > Publish release
Create tag and push to remote
Semantic versioning as tag names:
git tag v1.0.0 <commit> Create tag for a commit (default is last commit).
git push origin v1.0.0 Push a tag to the remote repository.
git push origin --tags Push all tags to the remote.
vMajor.Minor.Patch
git tag v1.0.0 <commit> Create tag for a commit (default is last commit).
git push origin v1.0.0 Push a tag to the remote repository.
git push origin --tags Push all tags to the remote.
Add file
> Create new file
> Type in "LICENSE" > Choose a license template
> Select license > Click Review and submit
Fetch or Pull from remote repository
Remote-tracking branch: branch fetched from a remote repository
git branch -vv List branches, last commits, and remote-tracking branch if any.
git fetch [<remote> <branch>] Download new commits since last sync, if any.
git status After git fetch, list how many commits you are behind, if any.
git merge origin/main Merge remote-tracking branch "origin/main" into local main.
git pull [<remote> <branch>] Download and merge new commits since last sync.
<remote>/<branch>
.git branch -vv List branches, last commits, and remote-tracking branch if any.
⋯ > Fetch
git status After git fetch, list how many commits you are behind, if any.
git merge origin/main Merge remote-tracking branch "origin/main" into local main.
⋯ > Pull
Docs and examples
Git docs fetch: git-scm.com/docs/git-fetch | git help fetch
Git docs pull: git-scm.com/docs/git-pull | git help pull
Github docs: docs.github.com/../getting-changes-from-a-remote-repository
fetch:
git fetch Fetches from the remote-tracking branch.
git fetch origin Fetches from the remote named "origin".
git fetch origin main Fetches from the remote named "origin" from the branch name "main".
git diff origin/main Shows the differences between the fetched remote-tracking branch and your local version.
Merge:
After running git fetch you can merge any differences with the merge command:
git merge origin/main
Pull: Pull combines the fetch and merge commands above.
git pull Downloads and merges any commits made to the remote tracking branch that is not yet reflected in the local version.
Git docs pull: git-scm.com/docs/git-pull | git help pull
Github docs: docs.github.com/../getting-changes-from-a-remote-repository
fetch:
git fetch Fetches from the remote-tracking branch.
git fetch origin Fetches from the remote named "origin".
git fetch origin main Fetches from the remote named "origin" from the branch name "main".
- If git fetch prints nothing to the Terminal you are up-to-date.
- If there are commits to the remote main branch not included in your local main branch they will be stored in .git/refs/remotes/origin/main.
- If the git fetch prints to the Terminal then run:
git diff origin/main Shows the differences between the fetched remote-tracking branch and your local version.
Merge:
After running git fetch you can merge any differences with the merge command:
git merge origin/main
Pull: Pull combines the fetch and merge commands above.
git pull Downloads and merges any commits made to the remote tracking branch that is not yet reflected in the local version.
Collaborative Development models: (1) Shared Repository, (2) Fork and Pull
Topic branch: A short-lived branch you create for a particular feature or bug fix.
Draft pull request: Request feedback on topic branch before submitting for review.
Docs, more info
Docs: docs.github.com/pull-requests
Pull Request:
Pull Request:
- Pull requests let you tell others about changes you've pushed to a branch in a repository on GitHub. Once a pull request is opened, you can discuss and review the potential changes with collaborators and add follow-up commits before your changes are merged into the base branch.
- If you receive feedback that needs to be addressed, convert the pull request to a draft pull request while working on them. Open the PR page. Under "reviewers" click "Convert to draft".
- You can open a Draft Pull Request to start a discussion on the code or topic before the branch is complete.
- Create and push a branch with at least one commit.
- Change the
Create pull request ▾
button toCreate draft pull request ▾
before clicking it. - Ready for review:
- Incorporate feedback on your local branch, make commits, and push them.
- When the branch is ready, click the Github
Pull requests
tab > Select your pull request > In the merge bock clickReady for review
.
(1) Shared repository model
For small teams with private projects. Collaborators push to single shared repository.
More details
- Prevalent with small teams and organizations collaborating on private projects.
- Collaborators are granted push (write) access to a single shared repository.
- Topic branches are created when changes need to be made.
- Pull requests are not required in this model but are useful because they initiate code review and general discussion about a set of changes before the changes are merged into the main development branch.
Shared repository model workflow
A: Alias remote URL as "origin", and set origin/main as remote-tracking branch.B: In local repo create topic branch, code it, push topic branch.
C: In remote repo, create a pull request from the topic branch.
D: Reviewer(s) review PR: Approves, makes comments, or requests changes.
E: If reviewer requests changes, make changes to local topic branch, then push commit.
F: Merge or reject pull request.
G: If reviewer merges PR in remote, sync the local repo. Delete branch if complete.
D: Reviewer(s) review PR: Approves, makes comments, or requests changes.
E: If reviewer requests changes, make changes to local topic branch, then push commit.
F: Merge or reject pull request.
G: If reviewer merges PR in remote, sync the local repo. Delete branch if complete.
Shared repository workflow with steps
A (Local): Alias remote URL as "origin", and set origin/main as remote-tracking branch:
- git remote add origin https://github.com/username/repository-name.git Add a remote repository URL.
- git push -u origin main Push the local repository to the remote and make main the tracking branch.
B (Local): Create a topic branch, code it, sync main branch, push topic branch:
- git pull Sync the main (tracking) branch with the remote.
- git checkout -b <topicBranch> Create and check out a new branch.
- Add, modify, delete files until the branch is complete. Make one or more commits:
- git add . Stage the added/deleted/changed files for commit.
- git commit -m 'Message' Commit the file changes.
- git checkout main Switch to the main branch to make sure it is in sync with remote.
- git pull Sync main (tracking) branch with remote.
- git checkout <topicBranch> Switch back to the topic branch.
- If main was out of sync, merge main branch: git merge main
- git push origin <topicBranch> Push topic branch to the remote repository.
C (Remote): Go to remote repo to create a pull request from the pushed topic branch.
- Click
Compare & pull request
> Add description > clickCreate pull request
- For comments only, change
Create pull request ▾
toCreate draft pull request
- Optionally, request reviewers:
Reviewer
>Select collaborators
D (Remote): Reviewers review the PR. Then approve, comment, or request changes.
Access: Must have write access to approve or request changes.
- From Github project page: Click
Pull requests
> select the request > - Review request: Click
Files changed
> Review the changes > clickReview changes
> Type comment summarizing feedback > Select type of review [Comment | Approve | Request changes] >Submit review
E (Local): To incorporate reviewer comments or change requests:
- Make changes in local repo to the topic branch.
- When complete, commit, push the follow-up commits to the remote topic branch:
- git add .
- git commit -m 'message'
- git push origin <topicBranch>
F (Remote): Merge or Reject Pull Request. Access: Must have write access.
- To merge PR:
Conversation
tab > Select and click a merge button:Create a merge commit
: branch commits + a merge commit.Squash and merge
: Combine all branch commits into one. Only use squash if you are done with the feature branch.Rebase and merge
: branch commits, no merge commit.- Optionally change commit message > Click
Confirm merge
- If branch will not be updated, click
Delete Branch
- To reject PR:
Conversation tab
> Type a comment > ClickClose pull request
.
G (Local): If reviewer merges pull request on remote repo, sync the local repo:
- git checkout main Switch to main branch
- git pull In the main branch, sync with the remote main branch.
- If there won't be further branch updates: git branch -D <topicBranch>
(2) Fork and pull model
Popular with open source projects. Anyone can fork a repo and make pull requests.
More details
- Popular with open source projects as it reduces the amount of friction for new contributors and allows people to work independently without upfront coordination.
- Anyone can fork an existing repository and push changes to their personal fork, then open a pull request on the original repo.
- The changes can be reviewed and pulled into the source repository by the project maintainer.
Fork: Copy of another user's GitHub repository to your GitHub account.
Upstream repository: The original repository.
Upstream repository: The original repository.
More details, and official forking tutorial link
Fork: A fork is a copy of a repository that you manage. Forks let you make changes to a project without affecting the original repository. You can fetch updates from or submit changes to the original repository with pull requests.
Difference between forking and cloning:
Forking is like cloning in that you copy someone else's repository. The difference is cloning copies it to your computer. Forking copies it to your Github account.
Use forking to:
Official Github forking example:
GitHub has a short tutorial on forking: docs.github.com/en/get-started/quickstart/fork-a-repo
There is an example repository you can fork as practice: github.com/octocat/Spoon-Knife
Difference between forking and cloning:
Forking is like cloning in that you copy someone else's repository. The difference is cloning copies it to your computer. Forking copies it to your Github account.
Use forking to:
- Propose changes to someone else's project where you don't have write access.
- Copy someone else's project to use as a starting point for your own ideas. In this case you can use forking or cloning.
Official Github forking example:
GitHub has a short tutorial on forking: docs.github.com/en/get-started/quickstart/fork-a-repo
There is an example repository you can fork as practice: github.com/octocat/Spoon-Knife
Fork and pull model workflow
A: Fork and clone repo. Configure remote.B: In local repo create topic branch, code it, push topic branch.
C: In remote forked repo, create a pull request from the topic branch.
D: Owner or reviewer reviews PR and either: Merges it | Rejects it | Requests changes.
E: If reviewer requests changes, make changes to local topic branch, then push to fork.
F: Merge or reject pull request.
G: Sync the fork repos.
D: Owner or reviewer reviews PR and either: Merges it | Rejects it | Requests changes.
E: If reviewer requests changes, make changes to local topic branch, then push to fork.
F: Merge or reject pull request.
G: Sync the fork repos.
Fork and Pull workflow with steps
A: Fork and clone repo. Configure remote.
A(Remote)1: Fork the Repo:
A(Remote)1: Fork the Repo:
- From Github repo: click
Fork
> ClickCreate fork
. - Copy forked repo URL: Click
Code ▾
> Click URL copy symbol⧉
.
- Open Terminal to location you want the cloned repo in:
- git clone https://github.com/username/repository-name.git [new-name]
- git remote add upstream https://github.com/orig-username/repo-name.git
- git remote -v Note: cloning automatically aliased Forked URL as origin.
B (Local): Create local topic branch, code it, and push it to forked repo:
- git checkout -b <topicBranch> Create and check out a new branch.
- Add, modify, delete files until the branch is complete. Make one or more commits:
- git add . Stage the added/deleted/changed files for commit.
- git commit -m 'Message' Commit the file changes.
- git checkout main Switch to the main branch to make sure it is in sync with remote.
- git pull upstream main Sync main branch with upstream remote.
- git checkout <topicBranch> Switch back to the topic branch.
- If main was out of sync, merge main branch: git merge main
- git push origin <topicBranch> Push topic branch to forked remote repo.
C (Remote): Go to remote forked repo to create a pull request from the topic branch.
- Click
Compare & pull request
> Add description > clickCreate pull request
- For comments only, change
Create pull request ▾
toCreate draft pull request ▾
- Optionally check
Allow edits from maintainers
- Optionally, request reviewers:
Reviewers
>Select collaborators
D (Remote): Reviewers review the PR. Then approve, comment, or request changes.
Access: Must have write access to approve or request changes.
- Github fork repo: Click
Pull requests
> select the request - Review request: Click
Files changed
> Review the changes > clickReview changes
> Type comment summarizing feedback > Select type of review [Comment | Approve | Request changes] >Submit review
- If maintainer edits are allowed, maintainers can make their own changes to the pull request.
E (Local): To incorporate reviewer comments or change requests:
- Make changes in local repo to the topic branch.
- When complete, commit and push branch with new commit to forked remote:
- git add .
- git commit -m 'message'
- git push origin <topicBranch>
F (Remote): Merge or Reject Pull Request. Access: Must have write access.
- To merge PR:
Conversation
tab > Select and click a merge button:Create a merge commit
: branch commits + a merge commit.Squash and merge
: Combine all branch commits into one. Only use squash if you are done with the feature branch.Rebase and merge
: branch commits, no merge commit.- Optionally change commit message > Click
Confirm merge
- If branch will not be updated, click
Delete Branch
- To reject PR:
Conversation tab
> Type a comment > ClickClose pull request
.
G (Local): If reviewer merges PR in original repo, sync local and remote fork repos:
- git checkout main Switch to main branch.
- git pull upstream main In the main branch to sync with the upstream repo.
- git push origin main Sync the remote fork repo.
- If there won't be further branch updates: git branch -D <topicBranch>
Issues - click on issues tab
Docs, common use cases, permissions
Docs: docs.github.com/issues
Common use cases for issues:
Issue permissions:
- Release tracking: You can use an issue to track the progress for a release or the steps to complete the day of a launch.
- Large initiatives: You can use an issue to track progress on a large initiative or project, which is then linked to the smaller issues.
- Feature requests: Your team or users can create issues to request an improvement to your product or project.
- Bugs: Your team or users can create issues to report a bug.
Issue permissions:
- Read access: Open issues. Close issues they opened. Reopen issues they closed. Have issues assigned to them.
- Triage access: Close, reopen, and assign all issues.
- Write access: Edit and delete anyone's comments on issues. Transfer issues.
- Admin access: Delete an issue.
<file>
> click Blame
> Commit links are left of the code.Create issue:
Discuss issue: Add comments. Address specific users with @username.
Close issue: Click the issue > Click
Comments:
Issues
tab > New issue
> Enter a title and comment > Submit new issue
.Discuss issue: Add comments. Address specific users with @username.
Close issue: Click the issue > Click
close as complete
or close as not planned
> Click Comment
.Comments:
@username, @team-name
Mention users or teams. Ask for feedback.#IssueNumber
Link to another issue.`code`
Display code.- [ ] Task
Create a tasklist.
Docs, keywords, example
Docs: docs.github.com/../linking-a-pull-request-to-an-issue
Keywords you can use to indicate the issue: close, closes, closed, fix, fixes, fixed, resolve, resolves, resolved.
Example link to issue number 1: close #1
Keywords you can use to indicate the issue: close, closes, closed, fix, fixes, fixed, resolve, resolves, resolved.
Example link to issue number 1: close #1
MarkdownGo to video for this category
Ref: markdownguide.org
- Markdown files use
.md
or.markdown
extensions (ex: README.md)
About Markdown
About Markdown:
Using Markdown is a three step process.
- Markdown is a lightweight markup language for creating formatted text documents using a plain-text editor.
- Use Markdown syntax to add formatting such as headings, lists, bold and italic text, hyperlinks, and images.
- You write your document in any plain text editor like VS Code, in a dedicated Markdown application, or in a web form.
- Unlike WYSIWYG editors like MS Word, the formatting does not happen directly in the editor. Rather a software program converts it to HTML, then it is rendered in a browser.
- The syntax is designed to be readable as is, and is much less obtrusive than HTML or other markup languages.
- Many Markdown variants, including GitHub's, allow you to use HTML tags in your Markdown document.
Using Markdown is a three step process.
- Write text with Markdown syntax in a Markdown file or web form.
- Markdown software converts the text to HTML.
- The converted HTML is rendered in a browser or Preview window.
Markdown variants:
Markdown syntax can be used:
- Original: The original Markdown syntax was created in 2004 by John Gruber and Aaron Swartz. The converter tool was a Perl script. It is available at daringfireball.net/projects/markdown
- CommonMark: A commonly used basic version called commonmark.org released in 2014.
- GitHub Flavored Markdown: GitHub has a version based on CommonMark with extended syntax for fenced code, tables, task lists, and more.
Markdown syntax can be used:
- In a dedicated desktop or web Markdown application that can convert Markdown text into an HTML or PDF file. Ex: dillinger.io
- In a text editor, then uploaded to a site like GitHub.
- Some text editors have a side-by-side Preview feature. Ex: VS Code.
- On GitHub in readmes or other markdown files, in comments, release notes, etc.
- In a web application that incorporates markdown. Ex: stackoverflow.com, reddit.com.
- Messaging apps like Slack.com.
VS Code: Markdown file and Preview side-by-side
- Open filename.md in the editor > Click
(Open preview) at the top right.
- To close the Preview window: click the
X
next toPreview filename.md
Basic Syntax
- Basic HTML tags are supported in some Markdown variants.
- Escape characters with a backslash
\
Element | Markdown | HTML |
---|---|---|
Horizontal rule | --- | ___ | *** | <hr> |
Heading Level 1 Level 2 Level 3 Level 4 Level 5 Level 6 | # text | double underline ===== ## text | single underline ----- ### text #### text ##### text ###### text | <h1></h1> <h2></h2> <h3></h3> <h4></h4> <h5></h5> <h6></h6> |
Line break | 2 spaces | <br> |
Paragraph | Empty line followed by text | <p></p> |
Blockquote | > text | <blockquote></..> |
Italic | *text* | _text_ | <i></i> |
Bold | **text** | __text__ | <b></b> |
Italic and Bold | ***text*** | <b><i></i></b> |
Code | `code` | <code></code> |
Code block | indent code with a tab or with four spaces | <pre></pre> |
Unordered List | - List item | * List item - Indented list item | <ul> <li>List item</li> </ul> |
Ordered List | 1. Item 1 1. Indented item 1 | <ol> <li>Item 1</li> </ol> |
Link | [Link text](https://example.com) | <a href='url'></a> |
Image from file with title Set width/height |   | <img src='' alt=''> <img src='' title=''> <img..width=''> |
Examples
Original Markdown: daringfireball.net/projects/markdown
Markdown Standardization Variant: commonmark.org
Headings:
Line Breaks: Create a line break by ending the line with two spaces, or use a <br> tag.
Paragraphs: Separate paragraphs by blank lines
Blockquote:
Italic and Bold:
Code:
Put inline code in backtics: `triple(2)` becomes
Code blocks: indent the code block four spaces.
Unordered List:Becomes:
Link:
Image:

If you want to set width or height, use the HTML tag. The Markdown application you are using must support HTML tags.
Becomes:

Markdown Standardization Variant: commonmark.org
Headings:
# Heading level 1 ## Heading level 2 ### Heading level 3 #### Heading level 4 ##### Heading level 5 ###### Heading level 6
Alternate Syntax for h1 and h2. Use one or more
=
or -
underline characters in the line below the heading text:Heading level 1
=============== Heading level 2 ---------------
Line Breaks: Create a line break by ending the line with two spaces, or use a <br> tag.
This is line 1. It ends with two spaces. This is line 2. It ends with an HTML break tag.<br> This is line 3.
Paragraphs: Separate paragraphs by blank lines
This is paragraph 1.
This is paragraph 2.
Blockquote:
> This is a blockquote.
Italic and Bold:
This is *italic*. So is _this_.
becomes This is italic. So is this.
This is **bold**. So is __this__.
becomes This is bold. So is this.
This is both ***bold and italic***.
becomes This is both bold and italic.
Code:
Put inline code in backtics: `triple(2)` becomes
triple(2)
. Code blocks: indent the code block four spaces.
function triple(num) {
return num * 3;
};
triple(2);
Unordered List:
- List item.
- Another list item.
- Indented item.
- Another indented item.
Becomes:
Ordered List:
- List item.
- Another list item.
- Indented item.
- Another indented item.
Ordered List:
1. Item 1
1. Item 2
1. Indented item 1.
1. Indented item 2.
- Item 1
- Item 2
- Indented item 1.
- Indented item 2.
Link:
[example](https://example.com)
becomes example.comImage:

If you want to set width or height, use the HTML tag. The Markdown application you are using must support HTML tags.
<img src="markdown-icon.png" alt="Markdown icon" title="Markdown" width="52" height="32">
Becomes:
GitHub Flavored Markdown
About GFM, docs
- GitHub Flavored Markdown, often shortened as GFM, is the dialect of Markdown that is currently supported for user content on GitHub.com and GitHub Enterprise.
- It is a superset of the CommonMark variant of Markdown, which supports the Basic Markdown syntax.
- Features supported by GFM that are not specified on the original CommonMark Spec are referred to as extensions.
- GitHub.com and GitHub Enterprise perform additional post-processing and sanitization after GFM is converted to HTML to ensure security and consistency of the website.
- Text between < and > that looks like an HTML tag is parsed as a raw HTML tag and will be rendered in HTML without escaping.
Docs: docs.github.com/../basic-writing-and-formatting-syntax
GFM spec: github.github.com/gfm
Extended Syntax
Supports basic HTML elements including inline style attributes.
Ex:
Ex:
<span style="color: red">This text is red</span>
Element | Markdown | HTML |
---|---|---|
Strikethrough | ~~text~~ | <del></del> |
Link as is Link | https://example.com [Link text](https://example.com) | <a href="URL">URL</a> <a href="URL">Link text</a> |
Code block | ``` language code ``` Or indent code by 4 spaces | <pre></pre> |
Task List | - [ ] unchecked item - [x] checked item | <input type="checkbox"> <input type="checkbox" checked> |
Table | First Header | Second Header ------------ | ------------- Cell 1 content | Cell 2 content Cell 1 content | Cell 2 content | <table> <thead><tr>...</tr></thead> <tbody><tr>...</tr></tbody> </table> |
Examples
Links:
Code blocks: use three backticks ``` or three tildes ~~~ above and below the code block.
- A plain URL will automatically be converted into a hyperlink.
- Ex:
https://example.com
becomes https://example.com - To display the hyperlink with different text, use the Markdown syntax.
- Ex:
[example.com](https://example.com)
becomes example.com
Code blocks: use three backticks ``` or three tildes ~~~ above and below the code block.
- For language syntax highlighting, add the language name after the opening ``` or ~~~.
- Languages: html, css, javascript or js, json, python, etc.
``` javascript
function double(num) {
return num * 4;
};
double(2);
```
- Alternatively, indent the code block four spaces.
function triple(num) {
return num * 3;
};
triple(2);
Table of Contents
GitHub auto-generated TOC:
Heading ids: heading text, lowercase, spaces convert to dashes, non-numbers or letters removed.
GitHub automatically creates a TOC from the headings. Click
at upper left.
Manual TOC: [Heading title](#heading-id)
Add hyperlink to an h1-h6 heading. Heading ids: heading text, lowercase, spaces convert to dashes, non-numbers or letters removed.
Example
- h1-h6 headings automatically convert the heading text to an id. The text is lower cased, spaces are converted to dashes. Characters other than letters and numbers are removed (periods, commas, apostrophes, quotes, slashes, etc).
GitHub auto-generated TOC:
- GitHub automatically generates a hidden Table of Contents for every markdown file. It includes a link to every h1-h6 heading in the file.
- To view it, click the TOC icon at the top left of the displayed markdown file.
Manual Table of Contents:
- For the TOC items, add a hyperlink to each heading ID followed by 2 spaces.
# Page Heading
## Manual Table of Contents
[Topic 1](#topic-1)
[Topic 2](#topic-2)
## Topic 1
Topic 1 content.
## Topic 2
Topic 2 content.
GitHub README.md files
Ref: docs.github.com/../about-readmes
Place README.md file in the project root, /docs, or .github directories.
GitHub READMEs include information on one or more of the following:
Place README.md file in the project root, /docs, or .github directories.
GitHub READMEs include information on one or more of the following:
- What the project does.
- Why the project is useful.
- How users can get started with the project.
- Where users can get help with the project.
- Who maintains and contributes to the project.