Hướng dẫn dùng indentation python python

Python là ngôn ngữ khá giống với Perl, C và Java. Tuy nhiên có một vài điểm khác biệt rõ rệt với các ngôn ngữ trên.

Nội dung của bài

  • 1 Cách hoạt động của chương trình Python.
  • 2 Định danh và cách khai báo biến trong Python
  • 3 Dòng lệnh trong Python
  • 4 Thụt đầu dòng trong Python [Indentation]
  • 5 Khối code trong Python
  • 6 Kết luận

Cách hoạt động của chương trình Python.

Bạn có thể chạy trực tiếp cậu lệnh python:

print["Hello World!"]
# prints Hello World!

Hoặc bạn có thể tạo file python với đuôi [extension] .py

Ví dụ: tạo file test.py với nội dung:
print[“Hello World!”]

rồi chạy ở Command Line:

$python test.py

Kết quả trả về sẽ là:

Hello World!

Định danh và cách khai báo biến trong Python

Định danh là tên gọi của các thành phần trong chương trình Python như tên biến, tên hàm, tên lớp, tên module hay tên đối tượng. Python đặt ra một số quy tắc chung mà tất cả các định danh phải tuân thủ. Nếu không tuân thủ các quy tắc đặt định danh sẽ dấn tới lỗi cú pháp.

Python là ngôn ngữ case sensitive phân biệt chữa hoa và chữ thường. Python có quy tắc định danh như sau:

  • Định danh chỉ chưa các ký tự thường [a-z], ký tự hoa [A-Z], số [0-9] và dấu gạch chân[_]. Định danh có thể sử dụng ký tự Unicode, ví dụ có thể sử dụng tiếng việt là định danh, đặt cho tên biến: tôi_yêu_python = “Tôi yêu ngôn ngữ lập trình Python”. Các ký tự @, $, % hay dấu gạch ngang không được phép xuất hiện trong định danh.
  • Định danh chỉ được bắt đầu bằng ký tự [hoa, thường] và dấu gạch chân. Chữ số xuất hiện ở đầu định danh là không hợp lệ.
  • Định danh không được phép trùng với các từ khóa.

Dưới đây là các từ khóa trong Python, các từ khóa chỉ chưa các ký tự thường:

andexecnotassertfinallyorbreakforpassclassfromprintcontinueglobalraisedefifreturndelimporttryelifinwhileelseiswithexceptlambdayieldTừ khóa trong Python

Dòng lệnh trong Python

Không giống như Java hay C, kết thúc dòng lệnh cần sử dụng dấu chấm phảy [;]. Python kết thúc dòng cũng là kết thúc lệnh.

Ví dụ:

if 5 > 2:
  print["Five is greater than two!"]

Python cũng có thể sử dụng Multi-Line Statements [ khai báo một dòng lệnh trên nhiều dòng] bằng cách sử dụng ký tự \ ở cuối mỗi dòng.
Ví dụ:

name = fist_name + \
       last_name

Các dòng lệnh có chưa cặp ký tự [], {}, or [] thì có thể khai báo trên nhiều dòng mà không cần sử dụng ký tự \

Ví dụ:

days = ['Monday', 'Tuesday', 'Wednesday',
        'Thursday', 'Friday']

Thụt đầu dòng trong Python [Indentation]

Không giống các ngôn ngữ khác dùng dấu cách để cho code dễ đọc, python sử dụng dấu cách một cách chặt chẽ để định nghĩa cấu trúc code.

Vi dụ cho cách khai báo code đúng chuẩn:

if True:
    print["True"]
else:
    print["False"]

Cách khai báo sai:

if True:
print["True"]
else:
print["False"]

Với quy tắc này bạn cần cẩn trọng trong việc sử dụng dấu cách và dấu tab [thường các IDE quy định là 4 dấu cách]. Chỉ thụt đầu dòng bằng dấu tab khi cần thiết.

Khối code trong Python

Một khối code trong Python được quy định là những dòng lệnh liền nhau có chung số dấu cách đầu dòng. Điều này khác với các ngôn ngữ khác như Java sử dụng cặp ký tự: {}.

Ví dụ:

#!/usr/bin/python

import sys

try:
   # open file stream
   file = open[file_name, "w"]
except IOError:
   print "There was an error writing to", file_name
   sys.exit[]
print "Enter '", file_finish,
print "' When finished"
while file_text != file_finish:
   # Bắt đầu khối code 
   file_text = raw_input["Enter text: "]
   if file_text == file_finish:
      # close the file
      file.close
      break
   file.write[file_text]
   file.write["\n"]
   # Kết thúc khối code
file.close[]
file_name = raw_input["Enter filename: "]
if len[file_name] == 0:
   print "Next time please enter something"
   sys.exit[]
try:
   file = open[file_name, "r"]
except IOError:
   print "There was an error reading file"
   sys.exit[]
file_text = file.read[]
file.close[]
print file_text


Kết luận

Ngoài cách sử dụng cú pháp khá giống với ngôn ngữ C, Python có 3 đặc điểm khác biệt rõ rệt đó là: Dòng lệnh, khối lệnh và định danh.

Visual Studio Code is an editor first and foremost, and includes the features you need for highly productive source code editing. This topic takes you through the basics of the editor and helps you get moving with your code.

Keyboard shortcuts

Being able to keep your hands on the keyboard when writing code is crucial for high productivity. VS Code has a rich set of default keyboard shortcuts as well as allowing you to customize them.

  • Keyboard Shortcuts Reference - Learn the most commonly used and popular keyboard shortcuts by downloading the reference sheet.
  • Install a Keymap extension - Use the keyboard shortcuts of your old editor [such as Sublime Text, Atom, and Vim] in VS Code by installing a Keymap extension.
  • Customize Keyboard Shortcuts - Change the default keyboard shortcuts to fit your style.

Multiple selections [multi-cursor]

VS Code supports multiple cursors for fast simultaneous edits. You can add secondary cursors [rendered thinner] with Alt+Click. Each cursor operates independently based on the context it sits in. A common way to add more cursors is with ⌥⌘↓ [Windows Ctrl+Alt+Down, Linux Shift+Alt+Down] or ⌥⌘↑ [Windows Ctrl+Alt+Up, Linux Shift+Alt+Up] that insert cursors below or above.

Note: Your graphics card driver [for example NVIDIA] might overwrite these default shortcuts.

⌘D [Windows, Linux Ctrl+D] selects the word at the cursor, or the next occurrence of the current selection.

Tip: You can also add more cursors with ⇧⌘L [Windows, Linux Ctrl+Shift+L], which will add a selection at each occurrence of the current selected text.

Multi-cursor modifier

If you'd like to change the modifier key for applying multiple cursors to Cmd+Click on macOS and Ctrl+Click on Windows and Linux, you can do so with the editor.multiCursorModifier setting. This lets users coming from other editors such as Sublime Text or Atom continue to use the keyboard modifier they are familiar with.

The setting can be set to:

  • ctrlCmd - Maps to Ctrl on Windows and Cmd on macOS.
  • alt - The existing default Alt.

There's also a menu item Use Ctrl+Click for Multi-Cursor in the Selection menu to quickly toggle this setting.

The Go to Definition and Open Link gestures will also respect this setting and adapt such that they do not conflict. For example, when the setting is ctrlCmd, multiple cursors can be added with Ctrl/Cmd+Click, and opening links or going to definition can be invoked with Alt+Click.

Shrink/expand selection

Quickly shrink or expand the current selection. Trigger it with ⌃⇧⌘← [Windows, Linux Shift+Alt+Left] and ⌃⇧⌘→ [Windows, Linux Shift+Alt+Right].

Here's an example of expanding the selection with ⌃⇧⌘→ [Windows, Linux Shift+Alt+Right]:

Column [box] selection

Place the cursor in one corner and then hold Shift+Alt while dragging to the opposite corner:

Note: This changes to Shift+Ctrl/Cmd when using Ctrl/Cmd as multi-cursor modifier.

There are also default key bindings for column selection on macOS and Windows, but not on Linux.

KeyCommandCommand ID⇧↓ [Windows Ctrl+Shift+Alt+Down, Linux ]Column Select Down
"html.format.enable": false
1⇧↑ [Windows Ctrl+Shift+Alt+Up, Linux ]Column Select Up
"html.format.enable": false
2⇧← [Windows Ctrl+Shift+Alt+Left, Linux ]Column Select Left
"html.format.enable": false
3⇧→ [Windows Ctrl+Shift+Alt+Right, Linux ]Column Select Right
"html.format.enable": false
4⇧PageDown [Windows Ctrl+Shift+Alt+PageDown, Linux ]Column Select Page Down
"html.format.enable": false
5⇧PageUp [Windows Ctrl+Shift+Alt+PageUp, Linux ]Column Select Page Up
"html.format.enable": false
6

You can edit your

"html.format.enable": false
7 to bind them to something more familiar if you want.

Column Selection mode

The user setting Editor: Column Selection controls this feature. Once this mode is entered, as indicated in the Status bar, the mouse gestures and the arrow keys will create a column selection by default. This global toggle is also accessible via the Selection > Column Selection Mode menu item. In addition, one can also disable Column Selection mode from the Status bar.

Save / Auto Save

By default, VS Code requires an explicit action to save your changes to disk, ⌘S [Windows, Linux Ctrl+S].

However, it's easy to turn on

"html.format.enable": false
8, which will save your changes after a configured delay or when focus leaves the editor. With this option turned on, there is no need to explicitly save the file. The easiest way to turn on
"html.format.enable": false
8 is with the File > Auto Save toggle that turns on and off save after a delay.

For more control over

"html.format.enable": false
8, open User or Workspace settings and find the associated settings:

  •   "[html]": {
        "editor.foldingStrategy": "indentation"
      },
    
    1: Can have the values:
    •   "[html]": {
          "editor.foldingStrategy": "indentation"
        },
      
      2 - to disable auto save.
    •   "[html]": {
          "editor.foldingStrategy": "indentation"
        },
      
      3 - to save files after a configured delay [default 1000 ms].
    •   "[html]": {
          "editor.foldingStrategy": "indentation"
        },
      
      4 - to save files when focus moves out of the editor of the dirty file.
    •   "[html]": {
          "editor.foldingStrategy": "indentation"
        },
      
      5 - to save files when the focus moves out of the VS Code window.
  •   "[html]": {
        "editor.foldingStrategy": "indentation"
      },
    
    6: Configures the delay in milliseconds when
      "[html]": {
        "editor.foldingStrategy": "indentation"
      },
    
    1 is configured to
      "[html]": {
        "editor.foldingStrategy": "indentation"
      },
    
    3. The default is 1000 ms.

Hot Exit

VS Code will remember unsaved changes to files when you exit by default. Hot exit is triggered when the application is closed via File > Exit [Code > Quit on macOS] or when the last window is closed.

You can configure hot exit by setting

  "[html]": {
    "editor.foldingStrategy": "indentation"
  },
9 to the following values:

  •     "editor.insertSpaces": true,
        "editor.tabSize": 4,
    
    0: Disable hot exit.
  •     "editor.insertSpaces": true,
        "editor.tabSize": 4,
    
    1: Hot exit will be triggered when the application is closed, that is when the last window is closed on Windows/Linux or when the
        "editor.insertSpaces": true,
        "editor.tabSize": 4,
    
    2 command is triggered [from the Command Palette, keyboard shortcut or menu]. All windows without folders opened will be restored upon next launch.
  •     "editor.insertSpaces": true,
        "editor.tabSize": 4,
    
    3: Hot exit will be triggered when the application is closed, that is when the last window is closed on Windows/Linux or when the
        "editor.insertSpaces": true,
        "editor.tabSize": 4,
    
    2 command is triggered [from the Command Palette, keyboard shortcut or menu], and also for any window with a folder opened regardless of whether it is the last window. All windows without folders opened will be restored upon next launch. To restore folder windows as they were before shutdown, set
        "editor.insertSpaces": true,
        "editor.tabSize": 4,
    
    5 to
        "editor.insertSpaces": true,
        "editor.tabSize": 4,
    
    6.

If something happens to go wrong with hot exit, all backups are stored in the following folders for standard install locations:

  • Windows
        "editor.insertSpaces": true,
        "editor.tabSize": 4,
    
    7
  • macOS
        "editor.insertSpaces": true,
        "editor.tabSize": 4,
    
    8
  • Linux
        "editor.insertSpaces": true,
        "editor.tabSize": 4,
    
    9

Find and Replace

VS Code allows you to quickly find text and replace in the currently opened file. Press ⌘F [Windows, Linux Ctrl+F] to open the Find Widget in the editor, search results will be highlighted in the editor, overview ruler and minimap.

If there are more than one matched result in the current opened file, you can press Enter and ⇧Enter [Windows, Linux Shift+Enter] to navigate to next or previous result when the find input box is focused.

Seed Search String From Selection

When the Find Widget is opened, it will automatically populate the selected text in the editor into the find input box. If the selection is empty, the word under the cursor will be inserted into the input box instead.

This feature can be turned off by setting

    "editor.detectIndentation": false,
    "editor.tabSize": 3,
0 to
    "editor.detectIndentation": false,
    "editor.tabSize": 3,
1.

Find In Selection

By default, the find operations are run on the entire file in the editor. It can also be run on selected text. You can turn this feature on by clicking the hamburger icon on the Find Widget.

If you want it to be the default behavior of the Find Widget, you can set

    "editor.detectIndentation": false,
    "editor.tabSize": 3,
2 to
    "editor.detectIndentation": false,
    "editor.tabSize": 3,
3, or to
    "editor.detectIndentation": false,
    "editor.tabSize": 3,
4, if you want it to be run on selected text only when multiple lines of content are selected.

Advanced find and replace options

In addition to find and replace with plain text, the Find Widget also has three advanced search options:

  • Match Case
  • Match Whole Word
  • Regular Expression

The replace input box support case preserving, you can turn it on by clicking the Preserve Case [AB] button.

Multiline support and Find Widget resizing

You can search multiple line text by pasting the text into the Find input box and Replace input box. Pressing

    "editor.detectIndentation": false,
    "editor.tabSize": 3,
5 inserts a new line in the input box.

While searching long text, the default size of Find Widget might be too small. You can drag the left sash to enlarge the Find Widget or double click the left sash to maximize it or shrink it to its default size.

Search across files

VS Code allows you to quickly search over all files in the currently opened folder. Press ⇧⌘F [Windows, Linux Ctrl+Shift+F] and enter your search term. Search results are grouped into files containing the search term, with an indication of the hits in each file and its location. Expand a file to see a preview of all of the hits within that file. Then single-click on one of the hits to view it in the editor.

Tip: We support regular expression searching in the search box, too.

You can configure advanced search options by clicking the ellipsis [Toggle Search Details] below the search box on the right [or press ⇧⌘J [Windows, Linux Ctrl+Shift+J]]. This will show additional fields to configure the search.

Advanced search options

In the two input boxes below the search box, you can enter patterns to include or exclude from the search. If you enter

    "editor.detectIndentation": false,
    "editor.tabSize": 3,
6, that will match every folder and file named
    "editor.detectIndentation": false,
    "editor.tabSize": 3,
6 in the workspace. If you enter
    "editor.detectIndentation": false,
    "editor.tabSize": 3,
8, that will match the folder
    "editor.detectIndentation": false,
    "editor.tabSize": 3,
9 at the top level of your workspace. Use
    "editor.wordWrap": "on"
0 to separate multiple patterns. Paths must use forward slashes. You can also use glob syntax:

  •     "editor.wordWrap": "on"
    
    1 to match zero or more characters in a path segment
  •     "editor.wordWrap": "on"
    
    2 to match on one character in a path segment
  •     "editor.wordWrap": "on"
    
    3 to match any number of path segments, including none
  •     "editor.wordWrap": "on"
    
    4 to group conditions [for example
        "editor.wordWrap": "on"
    
    5 matches all HTML and text files]
  •     "editor.wordWrap": "on"
    
    6 to declare a range of characters to match [
        "editor.wordWrap": "on"
    
    7 to match on
        "editor.wordWrap": "on"
    
    8,
        "editor.wordWrap": "on"
    
    9, …]
  • {
      "key": "shift+alt+down",
      "command": "editor.action.insertCursorBelow",
      "when": "textInputFocus",
      "args": { "logicalLine": true },
    },
    {
      "key": "shift+alt+up",
      "command": "editor.action.insertCursorAbove",
      "when": "textInputFocus",
      "args": { "logicalLine": true },
    },
    
    0 to negate a range of characters to match [
    {
      "key": "shift+alt+down",
      "command": "editor.action.insertCursorBelow",
      "when": "textInputFocus",
      "args": { "logicalLine": true },
    },
    {
      "key": "shift+alt+up",
      "command": "editor.action.insertCursorAbove",
      "when": "textInputFocus",
      "args": { "logicalLine": true },
    },
    
    1 to match on
    {
      "key": "shift+alt+down",
      "command": "editor.action.insertCursorBelow",
      "when": "textInputFocus",
      "args": { "logicalLine": true },
    },
    {
      "key": "shift+alt+up",
      "command": "editor.action.insertCursorAbove",
      "when": "textInputFocus",
      "args": { "logicalLine": true },
    },
    
    2,
    {
      "key": "shift+alt+down",
      "command": "editor.action.insertCursorBelow",
      "when": "textInputFocus",
      "args": { "logicalLine": true },
    },
    {
      "key": "shift+alt+up",
      "command": "editor.action.insertCursorAbove",
      "when": "textInputFocus",
      "args": { "logicalLine": true },
    },
    
    3, but not
        "editor.wordWrap": "on"
    
    8]

VS Code excludes some folders by default to reduce the number of search results that you are not interested in [for example:

{
  "key": "shift+alt+down",
  "command": "editor.action.insertCursorBelow",
  "when": "textInputFocus",
  "args": { "logicalLine": true },
},
{
  "key": "shift+alt+up",
  "command": "editor.action.insertCursorAbove",
  "when": "textInputFocus",
  "args": { "logicalLine": true },
},
5]. Open settings to change these rules under the
{
  "key": "shift+alt+down",
  "command": "editor.action.insertCursorBelow",
  "when": "textInputFocus",
  "args": { "logicalLine": true },
},
{
  "key": "shift+alt+up",
  "command": "editor.action.insertCursorAbove",
  "when": "textInputFocus",
  "args": { "logicalLine": true },
},
6 and
{
  "key": "shift+alt+down",
  "command": "editor.action.insertCursorBelow",
  "when": "textInputFocus",
  "args": { "logicalLine": true },
},
{
  "key": "shift+alt+up",
  "command": "editor.action.insertCursorAbove",
  "when": "textInputFocus",
  "args": { "logicalLine": true },
},
7 section.

Note that glob patterns in the search view work differently than in settings such as

{
  "key": "shift+alt+down",
  "command": "editor.action.insertCursorBelow",
  "when": "textInputFocus",
  "args": { "logicalLine": true },
},
{
  "key": "shift+alt+up",
  "command": "editor.action.insertCursorAbove",
  "when": "textInputFocus",
  "args": { "logicalLine": true },
},
6 and
{
  "key": "shift+alt+down",
  "command": "editor.action.insertCursorBelow",
  "when": "textInputFocus",
  "args": { "logicalLine": true },
},
{
  "key": "shift+alt+up",
  "command": "editor.action.insertCursorAbove",
  "when": "textInputFocus",
  "args": { "logicalLine": true },
},
7. In the settings, you must use editor.multiCursorModifier0 to match a folder named
    "editor.detectIndentation": false,
    "editor.tabSize": 3,
6 in subfolder editor.multiCursorModifier2 in your workspace. In the search view, the
    "editor.wordWrap": "on"
3 prefix is assumed. The glob patterns in these settings are always evaluated relative to the path of the workspace folder.

Also note the Use Exclude Settings and Ignore Files toggle button in the files to exclude box. The toggle determines whether to exclude files that are ignored by your editor.multiCursorModifier4 files and/or matched by your

{
  "key": "shift+alt+down",
  "command": "editor.action.insertCursorBelow",
  "when": "textInputFocus",
  "args": { "logicalLine": true },
},
{
  "key": "shift+alt+up",
  "command": "editor.action.insertCursorAbove",
  "when": "textInputFocus",
  "args": { "logicalLine": true },
},
6 and
{
  "key": "shift+alt+down",
  "command": "editor.action.insertCursorBelow",
  "when": "textInputFocus",
  "args": { "logicalLine": true },
},
{
  "key": "shift+alt+up",
  "command": "editor.action.insertCursorAbove",
  "when": "textInputFocus",
  "args": { "logicalLine": true },
},
7 settings.

Tip: From the Explorer, you can right-click on a folder and select Find in Folder to search inside a folder only.

Search and replace

You can also Search and Replace across files. Expand the Search widget to display the Replace text box.

When you type text into the Replace text box, you will see a diff display of the pending changes. You can replace across all files from the Replace text box, replace all in one file or replace a single change.

Tip: You can quickly reuse a previous search term by using [Windows, Linux Down] and [Windows, Linux Up] to navigate through your search term history.

Case changing in regex replace

VS Code supports changing the case of regex matching groups while doing Search and Replace in the editor or globally. This is done with the modifiers editor.multiCursorModifier7, where editor.multiCursorModifier8 and editor.multiCursorModifier9 will upper/lowercase a single character, and ctrlCmd0 and ctrlCmd1 will upper/lowercase the rest of the matching group.

Example:

The modifiers can also be stacked - for example, ctrlCmd2 will uppercase the first three characters of the group, or ctrlCmd3 will lowercase the first character, and uppercase the rest. The capture group is referenced by ctrlCmd4 in the replacement string, where ctrlCmd5 is the order of the capture group.

Search Editor

Search Editors let you view workspace search results in a full-sized editor, complete with syntax highlighting and optional lines of surrounding context.

Below is a search for the word 'SearchEditor' with two lines of text before and after the match for context:

The Open Search Editor command opens an existing Search Editor if one exists, or to otherwise create a new one. The New Search Editor command will always create a new Search Editor.

In the Search Editor, results can be navigated to using Go to Definition actions, such as F12 to open the source location in the current editor group, or ⌘K F12 [Windows, Linux Ctrl+K F12] to open the location in an editor to the side. Additionally, double-clicking can optionally open the source location, configurable with the ctrlCmd6 setting.

You can also use the Open New Search Editor button at the top of the Search view, and can copy your existing results from a Search view over to a Search Editor with the Open in editor link at the top of the results tree, or the Search Editor: Open Results in Editor command.

The Search Editor above was opened by selecting the Open New Search Editor button [third button] on the top of the Search view.

Search Editor commands and arguments

  • ctrlCmd7 - Opens the Search Editor in a new tab.
  • ctrlCmd8 - Copy the current Search results into a new Search Editor.
  • ctrlCmd9 - Opens the Search Editor in a new window next to the window you currently have opened.

There are two arguments that you can pass to the Search Editor commands [ctrlCmd7, ctrlCmd9] to allow keybindings to configure how a new Search Editor should behave:

  • alt2 - Whether a search be automatically run when a Search Editor is opened. Default is true.
  • alt3 - Whether to put focus in the results of a search or the query input. Default is true.

For example, the following keybinding runs the search when the Search Editor is opened but leaves the focus in the search query control.

{
  "key": "ctrl+o",
  "command": "search.action.openNewEditor",
  "args": { "query": "VS Code", "triggerSearch": true, "focusResults": false }
}

Search Editor context default

The alt4 setting has a default value of 1, meaning one context line will be shown before and after each result line in the Search Editor.

Reuse last Search Editor configuration

The alt5 setting [default is

    "editor.detectIndentation": false,
    "editor.tabSize": 3,
1] lets you reuse the last active Search Editor's configuration when creating a new Search Editor.

IntelliSense

We'll always offer word completion, but for the rich languages, such as JavaScript, JSON, HTML, CSS, SCSS, Less, C# and TypeScript, we offer a true IntelliSense experience. If a language service knows possible completions, the IntelliSense suggestions will pop up as you type. You can always manually trigger it with ⌃Space [Windows, Linux Ctrl+Space]. By default, Tab or Enter are the accept keyboard triggers but you can also customize these key bindings.

Tip: The suggestions filtering supports CamelCase so you can type the letters which are upper cased in a method name to limit the suggestions. For example, "cra" will quickly bring up "createApplication".

Tip: IntelliSense suggestions can be configured via the alt7 and alt8 settings.

JavaScript and TypeScript developers can take advantage of the npmjs type declaration [typings] file repository to get IntelliSense for common JavaScript libraries [Node.js, React, Angular]. You can find a good explanation on using type declaration files in the JavaScript language topic and the Node.js tutorial.

Learn more in the IntelliSense document.

Formatting

VS Code has great support for source code formatting. The editor has two explicit format actions:

  • Format Document [⇧⌥F [Windows Shift+Alt+F, Linux Ctrl+Shift+I]] - Format the entire active file.
  • Format Selection [⌘K ⌘F [Windows, Linux Ctrl+K Ctrl+F]] - Format the selected text.

You can invoke these from the Command Palette [⇧⌘P [Windows, Linux Ctrl+Shift+P]] or the editor context menu.

VS Code has default formatters for JavaScript, TypeScript, JSON, and HTML. Each language has specific formatting options [for example, alt9] which you can tune to your preference in your user or workspace settings. You can also disable the default language formatter if you have another extension installed that provides formatting for the same language.

"html.format.enable": false

Along with manually invoking code formatting, you can also trigger formatting based on user gestures such as typing, saving or pasting. These are off by default but you can enable these behaviors through the following settings:

  • "html.format.enable": false
    
    00 - Format the line after typing.
  • "html.format.enable": false
    
    01 - Format a file on save.
  • "html.format.enable": false
    
    02 - Format the pasted content.

Note: Not all formatters support format on paste as to do so they must support formatting a selection or range of text.

In addition to the default formatters, you can find extensions on the Marketplace to support other languages or formatting tools. There is a

"html.format.enable": false
03 category so you can easily search and find formatting extensions. In the Extensions view search box, type 'formatters' or 'category:formatters' to see a filtered list of extensions within VS Code.

Folding

You can fold regions of source code using the folding icons on the gutter between line numbers and line start. Move the mouse over the gutter and click to fold and unfold regions. Use Shift + Click on the folding icon to fold or unfold the region and all regions inside.

You can also use the following actions:

  • Fold [⌥⌘[ [Windows, Linux Ctrl+Shift+[]] folds the innermost uncollapsed region at the cursor.
  • Unfold [⌥⌘] [Windows, Linux Ctrl+Shift+]]] unfolds the collapsed region at the cursor.
  • Toggle Fold [⌘K ⌘L [Windows, Linux Ctrl+K Ctrl+L]] folds or unfolds the region at the cursor.
  • Fold Recursively [⌘K ⌘[ [Windows, Linux Ctrl+K Ctrl+[]] folds the innermost uncollapsed region at the cursor and all regions inside that region.
  • Unfold Recursively [⌘K ⌘] [Windows, Linux Ctrl+K Ctrl+]]] unfolds the region at the cursor and all regions inside that region.
  • Fold All [⌘K ⌘0 [Windows, Linux Ctrl+K Ctrl+0]] folds all regions in the editor.
  • Unfold All [⌘K ⌘J [Windows, Linux Ctrl+K Ctrl+J]] unfolds all regions in the editor.
  • Fold Level X [⌘K ⌘2 [Windows, Linux Ctrl+K Ctrl+2] for level 2] folds all regions of level X, except the region at the current cursor position.
  • Fold All Block Comments [⌘K ⌘/ [Windows, Linux Ctrl+K Ctrl+/]] folds all regions that start with a block comment token.

Folding regions are by default evaluated based on the indentation of lines. A folding region starts when a line has a smaller indent than one or more following lines, and ends when there is a line with the same or smaller indent.

Folding regions can also be computed based on syntax tokens of the editor's configured language. The following languages already provide syntax aware folding: Markdown, HTML, CSS, LESS, SCSS, and JSON.

If you prefer to switch back to indentation-based folding for one [or all] of the languages above, use:

  "[html]": {
    "editor.foldingStrategy": "indentation"
  },

Regions can also be defined by markers defined by each language. The following languages currently have markers defined:

LanguageStart regionEnd regionBat
"html.format.enable": false
04 or
"html.format.enable": false
05
"html.format.enable": false
06 or
"html.format.enable": false
07C#
"html.format.enable": false
08
"html.format.enable": false
09C/C++
"html.format.enable": false
10
"html.format.enable": false
11CSS/Less/SCSS
"html.format.enable": false
12
"html.format.enable": false
13Coffeescript
"html.format.enable": false
08
"html.format.enable": false
09F#
"html.format.enable": false
16 or
"html.format.enable": false
17
"html.format.enable": false
18 or
"html.format.enable": false
19Java
"html.format.enable": false
16 or
"html.format.enable": false
21
"html.format.enable": false
22 or
"html.format.enable": false
23Markdown
"html.format.enable": false
24
"html.format.enable": false
25Perl5
"html.format.enable": false
08 or
"html.format.enable": false
27
"html.format.enable": false
09 or
"html.format.enable": false
29PHP
"html.format.enable": false
08
"html.format.enable": false
09PowerShell
"html.format.enable": false
08
"html.format.enable": false
09Python
"html.format.enable": false
08 or
"html.format.enable": false
35
"html.format.enable": false
09 or
"html.format.enable": false
37TypeScript/JavaScript
"html.format.enable": false
16
"html.format.enable": false
18Visual Basic
"html.format.enable": false
40
"html.format.enable": false
41

To fold and unfold only the regions defined by markers use:

  • Fold Marker Regions [⌘K ⌘8 [Windows, Linux Ctrl+K Ctrl+8]] folds all marker regions.
  • Unfold Marker Regions [⌘K ⌘9 [Windows, Linux Ctrl+K Ctrl+9]] unfolds all marker regions.

Fold selection

The command Create Manual Folding Ranges from Selection [⌘K ⌘, [Windows, Linux Ctrl+K Ctrl+,]] creates a folding range from the currently selected lines and collapses it. That range is called a manual folding range that goes on top of the ranges computed by folding providers.

Manual folding ranges can be removed with the command Remove Manual Folding Ranges [⌘K ⌘. [Windows, Linux Ctrl+K Ctrl+.]].

Manual folding ranges are especially useful for cases when there isn't programming language support for folding.

Indentation

VS Code lets you control text indentation and whether you'd like to use spaces or tab stops. By default, VS Code inserts spaces and uses 4 spaces per Tab key. If you'd like to use another default, you can modify the

"html.format.enable": false
42 and
"html.format.enable": false
43 settings.

    "editor.insertSpaces": true,
    "editor.tabSize": 4,

Auto-detection

VS Code analyzes your open file and determines the indentation used in the document. The auto-detected indentation overrides your default indentation settings. The detected setting is displayed on the right side of the Status Bar:

You can click on the Status Bar indentation display to bring up a dropdown with indentation commands allowing you to change the default settings for the open file or convert between tab stops and spaces.

Note: VS Code auto-detection checks for indentations of 2, 4, 6 or 8 spaces. If your file uses a different number of spaces, the indentation may not be correctly detected. For example, if your convention is to indent with 3 spaces, you may want to turn off

"html.format.enable": false
44 and explicitly set the tab size to 3.

    "editor.detectIndentation": false,
    "editor.tabSize": 3,

File encoding support

Set the file encoding globally or per workspace by using the

"html.format.enable": false
45 setting in User Settings or Workspace Settings.

You can view the file encoding in the status bar.

Click on the encoding button in the status bar to reopen or save the active file with a different encoding.

Then choose an encoding.

Next steps

You've covered the basic user interface - there is a lot more to VS Code. Read on to find out about:

  • Intro Video - Setup and Basics - Watch a tutorial on the basics of VS Code.
  • User/Workspace Settings - Learn how to configure VS Code to your preferences through user and workspace settings.
  • Code Navigation - Peek and Goto Definition, and more.
  • Integrated Terminal - Learn about the integrated terminal for quickly performing command-line tasks from within VS Code.
  • IntelliSense - VS Code brings smart code completions.
  • Debugging - This is where VS Code really shines.

Common questions

Is it possible to globally search and replace?

Yes, expand the Search view text box to include a replace text field. You can search and replace across all the files in your workspace. Note that if you did not open VS Code on a folder, the search will only run on the currently open files.

How do I turn on word wrap?

You can control word wrap through the

"html.format.enable": false
46 setting. By default,
"html.format.enable": false
46 is
  "[html]": {
    "editor.foldingStrategy": "indentation"
  },
2 but if you set to it to
"html.format.enable": false
49, text will wrap on the editor's viewport width.

    "editor.wordWrap": "on"

You can toggle word wrap for the VS Code session with ⌥Z [Windows, Linux Alt+Z].

You can also add vertical column rulers to the editor with the

"html.format.enable": false
50 setting, which takes an array of column character positions where you'd like vertical rulers.

How can I avoid placing extra cursors in word wrapped lines?

If you'd like to ignore line wraps when adding cursors above or below your current selection, you can pass in

"html.format.enable": false
51 to
"html.format.enable": false
52 on the keybinding like this:

Chủ Đề