├── .github ├── CODEOWNERS ├── ISSUE_TEMPLATE.md └── PULL_REQUEST_TEMPLATE.md ├── CODE_OF_CONDUCT.md ├── LICENSE ├── README.md ├── Rguide.md ├── Rguide.xml ├── _includes └── head-custom.html ├── angularjs-google-style.html ├── assets └── css │ └── style.scss ├── cppguide.html ├── cppguide.xml ├── csharp-style.md ├── docguide ├── README.md ├── READMEs.md ├── VERSION ├── best_practices.md ├── philosophy.md └── style.md ├── eclipse-cpp-google-style.xml ├── eclipse-java-google-style.xml ├── favicon.ico ├── go ├── best-practices.md ├── decisions.md ├── guide.md └── index.md ├── google-c-style.el ├── google-r-style.html ├── google_python_style.vim ├── htmlcssguide.html ├── htmlcssguide.xml ├── include ├── jsguide.js ├── link.png ├── styleguide.css └── styleguide.js ├── intellij-java-google-style.xml ├── javaguide.css ├── javaguide.html ├── javaguidelink.png ├── javascriptguide.xml ├── jsguide.html ├── jsoncstyleguide.html ├── jsoncstyleguide.xml ├── jsoncstyleguide_example_01.png ├── jsoncstyleguide_example_02.png ├── lispguide.xml ├── objcguide.md ├── objcguide.xml ├── pyguide.md ├── pylintrc ├── shell.xml ├── shell.xsl ├── shellguide.md ├── styleguide.css ├── styleguide.xsl ├── tsguide.html ├── vimscriptfull.xml ├── vimscriptguide.xml └── xmlstyle.html /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | # https://docs.github.com/en/github/creating-cloning-and-archiving-repositories/about-code-owners#codeowners-syntax 2 | 3 | csharp-style.md @jbcoe 4 | htmlcssguide.html @tonyruscoe 5 | shellguide.md @eatnumber1 @vapier 6 | /go/ @chressie @gaal @katrinahoffert @kliegs @matttproud 7 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | This repository publishes copies of Google's internal style guides to 2 | assist developers working on Google owned and originated open source 3 | projects. Development on these guides does not take place here. 4 | 5 | Substantive changes to the style rules and suggested new rules should 6 | not be submitted as issues in this repository. Material changes must be 7 | proposed, discussed, and approved on the internal forums first. 8 | 9 | If an issue points out a simple mistake — a typo, a broken link, etc. — 10 | then a correction might be made. However there is no commitment to do 11 | so. Issues are normally closed without comment. 12 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | These style guides are copies of Google's internal style guides to 2 | assist developers working on Google owned and originated open source 3 | projects. Changes should be made to the internal style guide first and 4 | only then copied here. 5 | 6 | Unsolicited pull requests will not be merged and are usually closed 7 | without comment. If a PR points out a simple mistake — a typo, a broken 8 | link, etc. — then the correction can be made internally and copied here 9 | through the usual process. 10 | 11 | Substantive changes to the style rules and suggested new rules should 12 | not be submitted as a PR in this repository. Material changes must be 13 | proposed, discussed, and approved on the internal forums first. 14 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, caste, color, religion, or sexual identity 10 | and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | * Demonstrating empathy and kindness toward other people 21 | * Being respectful of differing opinions, viewpoints, and experiences 22 | * Giving and gracefully accepting constructive feedback 23 | * Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | * Focusing on what is best not just for us as individuals, but for the 26 | overall community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | * The use of sexualized language or imagery, and sexual attention or 31 | advances of any kind 32 | * Trolling, insulting or derogatory comments, and personal or political attacks 33 | * Public or private harassment 34 | * Publishing others' private information, such as a physical or email 35 | address, without their explicit permission 36 | * Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Repo maintainers are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Repo maintainers have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Attribution 60 | 61 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 62 | version 2.0, available at 63 | [https://www.contributor-covenant.org/version/2/0/code_of_conduct.html][v2.0]. 64 | 65 | Community Impact Guidelines were inspired by 66 | [Mozilla's code of conduct enforcement ladder][Mozilla CoC]. 67 | 68 | For answers to common questions about this code of conduct, see the FAQ at 69 | [https://www.contributor-covenant.org/faq][FAQ]. 70 | 71 | [homepage]: https://www.contributor-covenant.org 72 | [v2.0]: https://www.contributor-covenant.org/version/2/0/code_of_conduct.html 73 | [Mozilla CoC]: https://github.com/mozilla/diversity 74 | [FAQ]: https://www.contributor-covenant.org/faq 75 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Creative Commons Legal Code 2 | 3 | Attribution 3.0 Unported 4 | 5 | CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE 6 | LEGAL SERVICES. DISTRIBUTION OF THIS LICENSE DOES NOT CREATE AN 7 | ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS 8 | INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES 9 | REGARDING THE INFORMATION PROVIDED, AND DISCLAIMS LIABILITY FOR 10 | DAMAGES RESULTING FROM ITS USE. 11 | 12 | License 13 | 14 | THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE 15 | COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY 16 | COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS 17 | AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED. 18 | 19 | BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE 20 | TO BE BOUND BY THE TERMS OF THIS LICENSE. TO THE EXTENT THIS LICENSE MAY 21 | BE CONSIDERED TO BE A CONTRACT, THE LICENSOR GRANTS YOU THE RIGHTS 22 | CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND 23 | CONDITIONS. 24 | 25 | 1. Definitions 26 | 27 | a. "Adaptation" means a work based upon the Work, or upon the Work and 28 | other pre-existing works, such as a translation, adaptation, 29 | derivative work, arrangement of music or other alterations of a 30 | literary or artistic work, or phonogram or performance and includes 31 | cinematographic adaptations or any other form in which the Work may be 32 | recast, transformed, or adapted including in any form recognizably 33 | derived from the original, except that a work that constitutes a 34 | Collection will not be considered an Adaptation for the purpose of 35 | this License. For the avoidance of doubt, where the Work is a musical 36 | work, performance or phonogram, the synchronization of the Work in 37 | timed-relation with a moving image ("synching") will be considered an 38 | Adaptation for the purpose of this License. 39 | b. "Collection" means a collection of literary or artistic works, such as 40 | encyclopedias and anthologies, or performances, phonograms or 41 | broadcasts, or other works or subject matter other than works listed 42 | in Section 1(f) below, which, by reason of the selection and 43 | arrangement of their contents, constitute intellectual creations, in 44 | which the Work is included in its entirety in unmodified form along 45 | with one or more other contributions, each constituting separate and 46 | independent works in themselves, which together are assembled into a 47 | collective whole. A work that constitutes a Collection will not be 48 | considered an Adaptation (as defined above) for the purposes of this 49 | License. 50 | c. "Distribute" means to make available to the public the original and 51 | copies of the Work or Adaptation, as appropriate, through sale or 52 | other transfer of ownership. 53 | d. "Licensor" means the individual, individuals, entity or entities that 54 | offer(s) the Work under the terms of this License. 55 | e. "Original Author" means, in the case of a literary or artistic work, 56 | the individual, individuals, entity or entities who created the Work 57 | or if no individual or entity can be identified, the publisher; and in 58 | addition (i) in the case of a performance the actors, singers, 59 | musicians, dancers, and other persons who act, sing, deliver, declaim, 60 | play in, interpret or otherwise perform literary or artistic works or 61 | expressions of folklore; (ii) in the case of a phonogram the producer 62 | being the person or legal entity who first fixes the sounds of a 63 | performance or other sounds; and, (iii) in the case of broadcasts, the 64 | organization that transmits the broadcast. 65 | f. "Work" means the literary and/or artistic work offered under the terms 66 | of this License including without limitation any production in the 67 | literary, scientific and artistic domain, whatever may be the mode or 68 | form of its expression including digital form, such as a book, 69 | pamphlet and other writing; a lecture, address, sermon or other work 70 | of the same nature; a dramatic or dramatico-musical work; a 71 | choreographic work or entertainment in dumb show; a musical 72 | composition with or without words; a cinematographic work to which are 73 | assimilated works expressed by a process analogous to cinematography; 74 | a work of drawing, painting, architecture, sculpture, engraving or 75 | lithography; a photographic work to which are assimilated works 76 | expressed by a process analogous to photography; a work of applied 77 | art; an illustration, map, plan, sketch or three-dimensional work 78 | relative to geography, topography, architecture or science; a 79 | performance; a broadcast; a phonogram; a compilation of data to the 80 | extent it is protected as a copyrightable work; or a work performed by 81 | a variety or circus performer to the extent it is not otherwise 82 | considered a literary or artistic work. 83 | g. "You" means an individual or entity exercising rights under this 84 | License who has not previously violated the terms of this License with 85 | respect to the Work, or who has received express permission from the 86 | Licensor to exercise rights under this License despite a previous 87 | violation. 88 | h. "Publicly Perform" means to perform public recitations of the Work and 89 | to communicate to the public those public recitations, by any means or 90 | process, including by wire or wireless means or public digital 91 | performances; to make available to the public Works in such a way that 92 | members of the public may access these Works from a place and at a 93 | place individually chosen by them; to perform the Work to the public 94 | by any means or process and the communication to the public of the 95 | performances of the Work, including by public digital performance; to 96 | broadcast and rebroadcast the Work by any means including signs, 97 | sounds or images. 98 | i. "Reproduce" means to make copies of the Work by any means including 99 | without limitation by sound or visual recordings and the right of 100 | fixation and reproducing fixations of the Work, including storage of a 101 | protected performance or phonogram in digital form or other electronic 102 | medium. 103 | 104 | 2. Fair Dealing Rights. Nothing in this License is intended to reduce, 105 | limit, or restrict any uses free from copyright or rights arising from 106 | limitations or exceptions that are provided for in connection with the 107 | copyright protection under copyright law or other applicable laws. 108 | 109 | 3. License Grant. Subject to the terms and conditions of this License, 110 | Licensor hereby grants You a worldwide, royalty-free, non-exclusive, 111 | perpetual (for the duration of the applicable copyright) license to 112 | exercise the rights in the Work as stated below: 113 | 114 | a. to Reproduce the Work, to incorporate the Work into one or more 115 | Collections, and to Reproduce the Work as incorporated in the 116 | Collections; 117 | b. to create and Reproduce Adaptations provided that any such Adaptation, 118 | including any translation in any medium, takes reasonable steps to 119 | clearly label, demarcate or otherwise identify that changes were made 120 | to the original Work. For example, a translation could be marked "The 121 | original work was translated from English to Spanish," or a 122 | modification could indicate "The original work has been modified."; 123 | c. to Distribute and Publicly Perform the Work including as incorporated 124 | in Collections; and, 125 | d. to Distribute and Publicly Perform Adaptations. 126 | e. For the avoidance of doubt: 127 | 128 | i. Non-waivable Compulsory License Schemes. In those jurisdictions in 129 | which the right to collect royalties through any statutory or 130 | compulsory licensing scheme cannot be waived, the Licensor 131 | reserves the exclusive right to collect such royalties for any 132 | exercise by You of the rights granted under this License; 133 | ii. Waivable Compulsory License Schemes. In those jurisdictions in 134 | which the right to collect royalties through any statutory or 135 | compulsory licensing scheme can be waived, the Licensor waives the 136 | exclusive right to collect such royalties for any exercise by You 137 | of the rights granted under this License; and, 138 | iii. Voluntary License Schemes. The Licensor waives the right to 139 | collect royalties, whether individually or, in the event that the 140 | Licensor is a member of a collecting society that administers 141 | voluntary licensing schemes, via that society, from any exercise 142 | by You of the rights granted under this License. 143 | 144 | The above rights may be exercised in all media and formats whether now 145 | known or hereafter devised. The above rights include the right to make 146 | such modifications as are technically necessary to exercise the rights in 147 | other media and formats. Subject to Section 8(f), all rights not expressly 148 | granted by Licensor are hereby reserved. 149 | 150 | 4. Restrictions. The license granted in Section 3 above is expressly made 151 | subject to and limited by the following restrictions: 152 | 153 | a. You may Distribute or Publicly Perform the Work only under the terms 154 | of this License. You must include a copy of, or the Uniform Resource 155 | Identifier (URI) for, this License with every copy of the Work You 156 | Distribute or Publicly Perform. You may not offer or impose any terms 157 | on the Work that restrict the terms of this License or the ability of 158 | the recipient of the Work to exercise the rights granted to that 159 | recipient under the terms of the License. You may not sublicense the 160 | Work. You must keep intact all notices that refer to this License and 161 | to the disclaimer of warranties with every copy of the Work You 162 | Distribute or Publicly Perform. When You Distribute or Publicly 163 | Perform the Work, You may not impose any effective technological 164 | measures on the Work that restrict the ability of a recipient of the 165 | Work from You to exercise the rights granted to that recipient under 166 | the terms of the License. This Section 4(a) applies to the Work as 167 | incorporated in a Collection, but this does not require the Collection 168 | apart from the Work itself to be made subject to the terms of this 169 | License. If You create a Collection, upon notice from any Licensor You 170 | must, to the extent practicable, remove from the Collection any credit 171 | as required by Section 4(b), as requested. If You create an 172 | Adaptation, upon notice from any Licensor You must, to the extent 173 | practicable, remove from the Adaptation any credit as required by 174 | Section 4(b), as requested. 175 | b. If You Distribute, or Publicly Perform the Work or any Adaptations or 176 | Collections, You must, unless a request has been made pursuant to 177 | Section 4(a), keep intact all copyright notices for the Work and 178 | provide, reasonable to the medium or means You are utilizing: (i) the 179 | name of the Original Author (or pseudonym, if applicable) if supplied, 180 | and/or if the Original Author and/or Licensor designate another party 181 | or parties (e.g., a sponsor institute, publishing entity, journal) for 182 | attribution ("Attribution Parties") in Licensor's copyright notice, 183 | terms of service or by other reasonable means, the name of such party 184 | or parties; (ii) the title of the Work if supplied; (iii) to the 185 | extent reasonably practicable, the URI, if any, that Licensor 186 | specifies to be associated with the Work, unless such URI does not 187 | refer to the copyright notice or licensing information for the Work; 188 | and (iv) , consistent with Section 3(b), in the case of an Adaptation, 189 | a credit identifying the use of the Work in the Adaptation (e.g., 190 | "French translation of the Work by Original Author," or "Screenplay 191 | based on original Work by Original Author"). The credit required by 192 | this Section 4 (b) may be implemented in any reasonable manner; 193 | provided, however, that in the case of a Adaptation or Collection, at 194 | a minimum such credit will appear, if a credit for all contributing 195 | authors of the Adaptation or Collection appears, then as part of these 196 | credits and in a manner at least as prominent as the credits for the 197 | other contributing authors. For the avoidance of doubt, You may only 198 | use the credit required by this Section for the purpose of attribution 199 | in the manner set out above and, by exercising Your rights under this 200 | License, You may not implicitly or explicitly assert or imply any 201 | connection with, sponsorship or endorsement by the Original Author, 202 | Licensor and/or Attribution Parties, as appropriate, of You or Your 203 | use of the Work, without the separate, express prior written 204 | permission of the Original Author, Licensor and/or Attribution 205 | Parties. 206 | c. Except as otherwise agreed in writing by the Licensor or as may be 207 | otherwise permitted by applicable law, if You Reproduce, Distribute or 208 | Publicly Perform the Work either by itself or as part of any 209 | Adaptations or Collections, You must not distort, mutilate, modify or 210 | take other derogatory action in relation to the Work which would be 211 | prejudicial to the Original Author's honor or reputation. Licensor 212 | agrees that in those jurisdictions (e.g. Japan), in which any exercise 213 | of the right granted in Section 3(b) of this License (the right to 214 | make Adaptations) would be deemed to be a distortion, mutilation, 215 | modification or other derogatory action prejudicial to the Original 216 | Author's honor and reputation, the Licensor will waive or not assert, 217 | as appropriate, this Section, to the fullest extent permitted by the 218 | applicable national law, to enable You to reasonably exercise Your 219 | right under Section 3(b) of this License (right to make Adaptations) 220 | but not otherwise. 221 | 222 | 5. Representations, Warranties and Disclaimer 223 | 224 | UNLESS OTHERWISE MUTUALLY AGREED TO BY THE PARTIES IN WRITING, LICENSOR 225 | OFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY 226 | KIND CONCERNING THE WORK, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE, 227 | INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY, 228 | FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF 229 | LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS, 230 | WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION 231 | OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU. 232 | 233 | 6. Limitation on Liability. EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE 234 | LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR 235 | ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES 236 | ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS 237 | BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 238 | 239 | 7. Termination 240 | 241 | a. This License and the rights granted hereunder will terminate 242 | automatically upon any breach by You of the terms of this License. 243 | Individuals or entities who have received Adaptations or Collections 244 | from You under this License, however, will not have their licenses 245 | terminated provided such individuals or entities remain in full 246 | compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will 247 | survive any termination of this License. 248 | b. Subject to the above terms and conditions, the license granted here is 249 | perpetual (for the duration of the applicable copyright in the Work). 250 | Notwithstanding the above, Licensor reserves the right to release the 251 | Work under different license terms or to stop distributing the Work at 252 | any time; provided, however that any such election will not serve to 253 | withdraw this License (or any other license that has been, or is 254 | required to be, granted under the terms of this License), and this 255 | License will continue in full force and effect unless terminated as 256 | stated above. 257 | 258 | 8. Miscellaneous 259 | 260 | a. Each time You Distribute or Publicly Perform the Work or a Collection, 261 | the Licensor offers to the recipient a license to the Work on the same 262 | terms and conditions as the license granted to You under this License. 263 | b. Each time You Distribute or Publicly Perform an Adaptation, Licensor 264 | offers to the recipient a license to the original Work on the same 265 | terms and conditions as the license granted to You under this License. 266 | c. If any provision of this License is invalid or unenforceable under 267 | applicable law, it shall not affect the validity or enforceability of 268 | the remainder of the terms of this License, and without further action 269 | by the parties to this agreement, such provision shall be reformed to 270 | the minimum extent necessary to make such provision valid and 271 | enforceable. 272 | d. No term or provision of this License shall be deemed waived and no 273 | breach consented to unless such waiver or consent shall be in writing 274 | and signed by the party to be charged with such waiver or consent. 275 | e. This License constitutes the entire agreement between the parties with 276 | respect to the Work licensed here. There are no understandings, 277 | agreements or representations with respect to the Work not specified 278 | here. Licensor shall not be bound by any additional provisions that 279 | may appear in any communication from You. This License may not be 280 | modified without the mutual written agreement of the Licensor and You. 281 | f. The rights granted under, and the subject matter referenced, in this 282 | License were drafted utilizing the terminology of the Berne Convention 283 | for the Protection of Literary and Artistic Works (as amended on 284 | September 28, 1979), the Rome Convention of 1961, the WIPO Copyright 285 | Treaty of 1996, the WIPO Performances and Phonograms Treaty of 1996 286 | and the Universal Copyright Convention (as revised on July 24, 1971). 287 | These rights and subject matter take effect in the relevant 288 | jurisdiction in which the License terms are sought to be enforced 289 | according to the corresponding provisions of the implementation of 290 | those treaty provisions in the applicable national law. If the 291 | standard suite of rights granted under applicable copyright law 292 | includes additional rights not granted under this License, such 293 | additional rights are deemed to be included in the License; this 294 | License is not intended to restrict the license of any rights under 295 | applicable law. 296 | 297 | 298 | Creative Commons Notice 299 | 300 | Creative Commons is not a party to this License, and makes no warranty 301 | whatsoever in connection with the Work. Creative Commons will not be 302 | liable to You or any party on any legal theory for any damages 303 | whatsoever, including without limitation any general, special, 304 | incidental or consequential damages arising in connection to this 305 | license. Notwithstanding the foregoing two (2) sentences, if Creative 306 | Commons has expressly identified itself as the Licensor hereunder, it 307 | shall have all rights and obligations of Licensor. 308 | 309 | Except for the limited purpose of indicating to the public that the 310 | Work is licensed under the CCPL, Creative Commons does not authorize 311 | the use by either party of the trademark "Creative Commons" or any 312 | related trademark or logo of Creative Commons without the prior 313 | written consent of Creative Commons. Any permitted use will be in 314 | compliance with Creative Commons' then-current trademark usage 315 | guidelines, as may be published on its website or otherwise made 316 | available upon request from time to time. For the avoidance of doubt, 317 | this trademark restriction does not form part of this License. 318 | 319 | Creative Commons may be contacted at https://creativecommons.org/. 320 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Google Style Guides 2 | 3 | Every major open-source project has its own style guide: a set of conventions 4 | (sometimes arbitrary) about how to write code for that project. It is much 5 | easier to understand a large codebase when all the code in it is in a consistent 6 | style. 7 | 8 | “Style” covers a lot of ground, from “use camelCase for variable names” to 9 | “never use global variables” to “never use exceptions.” This project 10 | ([google/styleguide](https://github.com/google/styleguide)) links to the style 11 | guidelines we use for Google code. If you are modifying a project that 12 | originated at Google, you may be pointed to this page to see the style guides 13 | that apply to that project. 14 | 15 | 16 | * [AngularJS Style Guide][angular] 17 | * [Common Lisp Style Guide][cl] 18 | * [C++ Style Guide][cpp] 19 | * [C# Style Guide][csharp] 20 | * [Go Style Guide][go] 21 | * [HTML/CSS Style Guide][htmlcss] 22 | * [JavaScript Style Guide][js] 23 | * [Java Style Guide][java] 24 | * [JSON Style Guide][json] 25 | * [Markdown Style Guide][markdown] 26 | * [Objective-C Style Guide][objc] 27 | * [Python Style Guide][py] 28 | * [R Style Guide][r] 29 | * [Shell Style Guide][sh] 30 | * [Swift Style Guide][swift] 31 | * [TypeScript Style Guide][ts] 32 | * [Vim script Style Guide][vim] 33 | 34 | This project also contains [google-c-style.el][emacs], an Emacs settings file 35 | for Google style. 36 | 37 | We used to host the cpplint tool, but we stopped making internal updates public. 38 | An open source community has forked the project, so users are encouraged to use 39 | https://github.com/cpplint/cpplint instead. 40 | 41 | If your project requires that you create a new XML document format, the 42 | [XML Document Format Style Guide][xml] may be helpful. In addition to actual 43 | style rules, it also contains advice on designing your own vs. adapting an 44 | existing format, on XML instance document formatting, and on elements vs. 45 | attributes. 46 | 47 | The style guides in this project are licensed under the CC-By 3.0 License, which 48 | encourages you to share these documents. See 49 | [https://creativecommons.org/licenses/by/3.0/][ccl] for more details. 50 | 51 | The following Google style guide lives outside of this project: 52 | 53 | * [Effective Dart][dart] 54 | * [Kotlin Style Guide][kotlin] 55 | 56 | Since projects are largely maintained in a [VCS], writing good commit messages 57 | is important to long term project health. Please refer to [How to Write a Git 58 | Commit Message](https://cbea.ms/git-commit/) as an excellent resource. While it 59 | explicitly refers to the Git [SCM], its principles apply to any system, and many 60 | Git conventions are trivial to translate to others. 61 | 62 | ## Contributing 63 | 64 | With few exceptions, these style guides are copies of Google's internal style 65 | guides to assist developers working on Google owned and originated open source 66 | projects. Changes to the style guides are made to the internal style guides 67 | first and eventually copied into the versions found here. **External 68 | contributions are not accepted.** Pull requests are regularly closed without 69 | comment. 70 | 71 | People can file [issues using the GitHub tracker][gh-tracker]. Issues that raise 72 | questions, justify changes on technical merits, or point out obvious mistakes 73 | may get some engagement and could in theory lead to changes, but we are 74 | primarily optimizing for Google's internal needs. 75 | 76 | Creative Commons License 77 | 78 | [cpp]: https://google.github.io/styleguide/cppguide.html 79 | [csharp]: https://google.github.io/styleguide/csharp-style.html 80 | [swift]: https://google.github.io/swift/ 81 | [objc]: objcguide.md 82 | [gh-tracker]: https://github.com/google/styleguide/issues 83 | [go]: go/ 84 | [java]: https://google.github.io/styleguide/javaguide.html 85 | [json]: https://google.github.io/styleguide/jsoncstyleguide.xml 86 | [kotlin]: https://developer.android.com/kotlin/style-guide 87 | [py]: https://google.github.io/styleguide/pyguide.html 88 | [r]: https://google.github.io/styleguide/Rguide.html 89 | [sh]: https://google.github.io/styleguide/shellguide.html 90 | [htmlcss]: https://google.github.io/styleguide/htmlcssguide.html 91 | [js]: https://google.github.io/styleguide/jsguide.html 92 | [markdown]: https://google.github.io/styleguide/docguide/style.html 93 | [ts]: https://google.github.io/styleguide/tsguide.html 94 | [angular]: https://google.github.io/styleguide/angularjs-google-style.html 95 | [cl]: https://google.github.io/styleguide/lispguide.xml 96 | [vim]: https://google.github.io/styleguide/vimscriptguide.xml 97 | [emacs]: https://raw.githubusercontent.com/google/styleguide/gh-pages/google-c-style.el 98 | [xml]: https://google.github.io/styleguide/xmlstyle.html 99 | [dart]: https://www.dartlang.org/guides/language/effective-dart 100 | [ccl]: https://creativecommons.org/licenses/by/3.0/ 101 | [SCM]: https://en.wikipedia.org/wiki/Source_control_management 102 | [VCS]: https://en.wikipedia.org/wiki/Version_control_system 103 | -------------------------------------------------------------------------------- /Rguide.md: -------------------------------------------------------------------------------- 1 | # Google's R Style Guide 2 | 3 | R is a high-level programming language used primarily for statistical computing 4 | and graphics. The goal of the R Programming Style Guide is to make our R code 5 | easier to read, share, and verify. 6 | 7 | The Google R Style Guide is a fork of the 8 | [Tidyverse Style Guide](https://style.tidyverse.org/) by Hadley Wickham 9 | [license](https://creativecommons.org/licenses/by-sa/2.0/). Google modifications 10 | were developed in collaboration with the internal R user community. The rest of 11 | this document explains Google's primary differences with the Tidyverse guide, 12 | and why these differences exist. 13 | 14 | ## Syntax 15 | 16 | ### Naming conventions 17 | 18 | Google prefers identifying functions with `BigCamelCase` to clearly distinguish 19 | them from other objects. 20 | 21 | ``` 22 | # Good 23 | DoNothing <- function() { 24 | return(invisible(NULL)) 25 | } 26 | ``` 27 | 28 | The names of private functions should begin with a dot. This helps communicate 29 | both the origin of the function and its intended use. 30 | 31 | ``` 32 | # Good 33 | .DoNothingPrivately <- function() { 34 | return(invisible(NULL)) 35 | } 36 | ``` 37 | 38 | We previously recommended naming objects with `dot.case`. We're moving away from 39 | that, as it creates confusion with S3 methods. 40 | 41 | ### Don't use attach() 42 | 43 | The possibilities for creating errors when using `attach()` are numerous. 44 | 45 | ## Pipes 46 | 47 | ### Right-hand assignment 48 | 49 | We do not support using right-hand assignment. 50 | 51 | ``` 52 | # Bad 53 | iris %>% 54 | dplyr::summarize(max_petal = max(Petal.Width)) -> results 55 | ``` 56 | 57 | This convention differs substantially from practices in other languages and 58 | makes it harder to see in code where an object is defined. E.g. searching for 59 | `foo <-` is easier than searching for `foo <-` and `-> foo` (possibly split over 60 | lines). 61 | 62 | ### Use explicit returns 63 | 64 | Do not rely on R's implicit return feature. It is better to be clear about your 65 | intent to `return()` an object. 66 | 67 | ``` 68 | # Good 69 | AddValues <- function(x, y) { 70 | return(x + y) 71 | } 72 | 73 | # Bad 74 | AddValues <- function(x, y) { 75 | x + y 76 | } 77 | ``` 78 | 79 | ### Qualifying namespaces 80 | 81 | Users should explicitly qualify namespaces for all external functions. 82 | 83 | ``` 84 | # Good 85 | purrr::map() 86 | ``` 87 | 88 | We discourage using the `@import` Roxygen tag to bring in all functions into a 89 | NAMESPACE. Google has a very big R codebase, and importing all functions creates 90 | too much risk for name collisions. 91 | 92 | While there is a small performance penalty for using `::`, it makes it easier to 93 | understand dependencies in your code. There are some exceptions to this rule. 94 | 95 | * Infix functions (`%name%`) always need to be imported. 96 | * Certain `rlang` pronouns, notably `.data`, need to be imported. 97 | * Functions from default R packages, including `datasets`, `utils`, 98 | `grDevices`, `graphics`, `stats` and `methods`. If needed, you can `@import` 99 | the full package. 100 | 101 | When importing functions, place the `@importFrom` tag in the Roxygen header 102 | above the function where the external dependency is used. 103 | 104 | ## Documentation 105 | 106 | ### Package-level documentation 107 | 108 | All packages should have a package documentation file, in a 109 | `packagename-package.R` file. 110 | -------------------------------------------------------------------------------- /Rguide.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Google's R Style Guide 8 | 9 | 10 |

Google's R Style Guide

11 |

12 | The style guide has moved to Rguide.html 13 |

14 | 15 | 16 | -------------------------------------------------------------------------------- /_includes/head-custom.html: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /angularjs-google-style.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | Google's AngularJS Style Guide 12 | 15 | 16 | 17 |

An AngularJS Style Guide for Closure Users at Google

18 | 19 | 20 | 21 |

This is the external version of a document that was primarily written for Google 22 | engineers. It describes a recommended style for AngularJS apps that use Closure, as used 23 | internally at Google. Members of the broader AngularJS community should feel free to apply 24 | (or not apply) these recommendations, as relevant to their own use cases.

25 | 26 |

This document describes style for AngularJS apps in google3. This guide 27 | supplements and extends the 28 | Google JavaScript Style Guide. 29 |

30 | 31 |

Style Note: Examples on the AngularJS external webpage, and many external apps, are 32 | written in a style that freely uses closures, favors functional inheritance, and does not often use 33 | 35 | JavaScript types. Google follows a more rigorous Javascript style to support JSCompiler 36 | optimizations and large code bases - see the javascript-style mailing list. 37 | This is not an Angular-specific issue, and is not discussed further in this style guide. 38 | (But if you want further reading: 39 | Martin Fowler on closures, 40 | much longer description, appendix A of the 41 | 42 | closure book has a good description of inheritance patterns and why it prefers 43 | pseudoclassical, 44 | 45 | Javascript, the Good Parts as a counter.)

46 | 47 |

1 Angular Language Rules

48 | 49 |

Manage dependencies with Closure's goog.require and goog.provide

50 |

Choose a namespace for your project, and use goog.provide and goog.require.

51 |
 52 | goog.provide('hello.about.AboutCtrl');
 53 | goog.provide('hello.versions.Versions');
 54 | 
55 | 56 |

Why? 57 | Google BUILD rules integrate nicely with closure provide/require.

58 | 59 |

Modules

60 | 61 |

Your main application module should be in your root client directory. A module should never be 62 | altered other than the one where it is defined.

63 | 64 |

Modules may either be defined in the same file as their components (this works well for a module 65 | that contains exactly one service) or in a separate file for wiring pieces together.

66 | 67 |

Why? 68 | A module should be consistent for anyone that wants to include it as a reusable component. 69 | If a module can mean different things depending on which files are included, it is not consistent. 70 |

71 | 72 |

73 | Modules should reference other modules using the Angular Module's "name" property 74 |

75 | 76 |

For example:

77 | 78 |
 79 | // file submodulea.js:
 80 |   goog.provide('my.submoduleA');
 81 | 
 82 |   my.submoduleA = angular.module('my.submoduleA', []);
 83 |   // ...
 84 | 
 85 | // file app.js
 86 |   goog.require('my.submoduleA');
 87 | 
 88 |   Yes: my.application.module = angular.module('hello', [my.submoduleA.name]);
 89 |   
 90 |       No: my.application.module = angular.module('hello', ['my.submoduleA']);
 91 |   
92 | 93 |

Why? 94 | Using a property of my.submoduleA prevents Closure presubmit failures complaining that the file is 95 | required but never used. Using the .name property avoids duplicating strings.

96 | 97 |

Use a common externs file

98 | 99 |

This maximally allows the JS compiler to enforce type safety in the presence of externally 100 | provided types from Angular, and means you don't have to worry about Angular vars being obfuscated 101 | in a confusing way.

102 | 103 |

Note to readers outside Google: the current externs file is located in an internal-to-Google 104 | directory, but an example can be found on github 105 | here.

106 | 107 |

JSCompiler Flags

108 |

Reminder: According to the JS style guide, customer facing code must be compiled.

109 | 110 |

Recommended: Use the JSCompiler (the closure compiler that works with js_binary by 111 | default) and ANGULAR_COMPILER_FLAGS_FULL from //javascript/angular/build_defs/build_defs for 112 | your base flags. 113 |

114 | 115 |

Note - if you are using @export for methods, you will need to add the compiler flag

116 |
117 | "--generate_exports",
118 | 
119 | 120 |

If you are using @export for properties, you will need to add the flags:

121 |
122 | "--generate_exports",
123 | "--remove_unused_prototype_props_in_externs=false",
124 | "--export_local_property_definitions",
125 | 
126 | 127 |

Controllers and Scopes

128 |

Controllers are classes. Methods should be defined on MyCtrl.prototype.

129 | 130 |

Google Angular applications should use the 'controller as' style to export the controller 131 | onto the scope. This is fully implemented in Angular 1.2 and can be mimicked in pre-Angular 1.2 132 | builds. 133 |

134 | 135 |

Pre Angular 1.2, this looks like:

136 |
137 | /**
138 |  * Home controller.
139 |  *
140 |  * @param {!angular.Scope} $scope
141 |  * @constructor
142 |  * @ngInject
143 |  * @export
144 |  */
145 | hello.mainpage.HomeCtrl = function($scope) {
146 |   /** @export */
147 |   $scope.homeCtrl = this; // This is a bridge until Angular 1.2 controller-as
148 | 
149 |   /**
150 |    * @type {string}
151 |    * @export
152 |    */
153 |   this.myColor = 'blue';
154 | };
155 | 
156 | 
157 | /**
158 |  * @param {number} a
159 |  * @param {number} b
160 |  * @export
161 |  */
162 | hello.mainpage.HomeCtrl.prototype.add = function(a, b) {
163 |   return a + b;
164 | };
165 | 
166 | 167 |

And the template:

168 | 169 |
170 | <div ng-controller="hello.mainpage.HomeCtrl"/>
171 |   <span ng-class="homeCtrl.myColor">I'm in a color!</span>
172 |   <span>{{homeCtrl.add(5, 6)}}</span>
173 | </div>
174 | 
175 | 176 |

After Angular 1.2, this looks like:

177 | 178 |
179 | /**
180 |  * Home controller.
181 |  *
182 |  * @constructor
183 |  * @ngInject
184 |  * @export
185 |  */
186 | hello.mainpage.HomeCtrl = function() {
187 |   /**
188 |    * @type {string}
189 |    * @export
190 |    */
191 |   this.myColor = 'blue';
192 | };
193 | 
194 | 
195 | /**
196 |  * @param {number} a
197 |  * @param {number} b
198 |  * @export
199 |  */
200 | hello.mainpage.HomeCtrl.prototype.add = function(a, b) {
201 |   return a + b;
202 | };
203 | 
204 | 205 |

If you are compiling with property renaming, expose properties and methods using the @export 206 | annotation. Remember to @export the constructor as well.

207 | 208 |

And in the template:

209 | 210 |
211 | <div ng-controller="hello.mainpage.HomeCtrl as homeCtrl"/>
212 |   <span ng-class="homeCtrl.myColor">I'm in a color!</span>
213 |   <span>{{homeCtrl.add(5, 6)}}</span>
214 | </div>
215 | 
216 | 217 |

Why? 218 | Putting methods and properties directly onto the controller, instead of building up a scope 219 | object, fits better with the Google Closure class style. Additionally, using 'controller as' 220 | makes it obvious which controller you are accessing when multiple controllers apply to an element. 221 | Since there is always a '.' in the bindings, you don't have to worry about prototypal inheritance 222 | masking primitives.

223 | 224 |

Directives

225 | 226 |

All DOM manipulation should be done inside directives. Directives should be kept small and use 227 | composition. Files defining directives should goog.provide a static function which returns the 228 | directive definition object.

229 | 230 |
231 | goog.provide('hello.pane.paneDirective');
232 | 
233 | /**
234 |  * Description and usage
235 |  * @return {angular.Directive} Directive definition object.
236 |  */
237 | hello.pane.paneDirective = function() {
238 |   // ...
239 | };
240 | 
241 | 242 |

Exception: DOM manipulation may occur in services for DOM elements disconnected from the 243 | rest of the view, e.g. dialogs or keyboard shortcuts.

244 | 245 |

Services

246 | 247 |

Services registered on the module with module.service are classes. 248 | Use module.service instead of module.provider or 249 | module.factory unless you need to do initialization beyond just creating a 250 | new instance of the class.

251 | 252 |
253 | /**
254 |  * @param {!angular.$http} $http The Angular http service.
255 |  * @constructor
256 |  */
257 | hello.request.Request = function($http) {
258 |   /** @type {!angular.$http} */
259 |   this.http_ = $http;
260 | };
261 | 
262 | hello.request.Request.prototype.get = function() {/*...*/};
263 | 
264 | 265 |

In the module:

266 | 267 |
268 | module.service('request', hello.request.Request);
269 | 
270 | 271 | 272 |

2 Angular Style Rules

273 | 274 |

Reserve $ for Angular properties and services

275 |

Do not use $ to prepend your own object properties and service identifiers. Consider this style 276 | of naming reserved by AngularJS and jQuery.

277 | 278 |

Yes:

279 |
280 |   $scope.myModel = { value: 'foo' }
281 |   myModule.service('myService', function() { /*...*/ });
282 |   var MyCtrl = function($http) {this.http_ = $http;};
283 | 
284 | 285 |

No:

286 |
287 |   $scope.$myModel = { value: 'foo' } // BAD
288 |   $scope.myModel = { $value: 'foo' } // BAD
289 |   myModule.service('$myService', function() { ... }); // BAD
290 |   var MyCtrl = function($http) {this.$http_ = $http;}; // BAD
291 | 
292 | 293 |

Why? 294 | It's useful to distinguish between Angular / jQuery builtins and things you add yourself. 295 | In addition, $ is not an acceptable character for variables names in the JS style guide. 296 |

297 | 298 |

Custom elements

299 | 300 |

For custom elements (e.g. <ng-include src="template"></ng-include>), IE8 301 | requires special support (html5shiv-like hacks) to enable css styling. Be aware of this 302 | restriction in apps targeting old versions of IE.

303 | 304 |

3 Angular Tips, Tricks, and Best Practices

305 | 306 |

These are not strict style guide rules, but are placed here as reference for folks getting 307 | started with Angular at Google.

308 | 309 |

Testing

310 | 311 |

Angular is designed for test-driven development.

312 | 313 |

The recommended unit testing setup is Jasmine + Karma (though you could use closure tests 314 | or js_test)

315 | 316 |

Angular provides easy adapters to load modules and use the injector in Jasmine tests. 317 |

321 |

322 | 323 | 324 |

Consider using the Best Practices for App Structure

325 |

326 | This directory structure doc describes how to structure your application with controllers in 327 | nested subdirectories and all components (e.g. services and directives) in a 'components' dir. 328 |

329 | 330 | 331 |

Be aware of how scope inheritance works

332 | 333 |

See 334 | The Nuances of Scope Prototypal Inheritance

335 | 336 |

Use @ngInject for easy dependency injection compilation

337 |

This removes the need to add myCtrl['$inject'] = ... to prevent minification from 338 | messing up Angular's dependency injection.

339 | 340 |

Usage:

341 |
342 | /**
343 |  * My controller.
344 |  * @param {!angular.$http} $http
345 |  * @param {!my.app.myService} myService
346 |  * @constructor
347 |  * @export
348 |  * @ngInject
349 |  */
350 | my.app.MyCtrl = function($http, myService) {
351 |   //...
352 | };
353 | 
354 | 355 |

4 Best practices links and docs

356 | 357 | 363 |
364 | Last modified Feb 07 2013 365 |
366 | 367 | 368 | -------------------------------------------------------------------------------- /assets/css/style.scss: -------------------------------------------------------------------------------- 1 | --- 2 | # Keep this YAML front matter block to trigger Jekyll processing. 3 | # See https://jekyllrb.com/docs/frontmatter for more information. 4 | --- 5 | 6 | @import "{{ site.theme }}"; 7 | 8 | // Hide “This site is open source. Improve this page.” 9 | .footer { 10 | display: none; 11 | } 12 | -------------------------------------------------------------------------------- /cppguide.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Redirecting 7 | 8 | 14 | 15 | Redirecting you to cppguide.html. 16 | 17 | 18 | -------------------------------------------------------------------------------- /csharp-style.md: -------------------------------------------------------------------------------- 1 | # C# at Google Style Guide 2 | 3 | This style guide is for C# code developed internally at Google, and is the 4 | default style for C# code at Google. It makes stylistic choices that conform to 5 | other languages at Google, such as Google C++ style and Google Java style. 6 | 7 | ## Formatting guidelines 8 | 9 | ### Naming rules 10 | 11 | Naming rules follow 12 | [Microsoft's C# naming guidelines](https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/naming-guidelines). 13 | Where Microsoft's naming guidelines are unspecified (e.g. private and local 14 | variables), rules are taken from the 15 | [CoreFX C# coding guidelines](https://github.com/dotnet/runtime/blob/HEAD/docs/coding-guidelines/coding-style.md) 16 | 17 | Rule summary: 18 | 19 | #### Code 20 | 21 | * Names of classes, methods, enumerations, public fields, public properties, 22 | namespaces: `PascalCase`. 23 | * Names of local variables, parameters: `camelCase`. 24 | * Names of private, protected, internal and protected internal fields and 25 | properties: `_camelCase`. 26 | * Naming convention is unaffected by modifiers such as const, static, 27 | readonly, etc. 28 | * For casing, a "word" is anything written without internal spaces, including 29 | acronyms. For example, `MyRpc` instead of ~~`MyRPC`~~. 30 | * Names of interfaces start with `I`, e.g. `IInterface`. 31 | 32 | #### Files 33 | 34 | * Filenames and directory names are `PascalCase`, e.g. `MyFile.cs`. 35 | * Where possible the file name should be the same as the name of the main 36 | class in the file, e.g. `MyClass.cs`. 37 | * In general, prefer one core class per file. 38 | 39 | ### Organization 40 | 41 | * Modifiers occur in the following order: `public protected internal private 42 | new abstract virtual override sealed static readonly extern unsafe volatile 43 | async`. 44 | * Namespace `using` declarations go at the top, before any namespaces. `using` 45 | import order is alphabetical, apart from `System` imports which always go 46 | first. 47 | * Class member ordering: 48 | * Group class members in the following order: 49 | * Nested classes, enums, delegates and events. 50 | * Static, const and readonly fields. 51 | * Fields and properties. 52 | * Constructors and finalizers. 53 | * Methods. 54 | * Within each group, elements should be in the following order: 55 | * Public. 56 | * Internal. 57 | * Protected internal. 58 | * Protected. 59 | * Private. 60 | * Where possible, group interface implementations together. 61 | 62 | ### Whitespace rules 63 | 64 | Developed from Google Java style. 65 | 66 | * A maximum of one statement per line. 67 | * A maximum of one assignment per statement. 68 | * Indentation of 2 spaces, no tabs. 69 | * Column limit: 100. 70 | * No line break before opening brace. 71 | * No line break between closing brace and `else`. 72 | * Braces used even when optional. 73 | * Space after `if`/`for`/`while` etc., and after commas. 74 | * No space after an opening parenthesis or before a closing parenthesis. 75 | * No space between a unary operator and its operand. One space between the 76 | operator and each operand of all other operators. 77 | * Line wrapping developed from Google C++ style guidelines, with minor 78 | modifications for compatibility with Microsoft's C# formatting tools: 79 | * In general, line continuations are indented 4 spaces. 80 | * Line breaks with braces (e.g. list initializers, lambdas, object 81 | initializers, etc) do not count as continuations. 82 | * For function definitions and calls, if the arguments do not all fit on 83 | one line they should be broken up onto multiple lines, with each 84 | subsequent line aligned with the first argument. If there is not enough 85 | room for this, arguments may instead be placed on subsequent lines with 86 | a four space indent. The code example below illustrates this. 87 | 88 | ### Example 89 | 90 | ```c# 91 | using System; // `using` goes at the top, outside the 92 | // namespace. 93 | 94 | namespace MyNamespace { // Namespaces are PascalCase. 95 | // Indent after namespace. 96 | public interface IMyInterface { // Interfaces start with 'I' 97 | public int Calculate(float value, float exp); // Methods are PascalCase 98 | // ...and space after comma. 99 | } 100 | 101 | public enum MyEnum { // Enumerations are PascalCase. 102 | Yes, // Enumerators are PascalCase. 103 | No, 104 | } 105 | 106 | public class MyClass { // Classes are PascalCase. 107 | public int Foo = 0; // Public member variables are 108 | // PascalCase. 109 | public bool NoCounting = false; // Field initializers are encouraged. 110 | private class Results { 111 | public int NumNegativeResults = 0; 112 | public int NumPositiveResults = 0; 113 | } 114 | private Results _results; // Private member variables are 115 | // _camelCase. 116 | public static int NumTimesCalled = 0; 117 | private const int _bar = 100; // const does not affect naming 118 | // convention. 119 | private int[] _someTable = { // Container initializers use a 2 120 | 2, 3, 4, // space indent. 121 | } 122 | 123 | public MyClass() { 124 | _results = new Results { 125 | NumNegativeResults = 1, // Object initializers use a 2 space 126 | NumPositiveResults = 1, // indent. 127 | }; 128 | } 129 | 130 | public int CalculateValue(int mulNumber) { // No line break before opening brace. 131 | var resultValue = Foo * mulNumber; // Local variables are camelCase. 132 | NumTimesCalled++; 133 | Foo += _bar; 134 | 135 | if (!NoCounting) { // No space after unary operator and 136 | // space after 'if'. 137 | if (resultValue < 0) { // Braces used even when optional and 138 | // spaces around comparison operator. 139 | _results.NumNegativeResults++; 140 | } else if (resultValue > 0) { // No newline between brace and else. 141 | _results.NumPositiveResults++; 142 | } 143 | } 144 | 145 | return resultValue; 146 | } 147 | 148 | public void ExpressionBodies() { 149 | // For simple lambdas, fit on one line if possible, no brackets or braces required. 150 | Func increment = x => x + 1; 151 | 152 | // Closing brace aligns with first character on line that includes the opening brace. 153 | Func difference1 = (x, y) => { 154 | long diff = (long)x - y; 155 | return diff >= 0 ? diff : -diff; 156 | }; 157 | 158 | // If defining after a continuation line break, indent the whole body. 159 | Func difference2 = 160 | (x, y) => { 161 | long diff = (long)x - y; 162 | return diff >= 0 ? diff : -diff; 163 | }; 164 | 165 | // Inline lambda arguments also follow these rules. Prefer a leading newline before 166 | // groups of arguments if they include lambdas. 167 | CallWithDelegate( 168 | (x, y) => { 169 | long diff = (long)x - y; 170 | return diff >= 0 ? diff : -diff; 171 | }); 172 | } 173 | 174 | void DoNothing() {} // Empty blocks may be concise. 175 | 176 | // If possible, wrap arguments by aligning newlines with the first argument. 177 | void AVeryLongFunctionNameThatCausesLineWrappingProblems(int longArgumentName, 178 | int p1, int p2) {} 179 | 180 | // If aligning argument lines with the first argument doesn't fit, or is difficult to 181 | // read, wrap all arguments on new lines with a 4 space indent. 182 | void AnotherLongFunctionNameThatCausesLineWrappingProblems( 183 | int longArgumentName, int longArgumentName2, int longArgumentName3) {} 184 | 185 | void CallingLongFunctionName() { 186 | int veryLongArgumentName = 1234; 187 | int shortArg = 1; 188 | // If possible, wrap arguments by aligning newlines with the first argument. 189 | AnotherLongFunctionNameThatCausesLineWrappingProblems(shortArg, shortArg, 190 | veryLongArgumentName); 191 | // If aligning argument lines with the first argument doesn't fit, or is difficult to 192 | // read, wrap all arguments on new lines with a 4 space indent. 193 | AnotherLongFunctionNameThatCausesLineWrappingProblems( 194 | veryLongArgumentName, veryLongArgumentName, veryLongArgumentName); 195 | } 196 | } 197 | } 198 | ``` 199 | 200 | ## C# coding guidelines 201 | 202 | ### Constants 203 | 204 | * Variables and fields that can be made `const` should always be made `const`. 205 | * If `const` isn’t possible, `readonly` can be a suitable alternative. 206 | * Prefer named constants to magic numbers. 207 | 208 | ### IEnumerable vs IList vs IReadOnlyList 209 | 210 | * For inputs use the most restrictive collection type possible, for example 211 | `IReadOnlyCollection` / `IReadOnlyList` / `IEnumerable` as inputs to methods 212 | when the inputs should be immutable. 213 | * For outputs, if passing ownership of the returned container to the owner, 214 | prefer `IList` over `IEnumerable`. If not transferring ownership, prefer the 215 | most restrictive option. 216 | 217 | ### Generators vs containers 218 | 219 | * Use your best judgement, bearing in mind: 220 | * Generator code is often less readable than filling in a container. 221 | * Generator code can be more performant if the results are going to be 222 | processed lazily, e.g. when not all the results are needed. 223 | * Generator code that is directly turned into a container via `ToList()` 224 | will be less performant than filling in a container directly. 225 | * Generator code that is called multiple times will be considerably slower 226 | than iterating over a container multiple times. 227 | 228 | ### Property styles 229 | 230 | * For single line read-only properties, prefer expression body properties 231 | (`=>`) when possible. 232 | * For everything else, use the older `{ get; set; }` syntax. 233 | 234 | ### Expression body syntax 235 | 236 | For example: 237 | 238 | ```c# 239 | int SomeProperty => _someProperty 240 | ``` 241 | 242 | * Judiciously use expression body syntax in lambdas and properties. 243 | * Don’t use on method definitions. This will be reviewed when C# 7 is live, 244 | which uses this syntax heavily. 245 | * As with methods and other scoped blocks of code, align the closing with the 246 | first character of the line that includes the opening brace. See sample code 247 | for examples. 248 | 249 | ### Structs and classes: 250 | 251 | * Structs are very different from classes: 252 | 253 | * Structs are always passed and returned by value. 254 | * Assigning a value to a member of a returned struct doesn’t modify the 255 | original - e.g. `transform.position.x = 10` doesn’t set the transform’s 256 | position.x to 10; `position` here is a property that returns a `Vector3` 257 | by value, so this just sets the x parameter of a copy of the original. 258 | 259 | * Almost always use a class. 260 | 261 | * Consider struct when the type can be treated like other value types - for 262 | example, if instances of the type are small and commonly short-lived or are 263 | commonly embedded in other objects. Good examples include Vector3, 264 | Quaternion and Bounds. 265 | 266 | * Note that this guidance may vary from team to team where, for example, 267 | performance issues might force the use of structs. 268 | 269 | ### Lambdas vs named methods 270 | 271 | * If a lambda is non-trivial (e.g. more than a couple of statements, excluding 272 | declarations), or is reused in multiple places, it should probably be a 273 | named method. 274 | 275 | ### Field initializers 276 | 277 | * Field initializers are generally encouraged. 278 | 279 | ### Extension methods 280 | 281 | * Only use an extension method when the source of the original class is not 282 | available, or else when changing the source is not feasible. 283 | * Only use an extension method if the functionality being added is a ‘core’ 284 | general feature that would be appropriate to add to the source of the 285 | original class. 286 | * Note - if we have the source to the class being extended, and the 287 | maintainer of the original class does not want to add the function, 288 | prefer not using an extension method. 289 | * Only put extension methods into core libraries that are available 290 | everywhere - extensions that are only available in some code will become a 291 | readability issue. 292 | * Be aware that using extension methods always obfuscates the code, so err on 293 | the side of not adding them. 294 | 295 | ### ref and out 296 | 297 | * Use `out` for returns that are not also inputs. 298 | * Place `out` parameters after all other parameters in the method definition. 299 | * `ref` should be used rarely, when mutating an input is necessary. 300 | * Do not use `ref` as an optimisation for passing structs. 301 | * Do not use `ref` to pass a modifiable container into a method. `ref` is only 302 | required when the supplied container needs be replaced with an entirely 303 | different container instance. 304 | 305 | ### LINQ 306 | 307 | * In general, prefer single line LINQ calls and imperative code, rather than 308 | long chains of LINQ. Mixing imperative code and heavily chained LINQ is 309 | often hard to read. 310 | * Prefer member extension methods over SQL-style LINQ keywords - e.g. prefer 311 | `myList.Where(x)` to `myList where x`. 312 | * Avoid `Container.ForEach(...)` for anything longer than a single statement. 313 | 314 | ### Array vs List 315 | 316 | * In general, prefer `List<>` over arrays for public variables, properties, 317 | and return types (keeping in mind the guidance on `IList` / `IEnumerable` / 318 | `IReadOnlyList` above). 319 | * Prefer `List<>` when the size of the container can change. 320 | * Prefer arrays when the size of the container is fixed and known at 321 | construction time. 322 | * Prefer array for multidimensional arrays. 323 | * Note: 324 | * array and `List<>` both represent linear, contiguous containers. 325 | * Similar to C++ arrays vs `std::vector`, arrays are of fixed capacity, 326 | whereas `List<>` can be added to. 327 | * In some cases arrays are more performant, but in general `List<>` is 328 | more flexible. 329 | 330 | ### Folders and file locations 331 | 332 | * Be consistent with the project. 333 | * Prefer a flat structure where possible. 334 | 335 | ### Use of tuple as a return type 336 | 337 | * In general, prefer a named class type over `Tuple<>`, particularly when 338 | returning complex types. 339 | 340 | ### String interpolation vs `String.Format()` vs `String.Concat` vs `operator+` 341 | 342 | * In general, use whatever is easiest to read, particularly for logging and 343 | assert messages. 344 | * Be aware that chained `operator+` concatenations will be slower and cause 345 | significant memory churn. 346 | * If performance is a concern, `StringBuilder` will be faster for multiple 347 | string concatenations. 348 | 349 | ### `using` 350 | 351 | * Generally, don’t alias long typenames with `using`. Often this is a sign 352 | that a `Tuple<>` needs to be turned into a class. 353 | * e.g. `using RecordList = List>` should probably be a 354 | named class instead. 355 | * Be aware that `using` statements are only file scoped and so of limited use. 356 | Type aliases will not be available for external users. 357 | 358 | ### Object Initializer syntax 359 | 360 | For example: 361 | 362 | ```c# 363 | var x = new SomeClass { 364 | Property1 = value1, 365 | Property2 = value2, 366 | }; 367 | ``` 368 | 369 | * Object Initializer Syntax is fine for ‘plain old data’ types. 370 | * Avoid using this syntax for classes or structs with constructors. 371 | * If splitting across multiple lines, indent one block level. 372 | 373 | ### Namespace naming 374 | 375 | * In general, namespaces should be no more than 2 levels deep. 376 | * Don't force file/folder layout to match namespaces. 377 | * For shared library/module code, use namespaces. For leaf 'application' code, 378 | such as `unity_app`, namespaces are not necessary. 379 | * New top-level namespace names must be globally unique and recognizable. 380 | 381 | ### Default values/null returns for structs 382 | 383 | * Prefer returning a ‘success’ boolean value and a struct `out` value. 384 | * Where performance isn't a concern and the resulting code significantly more 385 | readable (e.g. chained null conditional operators vs deeply nested if 386 | statements) nullable structs are acceptable. 387 | * Notes: 388 | 389 | * Nullable structs are convenient, but reinforce the general ‘null is 390 | failure’ pattern Google prefers to avoid. We will investigate a 391 | `StatusOr` equivalent in the future, if there is enough demand. 392 | 393 | ### Removing from containers while iterating 394 | 395 | C# (like many other languages) does not provide an obvious mechanism for 396 | removing items from containers while iterating. There are a couple of options: 397 | 398 | * If all that is required is to remove items that satisfy some condition, 399 | `someList.RemoveAll(somePredicate)` is recommended. 400 | * If other work needs to be done in the iteration, `RemoveAll` may not be 401 | sufficient. A common alternative pattern is to create a new container 402 | outside of the loop, insert items to keep in the new container, and swap the 403 | original container with the new one at the end of iteration. 404 | 405 | ### Calling delegates 406 | 407 | * When calling a delegate, use `Invoke()` and use the null conditional 408 | operator - e.g. `SomeDelegate?.Invoke()`. This clearly marks the call at the 409 | callsite as ‘a delegate that is being called’. The null check is concise and 410 | robust against threading race conditions. 411 | 412 | ### The `var` keyword 413 | 414 | * Use of `var` is encouraged if it aids readability by avoiding type names 415 | that are noisy, obvious, or unimportant. 416 | * Encouraged: 417 | 418 | * When the type is obvious - e.g. `var apple = new Apple();`, or `var 419 | request = Factory.Create();` 420 | * For transient variables that are only passed directly to other methods - 421 | e.g. `var item = GetItem(); ProcessItem(item);` 422 | 423 | * Discouraged: 424 | 425 | * When working with basic types - e.g. `var success = true;` 426 | * When working with compiler-resolved built-in numeric types - e.g. `var 427 | number = 12 * ReturnsFloat();` 428 | * When users would clearly benefit from knowing the type - e.g. `var 429 | listOfItems = GetList();` 430 | 431 | ### Attributes 432 | 433 | * Attributes should appear on the line above the field, property, or method 434 | they are associated with, separated from the member by a newline. 435 | * Multiple attributes should be separated by newlines. This allows for easier 436 | adding and removing of attributes, and ensures each attribute is easy to 437 | search for. 438 | 439 | ### Argument Naming 440 | 441 | Derived from the Google C++ style guide. 442 | 443 | When the meaning of a function argument is nonobvious, consider one of the 444 | following remedies: 445 | 446 | * If the argument is a literal constant, and the same constant is used in 447 | multiple function calls in a way that tacitly assumes they're the same, use 448 | a named constant to make that constraint explicit, and to guarantee that it 449 | holds. 450 | * Consider changing the function signature to replace a `bool` argument with 451 | an `enum` argument. This will make the argument values self-describing. 452 | * Replace large or complex nested expressions with named variables. 453 | * Consider using 454 | [Named Arguments](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/named-and-optional-arguments) 455 | to clarify argument meanings at the call site. 456 | * For functions that have several configuration options, consider defining a 457 | single class or struct to hold all the options and pass an instance of that. 458 | This approach has several advantages. Options are referenced by name at the 459 | call site, which clarifies their meaning. It also reduces function argument 460 | count, which makes function calls easier to read and write. As an added 461 | benefit, call sites don't need to be changed when another option is added. 462 | 463 | Consider the following example: 464 | 465 | ```c# 466 | // Bad - what are these arguments? 467 | DecimalNumber product = CalculateProduct(values, 7, false, null); 468 | ``` 469 | 470 | versus: 471 | 472 | ```c# 473 | // Good 474 | ProductOptions options = new ProductOptions(); 475 | options.PrecisionDecimals = 7; 476 | options.UseCache = CacheUsage.DontUseCache; 477 | DecimalNumber product = CalculateProduct(values, options, completionDelegate: null); 478 | ``` 479 | -------------------------------------------------------------------------------- /docguide/README.md: -------------------------------------------------------------------------------- 1 | # Google documentation guide 2 | 3 | * [Markdown styleguide](style.md) 4 | * [Best practices](best_practices.md) 5 | * [README files](READMEs.md) 6 | * [Philosophy](philosophy.md) 7 | 8 | ## See also 9 | 10 | * [How to update this guide](https://goto.google.com/doc-guide), for Googlers. 11 | -------------------------------------------------------------------------------- /docguide/READMEs.md: -------------------------------------------------------------------------------- 1 | # READMEs 2 | 3 | About README.md files. 4 | 5 | 1. [Overview](#overview) 6 | 1. [Readable README files](#readable-readme-files) 7 | 1. [Where to put your README](#where-to-put-your-readme) 8 | 1. [What to put in your README](#what-to-put-in-your-readme) 9 | 10 | ## Overview 11 | 12 | A README is a short summary of the contents of a directory. The contents of the 13 | file are displayed in GitHub and Gitiles when you view the contents of the 14 | containing directory. README files provide critical information for people 15 | browsing your code, especially first-time users. 16 | 17 | This document covers how to create README files that are readable with GitHub 18 | and Gitiles. 19 | 20 | ## Readable README files 21 | 22 | **README files must be named `README.md`.** The file name *must* end with the 23 | `.md` extension and is case sensitive. 24 | 25 | For example, the file /README.md is rendered when you view the contents of the 26 | containing directory: 27 | 28 | https://github.com/google/styleguide/tree/gh-pages 29 | 30 | Also `README.md` at `HEAD` ref is rendered by Gitiles when displaying repository 31 | index: 32 | 33 | https://gerrit.googlesource.com/gitiles/ 34 | 35 | ## Where to put your README 36 | 37 | Unlike all other Markdown files, `README.md` files should not be located inside 38 | your product or library's documentation directory. `README.md` files should be 39 | located in the top-level directory for your product or library's actual 40 | codebase. 41 | 42 | All top-level directories for a code package should have an up-to-date 43 | `README.md` file. This is especially important for package directories that 44 | provide interfaces for other teams. 45 | 46 | ## What to put in your README 47 | 48 | At a minimum, your `README.md` file should contain a link to your user- and/or 49 | team-facing documentation. 50 | 51 | Every package-level `README.md` should include or point to the following 52 | information: 53 | 54 | 1. What is in this package or library and what's it used for. 55 | 1. Points of contact. 56 | 1. Status of whether this package or library is deprecated, or not for general 57 | release, etc. 58 | 1. How to use the package or library. Examples include sample code, copyable 59 | `bazel run` or `bazel test` commands, etc. 60 | 1. Links to relevant documentation. 61 | -------------------------------------------------------------------------------- /docguide/VERSION: -------------------------------------------------------------------------------- 1 | 2.0 2 | -------------------------------------------------------------------------------- /docguide/best_practices.md: -------------------------------------------------------------------------------- 1 | # Documentation Best Practices 2 | 3 | "Say what you mean, simply and directly." - 4 | [Brian Kernighan](https://en.wikipedia.org/wiki/The_Elements_of_Programming_Style) 5 | 6 | Contents: 7 | 8 | 1. [Minimum Viable Documentation](#minimum-viable-documentation) 9 | 1. [Update Docs with Code](#update-docs-with-code) 10 | 1. [Delete Dead Documentation](#delete-dead-documentation) 11 | 1. [Prefer the Good Over the Perfect](#prefer-the-good-over-the-perfect) 12 | 1. [Documentation is the Story of Your Code](#documentation-is-the-story-of-your-code) 13 | 1. [Duplication is Evil](#duplication-is-evil) 14 | 15 | ## Minimum Viable Documentation 16 | 17 | A small set of fresh and accurate docs is better than a large assembly of 18 | "documentation" in various states of disrepair. 19 | 20 | Write short and useful documents. Cut out everything unnecessary, including 21 | out-of-date, incorrect, or redundant information. Also make a habit of 22 | continually massaging and improving every doc to suit your changing needs. 23 | **Docs work best when they are alive but frequently trimmed, like a bonsai 24 | tree**. 25 | 26 | See also 27 | [these Agile Documentation best practices](https://www.agilemodeling.com/essays/agileDocumentationBestPractices.htm). 28 | 29 | ## Update Docs with Code 30 | 31 | **Change your documentation in the same CL as the code change**. This keeps your 32 | docs fresh, and is also a good place to explain to your reviewer what you're 33 | doing. 34 | 35 | A good reviewer can at least insist that docstrings, header files, README.md 36 | files, and any other docs get updated alongside the CL. 37 | 38 | ## Delete Dead Documentation 39 | 40 | Dead docs are bad. They misinform, they slow down, they incite despair in 41 | engineers and laziness in team leads. They set a precedent for leaving behind 42 | messes in a code base. If your home is clean, most guests will be clean without 43 | being asked. 44 | 45 | Just like any big cleaning project, **it's easy to be overwhelmed**. If your 46 | docs are in bad shape: 47 | 48 | * Take it slow, doc health is a gradual accumulation. 49 | * First delete what you're certain is wrong, ignore what's unclear. 50 | * Get your whole team involved. Devote time to quickly scan every doc and make 51 | a simple decision: Keep or delete? 52 | * Default to delete or leave behind if migrating. Stragglers can always be 53 | recovered. 54 | * Iterate. 55 | 56 | ## Prefer the Good Over the Perfect 57 | 58 | Documentation is an art. There is no perfect document, there are only proven 59 | methods and prudent guidelines. See [Better is better than best](./style.md). 60 | 61 | ## Documentation is the Story of Your Code 62 | 63 | Writing excellent code doesn't end when your code compiles or even if your test 64 | coverage reaches 100%. It's easy to write something a computer understands, it's 65 | much harder to write something both a human and a computer understand. Your 66 | mission as a Code Health-conscious engineer is to **write for humans first, 67 | computers second.** Documentation is an important part of this skill. 68 | 69 | There's a spectrum of engineering documentation that ranges from terse comments 70 | to detailed prose: 71 | 72 | 1. **Meaningful names**: Good naming allows the code to convey information that 73 | would otherwise be relegated to comments or documentation. This includes 74 | nameable entities at all levels, from local variables to classes, files, and 75 | directories. 76 | 77 | 2. **Inline comments**: The primary purpose of inline comments is to provide 78 | information that the code itself cannot contain, such as why the code is 79 | there. 80 | 81 | 3. **Method and class comments**: 82 | 83 | * **Method API documentation**: The header / Javadoc / docstring comments 84 | that say what methods do and how to use them. This documentation is 85 | **the contract of how your code must behave**. The intended audience is 86 | future programmers who will use and modify your code. 87 | 88 | It is often reasonable to say that any behavior documented here should 89 | have a test verifying it. This documentation details what arguments the 90 | method takes, what it returns, any "gotchas" or restrictions, and what 91 | exceptions it can throw or errors it can return. It does not usually 92 | explain why code behaves a particular way unless that's relevant to a 93 | developer's understanding of how to use the method. "Why" explanations 94 | are for inline comments. Think in practical terms when writing method 95 | documentation: "This is a hammer. You use it to pound nails." 96 | 97 | * **Class / Module API documentation**: The header / Javadoc / docstring 98 | comments for a class or a whole file. This documentation gives a brief 99 | overview of what the class / file does and often gives a few short 100 | examples of how you might use the class / file. 101 | 102 | Examples are particularly relevant when there's several distinct ways to 103 | use the class (some advanced, some simple). Always list the simplest use 104 | case first. 105 | 106 | 4. **README.md**: A good README.md orients the new user to the directory and 107 | points to more detailed explanation and user guides: 108 | 109 | * What is this directory intended to hold? 110 | * Which files should the developer look at first? Are some files an API? 111 | * Who maintains this directory and where I can learn more? 112 | 113 | See the [README.md guidelines](READMEs.md). 114 | 115 | 5. **docs**: The contents of a good docs directory explain how to: 116 | 117 | * Get started using the relevant API, library, or tool. 118 | * Run its tests. 119 | * Debug its output. 120 | * Release the binary. 121 | 122 | 6. **Design docs, PRDs**: A good design doc or PRD discusses the proposed 123 | implementation at length for the purpose of collecting feedback on that 124 | design. However, once the code is implemented, design docs should serve as 125 | archives of these decisions, not as half-correct docs (they are often 126 | misused). 127 | 128 | 7. **Other external docs**: Some teams maintain documentation in other 129 | locations, separate from the code, such as Google Sites, Drive, or wiki. 130 | If you do maintain documentation in 131 | other locations, you should clearly point to those locations from your 132 | project directory (for example, by adding an obvious link to the location 133 | from your project's `README.md`). 134 | 135 | ## Duplication is Evil 136 | 137 | Do not write your own guide to a common Google technology or process. Link to it 138 | instead. If the guide doesn't exist or it's badly out of date, submit your 139 | updates to the appropriate directory or create a package-level 140 | README.md. **Take ownership and don't be shy**: Other teams will usually welcome 141 | your contributions. 142 | -------------------------------------------------------------------------------- /docguide/philosophy.md: -------------------------------------------------------------------------------- 1 | # Philosophy 2 | 3 | 埏埴以為器,當其無,有器之用. 4 | 5 | *Clay becomes pottery through craft, but it's the emptiness that makes a pot 6 | useful.* 7 | 8 | \- [Laozi](https://ctext.org/dictionary.pl?if=en&id=11602) 9 | 10 | Contents: 11 | 12 | 1. [Radical simplicity](#radical-simplicity) 13 | 1. [Readable source text](#readable-source-text) 14 | 1. [Minimum viable documentation](#minimum-viable-documentation) 15 | 1. [Better is better than best](#better-is-better-than-best) 16 | 17 | ## Radical simplicity 18 | 19 | * **Scalability and interoperability** are more important than a menagerie of 20 | unessential features. Scale comes from simplicity, speed, and ease. 21 | Interoperability comes from unadorned, digestible content. 22 | 23 | * **Fewer distractions** make for better writing and more productive reading. 24 | 25 | * **New features should never interfere with the simplest use case** and 26 | should remain invisible to users who don't need them. 27 | 28 | * **Markdown is designed for the average engineer** -- the busy, 29 | just-want-to-go-back-to-coding engineer. Large and complex documentation is 30 | possible but not the primary focus. 31 | 32 | * **Minimizing context switching makes people happier.** Engineers should be 33 | able to interact with documentation using the same tools they use to read 34 | and write code. 35 | 36 | ## Readable source text 37 | 38 | * **Plain text not only suffices, it is superior**. Markdown itself is not 39 | essential to this formula, but it is the best and most widely supported 40 | solution right now. HTML is generally not encouraged. 41 | 42 | * **Content and presentation should not mingle**. It should always be possible 43 | to ditch the renderer and read the essential information at source. Users 44 | should never have to touch the presentation layer if they don't want to. 45 | 46 | * **Portability and future-proofing leave room for the unimagined integrations 47 | to come**, and are best achieved by keeping the source as human-readable as 48 | possible. 49 | 50 | * **Static content is better than dynamic**, because content should not depend 51 | on the features of any one server. However, **fresh is better than stale**. We 52 | strive to balance these needs. 53 | 54 | ## Minimum viable documentation 55 | 56 | * **Docs thrive when they're treated like tests**: a necessary chore one learns 57 | to savor because it rewards over time. 58 | See [Best Practices](best_practices.md). 59 | 60 | * **Brief and utilitarian is better than long and exhaustive**. The vast 61 | majority of users need only a small fraction of the author's total knowledge, 62 | but they need it quickly and often. 63 | 64 | ## Better is better than best 65 | 66 | * **Incremental improvement is better than prolonged debate**. Patience and 67 | tolerance of imperfection allow projects to evolve organically. 68 | 69 | * **Don't 70 | [lick the cookie](https://community.redhat.com/blog/2018/09/dont-lick-the-cookie/), 71 | pass the plate**. Ideas are cheap. We're drowning in potentially impactful 72 | projects. Choose only those you can really handle and release those you 73 | can't. 74 | -------------------------------------------------------------------------------- /eclipse-cpp-google-style.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | -------------------------------------------------------------------------------- /favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/google/styleguide/1ab9120f856901f5cca56ca8947985628221b583/favicon.ico -------------------------------------------------------------------------------- /go/guide.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | # Go Style Guide 4 | 5 | https://google.github.io/styleguide/go/guide 6 | 7 | [Overview](index) | [Guide](guide) | [Decisions](decisions) | 8 | [Best practices](best-practices) 9 | 10 | 13 | 14 | {% raw %} 15 | 16 | **Note:** This is part of a series of documents that outline [Go Style](index) 17 | at Google. This document is **[normative](index#normative) and 18 | [canonical](index#canonical)**. See [the overview](index#about) for more 19 | information. 20 | 21 | 22 | 23 | ## Style principles 24 | 25 | There are a few overarching principles that summarize how to think about writing 26 | readable Go code. The following are attributes of readable code, in order of 27 | importance: 28 | 29 | 1. **[Clarity]**: The code's purpose and rationale is clear to the reader. 30 | 1. **[Simplicity]**: The code accomplishes its goal in the simplest way 31 | possible. 32 | 1. **[Concision]**: The code has a high signal-to-noise ratio. 33 | 1. **[Maintainability]**: The code is written such that it can be easily 34 | maintained. 35 | 1. **[Consistency]**: The code is consistent with the broader Google codebase. 36 | 37 | [Clarity]: #clarity 38 | [Simplicity]: #simplicity 39 | [Concision]: #concision 40 | [Maintainability]: #maintainability 41 | [Consistency]: #consistency 42 | 43 | 44 | 45 | ### Clarity 46 | 47 | The core goal of readability is to produce code that is clear to the reader. 48 | 49 | Clarity is primarily achieved with effective naming, helpful commentary, and 50 | efficient code organization. 51 | 52 | Clarity is to be viewed through the lens of the reader, not the author of the 53 | code. It is more important that code be easy to read than easy to write. Clarity 54 | in code has two distinct facets: 55 | 56 | * [What is the code actually doing?](#clarity-purpose) 57 | * [Why is the code doing what it does?](#clarity-rationale) 58 | 59 | 60 | 61 | #### What is the code actually doing? 62 | 63 | Go is designed such that it should be relatively straightforward to see what the 64 | code is doing. In cases of uncertainty or where a reader may require prior 65 | knowledge in order to understand the code, it is worth investing time in order 66 | to make the code's purpose clearer for future readers. For example, it may help 67 | to: 68 | 69 | * Use more descriptive variable names 70 | * Add additional commentary 71 | * Break up the code with whitespace and comments 72 | * Refactor the code into separate functions/methods to make it more modular 73 | 74 | There is no one-size-fits-all approach here, but it is important to prioritize 75 | clarity when developing Go code. 76 | 77 | 78 | 79 | #### Why is the code doing what it does? 80 | 81 | The code's rationale is often sufficiently communicated by the names of 82 | variables, functions, methods, or packages. Where it is not, it is important to 83 | add commentary. The "Why?" is especially important when the code contains 84 | nuances that a reader may not be familiar with, such as: 85 | 86 | * A nuance in the language, e.g., a closure will be capturing a loop variable, 87 | but the closure is many lines away 88 | * A nuance of the business logic, e.g., an access control check that needs to 89 | distinguish between the actual user and someone impersonating a user 90 | 91 | An API might require care to use correctly. For example, a piece of code may be 92 | intricate and difficult to follow for performance reasons, or a complex sequence 93 | of mathematical operations may use type conversions in an unexpected way. In 94 | these cases and many more, it is important that accompanying commentary and 95 | documentation explain these aspects so that future maintainers don't make a 96 | mistake and so that readers can understand the code without needing to 97 | reverse-engineer it. 98 | 99 | It is also important to be aware that some attempts to provide clarity (such as 100 | adding extra commentary) can actually obscure the code's purpose by adding 101 | clutter, restating what the code already says, contradicting the code, or adding 102 | maintenance burden to keep the comments up-to-date. Allow the code to speak for 103 | itself (e.g., by making the symbol names themselves self-describing) rather than 104 | adding redundant comments. It is often better for comments to explain why 105 | something is done, not what the code is doing. 106 | 107 | The Google codebase is largely uniform and consistent. It is often the case that 108 | code that stands out (e.g., by using an unfamiliar pattern) is doing so for a 109 | good reason, typically for performance. Maintaining this property is important 110 | to make it clear to readers where they should focus their attention when reading 111 | a new piece of code. 112 | 113 | The standard library contains many examples of this principle in action. Among 114 | them: 115 | 116 | * Maintainer comments in 117 | [`package sort`](https://cs.opensource.google/go/go/+/refs/tags/go1.19.2:src/sort/sort.go). 118 | * Good 119 | [runnable examples in the same package](https://cs.opensource.google/go/go/+/refs/tags/go1.19.2:src/sort/example_search_test.go), 120 | which benefit both users (they 121 | [show up in godoc](https://pkg.go.dev/sort#pkg-examples)) and maintainers 122 | (they [run as part of tests](decisions#examples)). 123 | * [`strings.Cut`](https://pkg.go.dev/strings#Cut) is only four lines of code, 124 | but they improve the 125 | [clarity and correctness of callsites](https://github.com/golang/go/issues/46336). 126 | 127 | 128 | 129 | ### Simplicity 130 | 131 | Your Go code should be simple for those using, reading, and maintaining it. 132 | 133 | Go code should be written in the simplest way that accomplishes its goals, both 134 | in terms of behavior and performance. Within the Google Go codebase, simple 135 | code: 136 | 137 | * Is easy to read from top to bottom 138 | * Does not assume that you already know what it is doing 139 | * Does not assume that you can memorize all of the preceding code 140 | * Does not have unnecessary levels of abstraction 141 | * Does not have names that call attention to something mundane 142 | * Makes the propagation of values and decisions clear to the reader 143 | * Has comments that explain why, not what, the code is doing to avoid future 144 | deviation 145 | * Has documentation that stands on its own 146 | * Has useful errors and useful test failures 147 | * May often be mutually exclusive with "clever" code 148 | 149 | Tradeoffs can arise between code simplicity and API usage simplicity. For 150 | example, it may be worthwhile to have the code be more complex so that the end 151 | user of the API may more easily call the API correctly. In contrast, it may also 152 | be worthwhile to leave a bit of extra work to the end user of the API so that 153 | the code remains simple and easy to understand. 154 | 155 | When code needs complexity, the complexity should be added deliberately. This is 156 | typically necessary if additional performance is required or where there are 157 | multiple disparate customers of a particular library or service. Complexity may 158 | be justified, but it should come with accompanying documentation so that clients 159 | and future maintainers are able to understand and navigate the complexity. This 160 | should be supplemented with tests and examples that demonstrate its correct 161 | usage, especially if there is both a "simple" and a "complex" way to use the 162 | code. 163 | 164 | This principle does not imply that complex code cannot or should not be written 165 | in Go or that Go code is not allowed to be complex. We strive for a codebase 166 | that avoids unnecessary complexity so that when complexity does appear, it 167 | indicates that the code in question requires care to understand and maintain. 168 | Ideally, there should be accompanying commentary that explains the rationale and 169 | identifies the care that should be taken. This often arises when optimizing code 170 | for performance; doing so often requires a more complex approach, like 171 | preallocating a buffer and reusing it throughout a goroutine lifetime. When a 172 | maintainer sees this, it should be a clue that the code in question is 173 | performance-critical, and that should influence the care that is taken when 174 | making future changes. If employed unnecessarily, on the other hand, this 175 | complexity is a burden on those who need to read or change the code in the 176 | future. 177 | 178 | If code turns out to be very complex when its purpose should be simple, this is 179 | often a signal to revisit the implementation to see if there is a simpler way to 180 | accomplish the same thing. 181 | 182 | 183 | 184 | #### Least mechanism 185 | 186 | Where there are several ways to express the same idea, prefer the one that uses 187 | the most standard tools. Sophisticated machinery often exists, but should not be 188 | employed without reason. It is easy to add complexity to code as needed, whereas 189 | it is much harder to remove existing complexity after it has been found to be 190 | unnecessary. 191 | 192 | 1. Aim to use a core language construct (for example a channel, slice, map, 193 | loop, or struct) when sufficient for your use case. 194 | 2. If there isn't one, look for a tool within the standard library (like an 195 | HTTP client or a template engine). 196 | 3. Finally, consider whether there is a core library in the Google codebase 197 | that is sufficient before introducing a new dependency or creating your own. 198 | 199 | As an example, consider production code that contains a flag bound to a variable 200 | with a default value which must be overridden in tests. Unless intending to test 201 | the program's command-line interface itself (say, with `os/exec`), it is simpler 202 | and therefore preferable to override the bound value directly rather than by 203 | using `flag.Set`. 204 | 205 | Similarly, if a piece of code requires a set membership check, a boolean-valued 206 | map (e.g., `map[string]bool`) often suffices. Libraries that provide set-like 207 | types and functionality should only be used if more complicated operations are 208 | required that are impossible or overly complicated with a map. 209 | 210 | 211 | 212 | ### Concision 213 | 214 | Concise Go code has a high signal-to-noise ratio. It is easy to discern the 215 | relevant details, and the naming and structure guide the reader through these 216 | details. 217 | 218 | There are many things that can get in the way of surfacing the most salient 219 | details at any given time: 220 | 221 | * Repetitive code 222 | * Extraneous syntax 223 | * [Opaque names](#naming) 224 | * Unnecessary abstraction 225 | * Whitespace 226 | 227 | Repetitive code especially obscures the differences between each 228 | nearly-identical section, and requires a reader to visually compare similar 229 | lines of code to find the changes. [Table-driven testing] is a good example of a 230 | mechanism that can concisely factor out the common code from the important 231 | details of each repetition, but the choice of which pieces to include in the 232 | table will have an impact on how easy the table is to understand. 233 | 234 | When considering multiple ways to structure code, it is worth considering which 235 | way makes important details the most apparent. 236 | 237 | Understanding and using common code constructions and idioms are also important 238 | for maintaining a high signal-to-noise ratio. For example, the following code 239 | block is very common in [error handling], and the reader can quickly understand 240 | the purpose of this block. 241 | 242 | ```go 243 | // Good: 244 | if err := doSomething(); err != nil { 245 | // ... 246 | } 247 | ``` 248 | 249 | If code looks very similar to this but is subtly different, a reader may not 250 | notice the change. In cases like this, it is worth intentionally ["boosting"] 251 | the signal of the error check by adding a comment to call attention to it. 252 | 253 | ```go 254 | // Good: 255 | if err := doSomething(); err == nil { // if NO error 256 | // ... 257 | } 258 | ``` 259 | 260 | [Table-driven testing]: https://github.com/golang/go/wiki/TableDrivenTests 261 | [error handling]: https://go.dev/blog/errors-are-values 262 | ["boosting"]: best-practices#signal-boost 263 | 264 | 265 | 266 | ### Maintainability 267 | 268 | Code is edited many more times than it is written. Readable code not only makes 269 | sense to a reader who is trying to understand how it works, but also to the 270 | programmer who needs to change it. Clarity is key. 271 | 272 | Maintainable code: 273 | 274 | * Is easy for a future programmer to modify correctly 275 | * Has APIs that are structured so that they can grow gracefully 276 | * Is clear about the assumptions that it makes and chooses abstractions that 277 | map to the structure of the problem, not to the structure of the code 278 | * Avoids unnecessary coupling and doesn't include features that are not used 279 | * Has a comprehensive test suite to ensure promised behaviors are maintained 280 | and important logic is correct, and the tests provide clear, actionable 281 | diagnostics in case of failure 282 | 283 | When using abstractions like interfaces and types which by definition remove 284 | information from the context in which they are used, it is important to ensure 285 | that they provide sufficient benefit. Editors and IDEs can connect directly to a 286 | method definition and show the corresponding documentation when a concrete type 287 | is used, but can only refer to an interface definition otherwise. Interfaces are 288 | a powerful tool, but come with a cost, since the maintainer may need to 289 | understand the specifics of the underlying implementation in order to correctly 290 | use the interface, which must be explained within the interface documentation or 291 | at the call-site. 292 | 293 | Maintainable code also avoids hiding important details in places that are easy 294 | to overlook. For example, in each of the following lines of code, the presence 295 | or lack of a single character is critical to understand the line: 296 | 297 | ```go 298 | // Bad: 299 | // The use of = instead of := can change this line completely. 300 | if user, err = db.UserByID(userID); err != nil { 301 | // ... 302 | } 303 | ``` 304 | 305 | ```go 306 | // Bad: 307 | // The ! in the middle of this line is very easy to miss. 308 | leap := (year%4 == 0) && (!(year%100 == 0) || (year%400 == 0)) 309 | ``` 310 | 311 | Neither of these are incorrect, but both could be written in a more explicit 312 | fashion, or could have an accompanying comment that calls attention to the 313 | important behavior: 314 | 315 | ```go 316 | // Good: 317 | u, err := db.UserByID(userID) 318 | if err != nil { 319 | return fmt.Errorf("invalid origin user: %s", err) 320 | } 321 | user = u 322 | ``` 323 | 324 | ```go 325 | // Good: 326 | // Gregorian leap years aren't just year%4 == 0. 327 | // See https://en.wikipedia.org/wiki/Leap_year#Algorithm. 328 | var ( 329 | leap4 = year%4 == 0 330 | leap100 = year%100 == 0 331 | leap400 = year%400 == 0 332 | ) 333 | leap := leap4 && (!leap100 || leap400) 334 | ``` 335 | 336 | In the same way, a helper function that hides critical logic or an important 337 | edge-case could make it easy for a future change to fail to account for it 338 | properly. 339 | 340 | Predictable names are another feature of maintainable code. A user of a package 341 | or a maintainer of a piece of code should be able to predict the name of a 342 | variable, method, or function in a given context. Function parameters and 343 | receiver names for identical concepts should typically share the same name, both 344 | to keep documentation understandable and to facilitate refactoring code with 345 | minimal overhead. 346 | 347 | Maintainable code minimizes its dependencies (both implicit and explicit). 348 | Depending on fewer packages means fewer lines of code that can affect behavior. 349 | Avoiding dependencies on internal or undocumented behavior makes code less 350 | likely to impose a maintenance burden when those behaviors change in the future. 351 | 352 | When considering how to structure or write code, it is worth taking the time to 353 | think through ways in which the code may evolve over time. If a given approach 354 | is more conducive to easier and safer future changes, that is often a good 355 | trade-off, even if it means a slightly more complicated design. 356 | 357 | 358 | 359 | ### Consistency 360 | 361 | Consistent code is code that looks, feels, and behaves like similar code 362 | throughout the broader codebase, within the context of a team or package, and 363 | even within a single file. 364 | 365 | Consistency concerns do not override any of the principles above, but if a tie 366 | must be broken, it is often beneficial to break it in favor of consistency. 367 | 368 | Consistency within a package is often the most immediately important level of 369 | consistency. It can be very jarring if the same problem is approached in 370 | multiple ways throughout a package, or if the same concept has many names within 371 | a file. However, even this should not override documented style principles or 372 | global consistency. 373 | 374 | 375 | 376 | ## Core guidelines 377 | 378 | These guidelines collect the most important aspects of Go style that all Go code 379 | is expected to follow. We expect that these principles be learned and followed 380 | by the time readability is granted. These are not expected to change frequently, 381 | and new additions will have to clear a high bar. 382 | 383 | The guidelines below expand on the recommendations in [Effective Go], which 384 | provide a common baseline for Go code across the entire community. 385 | 386 | [Effective Go]: https://go.dev/doc/effective_go 387 | 388 | 389 | 390 | ### Formatting 391 | 392 | All Go source files must conform to the format outputted by the `gofmt` tool. 393 | This format is enforced by a presubmit check in the Google codebase. 394 | [Generated code] should generally also be formatted (e.g., by using 395 | [`format.Source`]), as it is also browsable in Code Search. 396 | 397 | [Generated code]: https://docs.bazel.build/versions/main/be/general.html#genrule 398 | [`format.Source`]: https://pkg.go.dev/go/format#Source 399 | 400 | 401 | 402 | ### MixedCaps 403 | 404 | Go source code uses `MixedCaps` or `mixedCaps` (camel case) rather than 405 | underscores (snake case) when writing multi-word names. 406 | 407 | This applies even when it breaks conventions in other languages. For example, a 408 | constant is `MaxLength` (not `MAX_LENGTH`) if exported and `maxLength` (not 409 | `max_length`) if unexported. 410 | 411 | Local variables are considered [unexported] for the purpose of choosing the 412 | initial capitalization. 413 | 414 | 415 | 416 | [unexported]: https://go.dev/ref/spec#Exported_identifiers 417 | 418 | 419 | 420 | ### Line length 421 | 422 | There is no fixed line length for Go source code. If a line feels too long, 423 | prefer refactoring instead of splitting it. If it is already as short as it is 424 | practical for it to be, the line should be allowed to remain long. 425 | 426 | Do not split a line: 427 | 428 | * Before an [indentation change](decisions#indentation-confusion) (e.g., 429 | function declaration, conditional) 430 | * To make a long string (e.g., a URL) fit into multiple shorter lines 431 | 432 | 433 | 434 | ### Naming 435 | 436 | Naming is more art than science. In Go, names tend to be somewhat shorter than 437 | in many other languages, but the same [general guidelines] apply. Names should: 438 | 439 | * Not feel [repetitive](decisions#repetition) when they are used 440 | * Take the context into consideration 441 | * Not repeat concepts that are already clear 442 | 443 | You can find more specific guidance on naming in [decisions](decisions#naming). 444 | 445 | [general guidelines]: https://testing.googleblog.com/2017/10/code-health-identifiernamingpostforworl.html 446 | 447 | 448 | 449 | ### Local consistency 450 | 451 | Where the style guide has nothing to say about a particular point of style, 452 | authors are free to choose the style that they prefer, unless the code in close 453 | proximity (usually within the same file or package, but sometimes within a team 454 | or project directory) has taken a consistent stance on the issue. 455 | 456 | Examples of **valid** local style considerations: 457 | 458 | * Use of `%s` or `%v` for formatted printing of errors 459 | * Usage of buffered channels in lieu of mutexes 460 | 461 | Examples of **invalid** local style considerations: 462 | 463 | * Line length restrictions for code 464 | * Use of assertion-based testing libraries 465 | 466 | If the local style disagrees with the style guide but the readability impact is 467 | limited to one file, it will generally be surfaced in a code review for which a 468 | consistent fix would be outside the scope of the CL in question. At that point, 469 | it is appropriate to file a bug to track the fix. 470 | 471 | If a change would worsen an existing style deviation, expose it in more API 472 | surfaces, expand the number of files in which the deviation is present, or 473 | introduce an actual bug, then local consistency is no longer a valid 474 | justification for violating the style guide for new code. In these cases, it is 475 | appropriate for the author to clean up the existing codebase in the same CL, 476 | perform a refactor in advance of the current CL, or find an alternative that at 477 | least does not make the local problem worse. 478 | 479 | 482 | 483 | {% endraw %} 484 | -------------------------------------------------------------------------------- /go/index.md: -------------------------------------------------------------------------------- 1 | # Go Style 2 | 3 | https://google.github.io/styleguide/go 4 | 5 | [Overview](index) | [Guide](guide) | [Decisions](decisions) | 6 | [Best practices](best-practices) 7 | 8 | 11 | 12 | {% raw %} 13 | 14 | 15 | 16 | ## About 17 | 18 | The Go Style Guide and accompanying documents codify the current best approaches 19 | for writing readable and idiomatic Go. Adherence to the Style Guide is not 20 | intended to be absolute, and these documents will never be exhaustive. Our 21 | intention is to minimize the guesswork of writing readable Go so that newcomers 22 | to the language can avoid common mistakes. The Style Guide also serves to unify 23 | the style guidance given by anyone reviewing Go code at Google. 24 | 25 | Document | Link | Primary Audience | [Normative] | [Canonical] 26 | ------------------- | ----------------------------------------------------- | ------------------- | ----------- | ----------- 27 | **Style Guide** | https://google.github.io/styleguide/go/guide | Everyone | Yes | Yes 28 | **Style Decisions** | https://google.github.io/styleguide/go/decisions | Readability Mentors | Yes | No 29 | **Best Practices** | https://google.github.io/styleguide/go/best-practices | Anyone interested | No | No 30 | 31 | [Normative]: #normative 32 | [Canonical]: #canonical 33 | 34 | 35 | 36 | ### Documents 37 | 38 | 1. The **[Style Guide](https://google.github.io/styleguide/go/guide)** outlines 39 | the foundation of Go style at Google. This document is definitive and is 40 | used as the basis for the recommendations in Style Decisions and Best 41 | Practices. 42 | 43 | 1. **[Style Decisions](https://google.github.io/styleguide/go/decisions)** is a 44 | more verbose document that summarizes decisions on specific style points and 45 | discusses the reasoning behind the decisions where appropriate. 46 | 47 | These decisions may occasionally change based on new data, new language 48 | features, new libraries, or emerging patterns, but it is not expected that 49 | individual Go programmers at Google should keep up-to-date with this 50 | document. 51 | 52 | 1. **[Best Practices](https://google.github.io/styleguide/go/best-practices)** 53 | documents some of the patterns that have evolved over time that solve common 54 | problems, read well, and are robust to code maintenance needs. 55 | 56 | These best practices are not canonical, but Go programmers at Google are 57 | encouraged to use them where possible to keep the codebase uniform and 58 | consistent. 59 | 60 | These documents intend to: 61 | 62 | * Agree on a set of principles for weighing alternate styles 63 | * Codify settled matters of Go style 64 | * Document and provide canonical examples for Go idioms 65 | * Document the pros and cons of various style decisions 66 | * Help minimize surprises in Go readability reviews 67 | * Help readability mentors use consistent terminology and guidance 68 | 69 | These documents do **not** intend to: 70 | 71 | * Be an exhaustive list of comments that can be given in a readability review 72 | * List all of the rules everyone is expected to remember and follow at all 73 | times 74 | * Replace good judgment in the use of language features and style 75 | * Justify large-scale changes to get rid of style differences 76 | 77 | There will always be differences from one Go programmer to another and from one 78 | team's codebase to another. However, it is in the best interest of Google and 79 | Alphabet that our codebase be as consistent as possible. (See 80 | [guide](guide#consistency) for more on consistency.) To that end, feel free to 81 | make style improvements as you see fit, but you do not need to nit-pick every 82 | violation of the Style Guide that you find. In particular, these documents may 83 | change over time, and that is no reason to cause extra churn in existing 84 | codebases; it suffices to write new code using the latest best practices and 85 | address nearby issues over time. 86 | 87 | It is important to recognize that issues of style are inherently personal and 88 | that there are always inherent trade-offs. Much of the guidance in these 89 | documents is subjective, but just like with `gofmt`, there is significant value 90 | in the uniformity they provide. As such, style recommendations will not be 91 | changed without due discourse, Go programmers at Google are encouraged to follow 92 | the style guide even where they might disagree. 93 | 94 | 95 | 96 | ## Definitions 97 | 98 | The following words, which are used throughout the style documents, are defined 99 | below: 100 | 101 | * **Canonical**: Establishes prescriptive and enduring rules 102 | 103 | 104 | Within these documents, "canonical" is used to describe something that is 105 | considered a standard that all code (old and new) should follow and that is 106 | not expected to change substantially over time. Principles in the canonical 107 | documents should be understood by authors and reviewers alike, so everything 108 | included within a canonical document must meet a high bar. As such, 109 | canonical documents are generally shorter and prescribe fewer elements of 110 | style than non-canonical documents. 111 | 112 | https://google.github.io/styleguide/go#canonical 113 | 114 | * **Normative**: Intended to establish consistency 115 | 116 | Within these documents, "normative" is used to describe something that is an 117 | agreed-upon element of style for use by Go code reviewers, in order that the 118 | suggestions, terminology, and justifications are consistent. These elements 119 | may change over time, and these documents will reflect such changes so that 120 | reviewers can remain consistent and up-to-date. Authors of Go code are not 121 | expected to be familiar with the normative documents, but the documents will 122 | frequently be used as a reference by reviewers in readability reviews. 123 | 124 | https://google.github.io/styleguide/go#normative 125 | 126 | * **Idiomatic**: Common and familiar 127 | 128 | Within these documents, "idiomatic" is used to refer to something that is 129 | prevalent in Go code and has become a familiar pattern that is easy to 130 | recognize. In general, an idiomatic pattern should be preferred to something 131 | unidiomatic if both serve the same purpose in context, as this is what will 132 | be the most familiar to readers. 133 | 134 | https://google.github.io/styleguide/go#idiomatic 135 | 136 | 137 | 138 | ## Additional references 139 | 140 | This guide assumes the reader is familiar with [Effective Go], as it provides a 141 | common baseline for Go code across the entire Go community. 142 | 143 | Below are some additional resources for those looking to self-educate about Go 144 | style and for reviewers looking to provide further linkable context in their 145 | reviews. Participants in the Go readability process are not expected to be 146 | familiar with these resources, but they may arise as context in readability 147 | reviews. 148 | 149 | [Effective Go]: https://go.dev/doc/effective_go 150 | 151 | **External References** 152 | 153 | * [Go Language Specification](https://go.dev/ref/spec) 154 | * [Go FAQ](https://go.dev/doc/faq) 155 | * [Go Memory Model](https://go.dev/ref/mem) 156 | * [Go Data Structures](https://research.swtch.com/godata) 157 | * [Go Interfaces](https://research.swtch.com/interfaces) 158 | * [Go Proverbs](https://go-proverbs.github.io/) 159 | 160 | * Go Tip Episodes - stay tuned. 161 | 162 | * Unit Testing Practices - stay tuned. 163 | 164 | **Relevant Testing-on-the-Toilet articles** 165 | 166 | * [TotT: Identifier Naming][tott-431] 167 | * [TotT: Testing State vs. Testing Interactions][tott-281] 168 | * [TotT: Effective Testing][tott-324] 169 | * [TotT: Risk-driven Testing][tott-329] 170 | * [TotT: Change-detector Tests Considered Harmful][tott-350] 171 | 172 | [tott-431]: https://testing.googleblog.com/2017/10/code-health-identifiernamingpostforworl.html 173 | [tott-281]: https://testing.googleblog.com/2013/03/testing-on-toilet-testing-state-vs.html 174 | [tott-324]: https://testing.googleblog.com/2014/05/testing-on-toilet-effective-testing.html 175 | [tott-329]: https://testing.googleblog.com/2014/05/testing-on-toilet-risk-driven-testing.html 176 | [tott-350]: https://testing.googleblog.com/2015/01/testing-on-toilet-change-detector-tests.html 177 | 178 | **Additional External Writings** 179 | 180 | * [Go and Dogma](https://research.swtch.com/dogma) 181 | * [Less is exponentially more](https://commandcenter.blogspot.com/2012/06/less-is-exponentially-more.html) 182 | * [Esmerelda's Imagination](https://commandcenter.blogspot.com/2011/12/esmereldas-imagination.html) 183 | * [Regular expressions for parsing](https://commandcenter.blogspot.com/2011/08/regular-expressions-in-lexing-and.html) 184 | * [Gofmt's style is no one's favorite, yet Gofmt is everyone's favorite](https://www.youtube.com/watch?v=PAAkCSZUG1c&t=8m43s) 185 | (YouTube) 186 | 187 | 190 | 191 | {% endraw %} 192 | -------------------------------------------------------------------------------- /google-c-style.el: -------------------------------------------------------------------------------- 1 | ;;; google-c-style.el --- Google's C/C++ style for c-mode 2 | 3 | ;; Keywords: c, tools 4 | 5 | ;; google-c-style.el is Copyright (C) 2008 Google Inc. All Rights Reserved. 6 | ;; 7 | ;; It is free software; you can redistribute it and/or modify it under the 8 | ;; terms of either: 9 | ;; 10 | ;; a) the GNU General Public License as published by the Free Software 11 | ;; Foundation; either version 1, or (at your option) any later version, or 12 | ;; 13 | ;; b) the "Artistic License". 14 | 15 | ;;; Commentary: 16 | 17 | ;; Provides the google C/C++ coding style. You may wish to add 18 | ;; `google-set-c-style' to your `c-mode-common-hook' after requiring this 19 | ;; file. For example: 20 | ;; 21 | ;; (add-hook 'c-mode-common-hook 'google-set-c-style) 22 | ;; 23 | ;; If you want the RETURN key to go to the next line and space over 24 | ;; to the right place, add this to your .emacs right after the load-file: 25 | ;; 26 | ;; (add-hook 'c-mode-common-hook 'google-make-newline-indent) 27 | 28 | ;;; Code: 29 | 30 | ;; For some reason 1) c-backward-syntactic-ws is a macro and 2) under Emacs 22 31 | ;; bytecode cannot call (unexpanded) macros at run time: 32 | (eval-when-compile (require 'cc-defs)) 33 | 34 | ;; Wrapper function needed for Emacs 21 and XEmacs (Emacs 22 offers the more 35 | ;; elegant solution of composing a list of lineup functions or quantities with 36 | ;; operators such as "add") 37 | (defun google-c-lineup-expression-plus-4 (langelem) 38 | "Indents to the beginning of the current C expression plus 4 spaces. 39 | 40 | This implements title \"Function Declarations and Definitions\" 41 | of the Google C++ Style Guide for the case where the previous 42 | line ends with an open parenthesis. 43 | 44 | \"Current C expression\", as per the Google Style Guide and as 45 | clarified by subsequent discussions, means the whole expression 46 | regardless of the number of nested parentheses, but excluding 47 | non-expression material such as \"if(\" and \"for(\" control 48 | structures. 49 | 50 | Suitable for inclusion in `c-offsets-alist'." 51 | (save-excursion 52 | (back-to-indentation) 53 | ;; Go to beginning of *previous* line: 54 | (c-backward-syntactic-ws) 55 | (back-to-indentation) 56 | (cond 57 | ;; We are making a reasonable assumption that if there is a control 58 | ;; structure to indent past, it has to be at the beginning of the line. 59 | ((looking-at "\\(\\(if\\|for\\|while\\)\\s *(\\)") 60 | (goto-char (match-end 1))) 61 | ;; For constructor initializer lists, the reference point for line-up is 62 | ;; the token after the initial colon. 63 | ((looking-at ":\\s *") 64 | (goto-char (match-end 0)))) 65 | (vector (+ 4 (current-column))))) 66 | 67 | ;;;###autoload 68 | (defconst google-c-style 69 | `((c-recognize-knr-p . nil) 70 | (c-enable-xemacs-performance-kludge-p . t) ; speed up indentation in XEmacs 71 | (c-basic-offset . 2) 72 | (indent-tabs-mode . nil) 73 | (c-comment-only-line-offset . 0) 74 | (c-hanging-braces-alist . ((defun-open after) 75 | (defun-close before after) 76 | (class-open after) 77 | (class-close before after) 78 | (inexpr-class-open after) 79 | (inexpr-class-close before) 80 | (namespace-open after) 81 | (inline-open after) 82 | (inline-close before after) 83 | (block-open after) 84 | (block-close . c-snug-do-while) 85 | (extern-lang-open after) 86 | (extern-lang-close after) 87 | (statement-case-open after) 88 | (substatement-open after))) 89 | (c-hanging-colons-alist . ((case-label) 90 | (label after) 91 | (access-label after) 92 | (member-init-intro before) 93 | (inher-intro))) 94 | (c-hanging-semi&comma-criteria 95 | . (c-semi&comma-no-newlines-for-oneline-inliners 96 | c-semi&comma-inside-parenlist 97 | c-semi&comma-no-newlines-before-nonblanks)) 98 | (c-indent-comments-syntactically-p . t) 99 | (comment-column . 40) 100 | (c-indent-comment-alist . ((other . (space . 2)))) 101 | (c-cleanup-list . (brace-else-brace 102 | brace-elseif-brace 103 | brace-catch-brace 104 | empty-defun-braces 105 | defun-close-semi 106 | list-close-comma 107 | scope-operator)) 108 | (c-offsets-alist . ((arglist-intro google-c-lineup-expression-plus-4) 109 | (func-decl-cont . ++) 110 | (member-init-intro . ++) 111 | (inher-intro . ++) 112 | (comment-intro . 0) 113 | (arglist-close . c-lineup-arglist) 114 | (topmost-intro . 0) 115 | (block-open . 0) 116 | (inline-open . 0) 117 | (substatement-open . 0) 118 | (statement-cont 119 | . 120 | (,(when (fboundp 'c-no-indent-after-java-annotations) 121 | 'c-no-indent-after-java-annotations) 122 | ,(when (fboundp 'c-lineup-assignments) 123 | 'c-lineup-assignments) 124 | ++)) 125 | (label . /) 126 | (case-label . +) 127 | (statement-case-open . +) 128 | (statement-case-intro . +) ; case w/o { 129 | (access-label . /) 130 | (innamespace . 0)))) 131 | "Google C/C++ Programming Style.") 132 | 133 | ;;;###autoload 134 | (defun google-set-c-style () 135 | "Set the current buffer's c-style to Google C/C++ Programming 136 | Style. Meant to be added to `c-mode-common-hook'." 137 | (interactive) 138 | (make-local-variable 'c-tab-always-indent) 139 | (setq c-tab-always-indent t) 140 | (c-add-style "Google" google-c-style t)) 141 | 142 | ;;;###autoload 143 | (defun google-make-newline-indent () 144 | "Sets up preferred newline behavior. Not set by default. Meant 145 | to be added to `c-mode-common-hook'." 146 | (interactive) 147 | (define-key c-mode-base-map "\C-m" 'newline-and-indent) 148 | (define-key c-mode-base-map [ret] 'newline-and-indent)) 149 | 150 | (provide 'google-c-style) 151 | ;;; google-c-style.el ends here 152 | -------------------------------------------------------------------------------- /google-r-style.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Redirecting 7 | 8 | 14 | 15 | Redirecting you to Rguide.html. 16 | 17 | 18 | -------------------------------------------------------------------------------- /google_python_style.vim: -------------------------------------------------------------------------------- 1 | " Copyright 2019 Google LLC 2 | " 3 | " Licensed under the Apache License, Version 2.0 (the "License"); 4 | " you may not use this file except in compliance with the License. 5 | " You may obtain a copy of the License at 6 | " 7 | " https://www.apache.org/licenses/LICENSE-2.0 8 | " 9 | " Unless required by applicable law or agreed to in writing, software 10 | " distributed under the License is distributed on an "AS IS" BASIS, 11 | " WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | " See the License for the specific language governing permissions and 13 | " limitations under the License. 14 | 15 | " Indent Python in the Google way. 16 | 17 | setlocal indentexpr=GetGooglePythonIndent(v:lnum) 18 | 19 | let s:maxoff = 50 " maximum number of lines to look backwards. 20 | 21 | function GetGooglePythonIndent(lnum) 22 | 23 | " Indent inside parens. 24 | " Align with the open paren unless it is at the end of the line. 25 | " E.g. 26 | " open_paren_not_at_EOL(100, 27 | " (200, 28 | " 300), 29 | " 400) 30 | " open_paren_at_EOL( 31 | " 100, 200, 300, 400) 32 | call cursor(a:lnum, 1) 33 | let [par_line, par_col] = searchpairpos('(\|{\|\[', '', ')\|}\|\]', 'bW', 34 | \ "line('.') < " . (a:lnum - s:maxoff) . " ? dummy :" 35 | \ . " synIDattr(synID(line('.'), col('.'), 1), 'name')" 36 | \ . " =~ '\\(Comment\\|String\\)$'") 37 | if par_line > 0 38 | call cursor(par_line, 1) 39 | if par_col != col("$") - 1 40 | return par_col 41 | endif 42 | endif 43 | 44 | " Delegate the rest to the original function. 45 | return GetPythonIndent(a:lnum) 46 | 47 | endfunction 48 | 49 | let pyindent_nested_paren="&sw*2" 50 | let pyindent_open_paren="&sw*2" 51 | -------------------------------------------------------------------------------- /htmlcssguide.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |

5 | The style guide has moved to 6 | htmlcssguide.html 7 |

8 |
9 | -------------------------------------------------------------------------------- /include/jsguide.js: -------------------------------------------------------------------------------- 1 | window.initStyleGuide = function(init) { 2 | // Runs the callback on every element matched by the query selector. 3 | function find(querySelector, callback) { 4 | var elements = [].slice.call(document.querySelectorAll(querySelector)); 5 | for (var i = 0; i < elements.length; i++) { 6 | callback(elements[i]); 7 | } 8 | } 9 | // Add the tocDiv at the top. 10 | var title = document.getElementsByTagName('h1')[0]; 11 | var toc = document.createElement('div'); 12 | toc.id = 'tocDiv'; 13 | toc.className = 'vertical_toc'; 14 | title.parentNode.insertBefore(toc, title.nextSibling); 15 | 16 | // If a paragraph starts with (e.g.) "Note:" or "Tip:" then add 17 | // that "callout class" to its element. 18 | find('p', function(paragraph) { 19 | var match = /^([a-z]+):/i.exec(paragraph.textContent); 20 | if (match) { 21 | paragraph.classList.add(match[1].toLowerCase()); 22 | } 23 | }); 24 | 25 | // Fill in text for intra-document links, ensuring that links 26 | // remain up-to-date even if sections are moved or renumbered. 27 | // This triggers on any link with "??" as its text and a URL 28 | // starting with "#", and the filled-in text is exactly the same 29 | // as the text of the referenced section heading. 30 | find('a[href^="#"]', function(link) { 31 | var href = link.getAttribute('href'); 32 | var heading = document.getElementById(href.substring(1)); 33 | // Fill in link text with heading title 34 | if (heading && link.textContent == '??') { 35 | link.textContent = heading.textContent; 36 | } 37 | }); 38 | 39 | // Hoedown renders fenced code blocks incompatibly with what 40 | // prettify expects. As a result, prettify doesn't handle them 41 | // properly. Fix it by moving the code directly into the pre. 42 | find('pre > code', function(code) { 43 | var pre = code.parentElement; 44 | // Internal HTML/CSS & TS style guides do not use prettyprint. 45 | if (code.classList.contains('language-css') || 46 | code.classList.contains('language-django') || 47 | code.classList.contains('language-html') || 48 | code.classList.contains('language-ts')) { 49 | code.classList.add('prettyprint'); 50 | } 51 | pre.className = code.className; 52 | pre.innerHTML = code.innerHTML; 53 | }); 54 | 55 | // Run the normal init function. 56 | init(); 57 | 58 | // Call the pretty-printer after we've fixed up the code blocks. 59 | var pretty = document.createElement('script'); 60 | pretty.src = 'https://cdn.jsdelivr.net/gh/google/code-prettify@master/' + 61 | 'loader/run_prettify.js'; 62 | document.body.appendChild(pretty); 63 | }.bind(null, window.initStyleGuide); 64 | -------------------------------------------------------------------------------- /include/link.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/google/styleguide/1ab9120f856901f5cca56ca8947985628221b583/include/link.png -------------------------------------------------------------------------------- /include/styleguide.css: -------------------------------------------------------------------------------- 1 | /* General CSS */ 2 | 3 | body { 4 | background-color: #fff; 5 | color: #333; 6 | font-family: sans-serif; 7 | font-size: 10pt; 8 | margin-right: 100px; 9 | margin-left: 100px; 10 | } 11 | 12 | h1 { 13 | text-align: center; 14 | font-size: 18pt; 15 | } 16 | 17 | h1, h2, h3, h4, h5, h6 { 18 | color: #06c; 19 | margin-top: 2em; 20 | margin-bottom: 1em; 21 | padding: 25px; 22 | font-weight:bold; 23 | } 24 | 25 | h2, 26 | h3, 27 | h4, 28 | h5, 29 | h6 { 30 | margin-top:1.5em; 31 | margin-bottom:.75em; 32 | } 33 | 34 | h1 {font-size:200%;} 35 | h2 {font-size:167%;} 36 | h3 {font-size:133%;} 37 | h4 {font-size:120%;} 38 | h5 {font-size:110%;} 39 | 40 | 41 | table { 42 | border: 1px solid #bbb; 43 | border-spacing: 0; 44 | border-collapse: collapse; 45 | margin: 0 0 1.5em; 46 | vertical-align: middle; 47 | width: 100% 48 | } 49 | 50 | td, th { 51 | border: 1px solid #ccc; 52 | padding: 2px 12px; 53 | font-size: 10pt; 54 | } 55 | 56 | code, samp, var { 57 | background-color:#FAFAFA; 58 | white-space: nowrap 59 | } 60 | 61 | pre { 62 | padding:6px 10px; 63 | background-color:#FAFAFA; 64 | border:1px solid #bbb; 65 | overflow:auto; 66 | } 67 | 68 | pre.prettyprint { 69 | padding:6px 10px !important; 70 | border:1px solid #bbb !important; 71 | } 72 | 73 | code.bad, code.badcode { 74 | color: magenta; 75 | } 76 | 77 | pre.bad, pre.badcode { 78 | background-color:#ffe6d8; 79 | border-top:1px inset #a03; 80 | border-left:1px inset #a03; 81 | } 82 | 83 | hr { 84 | margin-top: 3.5em; 85 | border-width: 1px; 86 | color: #fff; 87 | } 88 | 89 | /* TOC CSS */ 90 | 91 | table.columns { 92 | border: none; 93 | } 94 | 95 | td.two_columns { 96 | -webkit-column-count: 2; 97 | column-count: 2; 98 | } 99 | 100 | .toc_category { 101 | font-size: 10pt; 102 | padding-top: 1em; 103 | padding-bottom: 1em; 104 | border-left-width: 2px; 105 | border-right-width: 2px; 106 | border-color: grey; 107 | } 108 | 109 | .toc_stylepoint { 110 | font-size: 10pt; 111 | padding-top: 1em; 112 | padding-bottom: 1em; 113 | } 114 | 115 | li.toc_entry { 116 | padding-right: 1em; 117 | display: inline; 118 | list-style-type: none; 119 | } 120 | 121 | /* 122 | * This space is required to trigger the linewrap on the links 123 | * at href boundaries 124 | */ 125 | li.toc_entry::after { 126 | content: " "; 127 | } 128 | 129 | li.toc_entry a { 130 | white-space: nowrap; 131 | } 132 | 133 | /* Horizontal TOC */ 134 | .toc td, .toc th { 135 | border-width: 1px 5px; 136 | overflow: hidden; 137 | } 138 | 139 | /* Vertical TOC */ 140 | 141 | .toc td.two_columns { 142 | border-width: 0px; 143 | } 144 | 145 | /* Special Sections */ 146 | 147 | address { 148 | text-align: right; 149 | } 150 | 151 | .revision { 152 | text-align: right; 153 | } 154 | 155 | .headerbox { 156 | margin-left: 50%; 157 | font-size: 75%; 158 | } 159 | 160 | .legend { 161 | padding-top: 1em; 162 | margin-left: 50%; 163 | font-size: 10pt; 164 | } 165 | 166 | .link_button { 167 | float: left; 168 | display: none; 169 | background-color: #f8f8ff; 170 | border-color: #f0f0ff; 171 | border-style: solid; 172 | border-width: 1px; 173 | font-size: 75%; 174 | margin-top: 0; 175 | margin-left: -50px; 176 | padding: 24px; 177 | border-radius: 3px; 178 | -webkit-border-radius: 3px; 179 | -moz-border-radius: 3px; 180 | } 181 | 182 | .ignoreLink { 183 | padding: 0px; 184 | } 185 | 186 | .divider{ 187 | width:5px; 188 | height:auto; 189 | display:inline-block; 190 | } 191 | 192 | /* Style Guide semantic CSS */ 193 | 194 | .summary { 195 | margin-top: 1em; 196 | margin-bottom: 1em; 197 | } 198 | 199 | .stylebody { 200 | margin-top: 1em; 201 | margin-bottom: 1em; 202 | } 203 | 204 | .stylepoint_section { 205 | display: block; 206 | margin-bottom: 1em; 207 | font-family: sans-serif; 208 | font-weight: bold; 209 | } 210 | 211 | .stylepoint_subsection { 212 | display: block; 213 | margin-bottom: 1em; 214 | } 215 | 216 | .stylepoint_subsubsection { 217 | display: block; 218 | margin-bottom: 1em; 219 | } 220 | 221 | .definition:before { 222 | content: "Definition: "; 223 | font-weight: bold; 224 | display: block; 225 | margin-bottom: 1em; 226 | } 227 | 228 | .pros:before { 229 | content: "Pros: "; 230 | font-weight: bold; 231 | display: block; 232 | margin-bottom: 1em; 233 | } 234 | 235 | .cons:before { 236 | content: "Cons: "; 237 | font-weight: bold; 238 | display: block; 239 | margin-bottom: 1em; 240 | } 241 | 242 | .decision:before { 243 | content: "Decision: "; 244 | font-weight: bold; 245 | display: block; 246 | margin-bottom: 1em; 247 | } 248 | 249 | .exception:before { 250 | content: "Exception: "; 251 | font-weight: bold; 252 | display: block; 253 | margin-bottom: 1em; 254 | } 255 | 256 | .note:before { 257 | content: "Note: "; 258 | font-weight: bold; 259 | display: block; 260 | margin-bottom: 1em; 261 | } 262 | -------------------------------------------------------------------------------- /include/styleguide.js: -------------------------------------------------------------------------------- 1 | TocTypeEnum = { 2 | VERTICAL: 1, 3 | HORIZONTAL: 2 4 | }; 5 | 6 | function CreateTOC(tocElement) { 7 | 8 | // Find the toc element DIV. We'll place our TOC there. 9 | var toc = document.getElementById(tocElement); 10 | 11 | var tocTypeClass = toc.className; 12 | var tocType; 13 | 14 | switch (tocTypeClass) { 15 | case 'horizontal_toc': 16 | tocType = TocTypeEnum.HORIZONTAL; 17 | break; 18 | case 'vertical_toc': 19 | tocType = TocTypeEnum.VERTICAL; 20 | break; 21 | default: 22 | tocType = TocTypeEnum.VERTICAL; 23 | break; 24 | } 25 | 26 | // If toc_levels is defined, set headingLevels to it. 27 | // Otherwise, use default value of "h2,h3" 28 | var headingLevels; 29 | if (typeof toc_levels === 'undefined') { 30 | headingLevels = 'h2,h3'; 31 | } else { 32 | 33 | } 34 | 35 | // Collect all section heading elements in an array 36 | var headings = document.querySelectorAll(headingLevels); 37 | 38 | // Add TOC title elements 39 | var tocHeadingDiv = document.createElement('div'); 40 | toc.appendChild(tocHeadingDiv); 41 | tocHeadingDiv.className = 'toc_title'; 42 | var tocHeading = document.createElement('h3'); 43 | toc.appendChild(tocHeading); 44 | tocHeading.className = 'ignoreLink'; 45 | tocHeading.id = 'toc'; 46 | var tocText = document.createTextNode('Table of Contents'); 47 | tocHeading.appendChild(tocText); 48 | 49 | // Add table and tbody 50 | var tocTable = document.createElement('table'); 51 | if (tocType == TocTypeEnum.VERTICAL) { 52 | tocTable.className = 'columns'; 53 | } 54 | toc.appendChild(tocTable); 55 | 56 | var tbody_element = document.createElement('tbody'); 57 | tbody_element.setAttribute('valign', 'top'); 58 | tbody_element.className = 'toc'; 59 | tocTable.appendChild(tbody_element); 60 | 61 | // Get the highest level heading 62 | var firstHeading = headings[0]; 63 | var masterLevel = parseInt(headingLevels.charAt(1)); 64 | 65 | // Get the lowest heading level 66 | var lowestLevel = parseInt(headingLevels.charAt(headingLevels - 1)); 67 | 68 | switch (tocType) { 69 | case TocTypeEnum.HORIZONTAL: 70 | CreateHorizontalTOC(headings, masterLevel, lowestLevel, tbody_element); 71 | break; 72 | case TocTypeEnum.VERTICAL: 73 | CreateVerticalTOC(headings, masterLevel, lowestLevel, tbody_element); 74 | break; 75 | default: 76 | } 77 | } 78 | 79 | function CreateHorizontalTOC( 80 | headings, masterLevel, lowestLevel, tbody_element) { 81 | 82 | // Initialize the header counter 83 | var h = 0; 84 | var ignoreChildren = false; 85 | 86 | while (h < headings.length) { 87 | // Get current heading 88 | var heading = headings[h]; 89 | 90 | // Get the current heading level 91 | var level = parseInt(heading.tagName.charAt(1)); 92 | 93 | if (isNaN(level) || level < 1 || level > lowestLevel) continue; 94 | 95 | // If level is a masterLevel, make it a TOC parent category 96 | if ((level == masterLevel) && (!hasClass(heading, 'ignoreLink'))) { 97 | toc_current_row = AddTOCMaster(tbody_element, heading); 98 | ignoreChildren = false; 99 | } 100 | 101 | if ((level == masterLevel) && (hasClass(heading, 'ignoreLink'))) { 102 | ignoreChildren = true; 103 | } 104 | 105 | if ((level != masterLevel) && (!ignoreChildren)) { 106 | AddTOCElements(toc_current_row, heading); 107 | } 108 | 109 | // Advance the header counter 110 | h++; 111 | } 112 | } 113 | 114 | // Adds a master Table of Content heading 115 | function AddTOCMaster(tocTable, heading) { 116 | 117 | // Add the table row scaffolding 118 | var toc_tr = document.createElement('tr'); 119 | tocTable.appendChild(toc_tr); 120 | toc_tr.setAttribute('valign', 'top'); 121 | var toc_tr_td = document.createElement('td'); 122 | toc_tr.appendChild(toc_tr_td); 123 | var toc_category = document.createElement('div'); 124 | toc_tr_td.appendChild(toc_category); 125 | toc_category.className = 'toc_category'; 126 | 127 | // Create the link to this header 128 | var link = document.createElement('a'); 129 | link.href = '#' + heading.id; // Create the anchor link 130 | link.textContent = heading.textContent; // Link text is same as heading 131 | toc_category.appendChild(link); 132 | 133 | // Add the container table cell for its children 134 | var toc_td = document.createElement('td'); 135 | toc_tr.appendChild(toc_td); 136 | var toc_td_div = document.createElement('div'); 137 | toc_td_div.className = 'toc_stylepoint'; 138 | toc_td.appendChild(toc_td_div); 139 | 140 | return (toc_td_div); 141 | } 142 | 143 | // Adds Table of Contents element to a master heading as children 144 | function AddTOCElements(toc_div, heading) { 145 | 146 | if (heading.offsetParent === null) { 147 | // The element is currently hidden, so don't create a TOC entry 148 | } else { 149 | // Create the list item element 150 | var toc_list_element = document.createElement('li'); 151 | toc_list_element.className = 'toc_entry'; 152 | toc_div.appendChild(toc_list_element); 153 | 154 | // Create the link to this header 155 | var link = document.createElement('a'); 156 | link.href = '#' + heading.id; // Create the anchor link 157 | link.textContent = heading.textContent; // Link text is same as heading 158 | toc_list_element.appendChild(link); 159 | } 160 | } 161 | 162 | function CreateVerticalTOC(headings, masterLevel, lowestLevel, tbody_element) { 163 | 164 | // Create the Column scaffolding 165 | var toc_tr = document.createElement('tr'); 166 | tbody_element.appendChild(toc_tr); 167 | var toc_tr_td = document.createElement('td'); 168 | toc_tr_td.className = 'two_columns'; 169 | toc_tr.appendChild(toc_tr_td); 170 | 171 | 172 | // Initialize the header counter and the current row 173 | var h = 0; 174 | var toc_current_col = null; 175 | var ignoreChildren = false; 176 | 177 | while (h < headings.length) { 178 | // Get current heading 179 | var heading = headings[h]; 180 | 181 | // Get the current heading level 182 | var level = parseInt(heading.tagName.charAt(1)); 183 | 184 | if (isNaN(level) || level < 1 || level > lowestLevel) continue; 185 | 186 | // If level is a masterLevel, make it a TOC parent category 187 | if ((level == masterLevel) && (!hasClass(heading, 'ignoreLink'))) { 188 | if (heading.offsetParent === null) { 189 | // The element is currently hidden, so don't create a TOC entry 190 | } else { 191 | var td_dl = document.createElement('dl'); 192 | toc_tr_td.appendChild(td_dl); 193 | var td_dt = document.createElement('dt'); 194 | td_dl.appendChild(td_dt); 195 | toc_current_col = td_dl; 196 | 197 | // Create the link to this header 198 | var link = document.createElement('a'); 199 | link.href = '#' + heading.id; // Create the anchor link 200 | link.textContent = heading.textContent; // Link text is same as heading 201 | td_dt.appendChild(link); 202 | ignoreChildren = false; 203 | } 204 | } 205 | 206 | // If level is a masterLevel but it's specified to ignore links, skip it 207 | // and its children. 208 | if ((level == masterLevel) && (hasClass(heading, 'ignoreLink'))) { 209 | ignoreChildren = true; 210 | } 211 | 212 | if ((level != masterLevel) && (!ignoreChildren)) { 213 | if (heading.offsetParent === null) { 214 | // The element is currently hidden, so don't create a TOC entry 215 | } else { 216 | var td_dd = document.createElement('dd'); 217 | toc_current_col.appendChild(td_dd); 218 | // Create the link to this header 219 | var link = document.createElement('a'); 220 | link.href = '#' + heading.id; // Create the anchor link 221 | link.textContent = heading.textContent; // Link text is same as heading 222 | td_dd.appendChild(link); 223 | } 224 | } 225 | 226 | // Advance the header counter 227 | h++; 228 | } 229 | } 230 | 231 | /* 232 | * Utility function for finding elements with a given 233 | * class. 234 | */ 235 | function hasClass(element, cls) { 236 | return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1; 237 | } 238 | 239 | /* 240 | * Linkify all h2 through h4 headers, except for those marked 241 | * "ignoreLink" 242 | */ 243 | 244 | // Add the link image to the element. 245 | function LinkifyHeader(header, fileName, sizePixels) { 246 | var link = document.createElement('a'); 247 | link.href = '#' + header.id; 248 | link.setAttribute('alt', 'link to ' + header.id); 249 | link.innerHTML = 250 | ''; 254 | header.appendChild(link); 255 | } 256 | 257 | // Find all elements of the given tag and linkify if 258 | // they don't have 'ignoreLink' in their class. 259 | function LinkifyHeadersForTag(tagName) { 260 | var headers = document.getElementsByTagName(tagName); 261 | var header; 262 | for (var j = 0; j != headers.length; j++) { 263 | header = headers[j]; 264 | if (!hasClass(header, 'ignoreLink') && ('id' in header)) { 265 | if (header.id != '') { 266 | LinkifyHeader(header, 'link.png', 21); 267 | header.style.left = '-46px'; 268 | header.style.position = 'relative'; 269 | } 270 | } 271 | } 272 | } 273 | 274 | // Linkify all h2, h3, and h4s. h1s are titles. 275 | function LinkifyHeaders() { 276 | LinkifyHeadersForTag('h2'); 277 | LinkifyHeadersForTag('h3'); 278 | LinkifyHeadersForTag('h4'); 279 | } 280 | 281 | /* 282 | * Initialize the style guide by showing all internal 283 | * elements and then linkifying the headers. 284 | */ 285 | 286 | function initStyleGuide() { 287 | LinkifyHeaders(); 288 | CreateTOC('tocDiv'); 289 | } 290 | -------------------------------------------------------------------------------- /javaguide.css: -------------------------------------------------------------------------------- 1 | table { 2 | border-collapse: collapse; 3 | } 4 | 5 | td, 6 | th { 7 | border: 1px solid #ccc; 8 | padding: 2px 12px; 9 | font-size: 10pt; 10 | } 11 | 12 | code, 13 | samp, 14 | var { 15 | color: #060; 16 | } 17 | 18 | pre { 19 | font-size: 10pt; 20 | display: block; 21 | color: #060; 22 | background-color: #e8fff6; 23 | border: 1px solid #f0fff0; 24 | border-left-width: 5px; 25 | padding: 4px 12px; 26 | } 27 | 28 | pre.badcode { 29 | color: #c00; 30 | background-color: #ffe6d8; 31 | border-color: #fff0f0; 32 | } 33 | 34 | hr { 35 | margin-top: 3.5em; 36 | border-width: 1px; 37 | color: #fff; 38 | } 39 | 40 | html { 41 | margin: 2em 10% 0; 42 | padding: 0; 43 | } 44 | 45 | .bp-reset-element, 46 | body, 47 | h1, 48 | h2, 49 | h3, 50 | h4, 51 | h5, 52 | h6, 53 | article, 54 | aside, 55 | details, 56 | figcaption, 57 | figure, 58 | footer, 59 | header, 60 | hgroup, 61 | menu, 62 | nav, 63 | section, 64 | summary, 65 | blockquote, 66 | q, 67 | th, 68 | td, 69 | caption, 70 | table, 71 | div, 72 | span, 73 | object, 74 | iframe, 75 | p, 76 | pre, 77 | a, 78 | abbr, 79 | acronym, 80 | address, 81 | code, 82 | del, 83 | dfn, 84 | em, 85 | img, 86 | dl, 87 | dt, 88 | dd, 89 | ol, 90 | ul, 91 | li, 92 | fieldset, 93 | form, 94 | label, 95 | legend, 96 | caption, 97 | tbody, 98 | tfoot, 99 | thead, 100 | tr { 101 | margin: 0; 102 | padding: 0; 103 | border: 0; 104 | font-weight: inherit; 105 | font-style: inherit; 106 | font-size: 100%; 107 | font-family: inherit; 108 | vertical-align: baseline; 109 | } 110 | 111 | body { 112 | font-family: 'Arial', sans-serif; 113 | font-size: 81.25%; 114 | color: #222; 115 | background-color: #fff; 116 | line-height: 1.67; 117 | overflow: auto; 118 | } 119 | 120 | .change { 121 | text-align: right; 122 | margin-bottom: 1em; 123 | } 124 | 125 | em { 126 | font-style: italic; 127 | } 128 | 129 | h1, 130 | h2, 131 | h3, 132 | h4, 133 | h5, 134 | h6 { 135 | font-weight: bold; 136 | } 137 | 138 | h1 { 139 | margin-bottom: 0.5em; 140 | text-align: center; 141 | } 142 | 143 | h2, 144 | h3, 145 | h4, 146 | h5, 147 | h6 { 148 | margin-top: 1.5em; 149 | margin-bottom: 0.75em; 150 | } 151 | 152 | h1 { 153 | font-size: 200%; 154 | } 155 | 156 | h2 { 157 | font-size: 167%; 158 | } 159 | 160 | h3 { 161 | font-size: 133%; 162 | } 163 | 164 | h4 { 165 | font-size: 120%; 166 | } 167 | 168 | h5 { 169 | font-size: 110%; 170 | } 171 | 172 | p { 173 | margin: 0 0 1.5em; 174 | } 175 | 176 | a[href=''] { 177 | cursor: default; 178 | } 179 | 180 | h1 img, 181 | h2 img, 182 | h3 img, 183 | h4 img, 184 | h5 img, 185 | h6 img { 186 | margin: 0; 187 | } 188 | 189 | a img { 190 | border: none; 191 | } 192 | 193 | pre { 194 | margin: 1.5em 0; 195 | white-space: pre; 196 | } 197 | 198 | pre, 199 | code, 200 | kbd, 201 | tt { 202 | font: 1em 'Droid Sans Mono', monospace; 203 | line-height: 1.5; 204 | } 205 | 206 | dl { 207 | margin: 0 0 1.5em; 208 | } 209 | 210 | dl dt { 211 | font-weight: bold; 212 | } 213 | 214 | dd { 215 | margin-left: 1.5em; 216 | } 217 | 218 | dd.toc3 { 219 | margin-left: 3em; 220 | } 221 | 222 | hr { 223 | height: 0; 224 | border: 0; 225 | border-top: 1px solid #ccc; 226 | background-color: #ccc; 227 | } 228 | 229 | table { 230 | border: 1px solid #bbb; 231 | border-spacing: 0; 232 | border-collapse: collapse; 233 | margin: 0 0 1.5em; 234 | vertical-align: middle; 235 | width: 100%; 236 | } 237 | 238 | table.unlined, 239 | table.unlined th, 240 | table.unlined tr, 241 | table.unlined td { 242 | border: 0; 243 | } 244 | 245 | th, 246 | td, 247 | caption { 248 | float: none !important; 249 | text-align: left; 250 | font-weight: normal; 251 | vertical-align: middle; 252 | padding: 4px; 253 | } 254 | 255 | caption { 256 | padding: 0; 257 | } 258 | 259 | td { 260 | border: 1px solid #bbb; 261 | vertical-align: top; 262 | } 263 | 264 | th { 265 | border: 0; 266 | border-bottom: 1px solid black; 267 | font-weight: bold; 268 | background: rgb(229, 236, 249); 269 | } 270 | 271 | table th code { 272 | background-color: inherit; 273 | color: inherit; 274 | } 275 | 276 | table tfoot th { 277 | border: 1px solid #bbb; 278 | } 279 | 280 | tfoot { 281 | font-style: italic; 282 | } 283 | 284 | caption { 285 | background: #eee; 286 | } 287 | 288 | table[border='0'] { 289 | border: none; 290 | } 291 | 292 | table[border='0'] > tbody > tr > td, 293 | table[border='0'] > tr > td { 294 | border: none; 295 | } 296 | 297 | tr.alt td, 298 | td.alt { 299 | background-color: #efefef; 300 | } 301 | 302 | table.striped tr:nth-child(even) td, 303 | table tr.even td { 304 | background: #efefef; 305 | } 306 | 307 | table.columns { 308 | border: none; 309 | } 310 | 311 | table.columns > tbody > tr > td, 312 | table.columns > tr > td { 313 | border: none; 314 | padding: 0 3em 0 0; 315 | } 316 | 317 | table.columns > tbody > tr > td:last-child, 318 | table.columns > tr > td:last-child { 319 | border: none; 320 | padding: 0; 321 | } 322 | 323 | ul, 324 | ol { 325 | margin: 0 1.5em 1.5em 0; 326 | padding-left: 2em; 327 | } 328 | 329 | li ul, 330 | li ol { 331 | margin: 0; 332 | } 333 | 334 | ul { 335 | list-style-type: disc; 336 | } 337 | 338 | ol { 339 | list-style-type: decimal; 340 | } 341 | 342 | ul { 343 | list-style-type: disc; 344 | } 345 | 346 | ul ul { 347 | list-style-type: circle; 348 | } 349 | 350 | ul ul ul { 351 | list-style-type: square; 352 | } 353 | 354 | ul.disc { 355 | list-style-type: disc; 356 | } 357 | 358 | ul.circle { 359 | list-style-type: circle; 360 | } 361 | 362 | ul.square { 363 | list-style-type: square; 364 | } 365 | 366 | ol { 367 | list-style-type: decimal; 368 | } 369 | 370 | ol ol { 371 | list-style-type: lower-alpha; 372 | } 373 | 374 | ol ol ol { 375 | list-style-type: lower-roman; 376 | } 377 | 378 | ol ul { 379 | list-style-type: circle; 380 | } 381 | 382 | ol.decimal { 383 | list-style-type: decimal; 384 | } 385 | 386 | ol.upper-alpha { 387 | list-style-type: upper-alpha; 388 | } 389 | 390 | ol.lower-alpha { 391 | list-style-type: lower-alpha; 392 | } 393 | 394 | ol.upper-roman { 395 | list-style-type: upper-roman; 396 | } 397 | 398 | ol.lower-roman { 399 | list-style-type: lower-roman; 400 | } 401 | 402 | ol.nolist, 403 | ul.nolist { 404 | padding-left: 0; 405 | list-style-image: none; 406 | list-style-type: none; 407 | margin-left: 0; 408 | } 409 | 410 | .center { 411 | text-align: center; 412 | } 413 | 414 | code, 415 | kbd, 416 | pre { 417 | color: #090; 418 | } 419 | 420 | kbd { 421 | font-weight: bold; 422 | } 423 | 424 | table.striped code { 425 | background-color: inherit; 426 | } 427 | 428 | pre { 429 | padding: 6px 10px; 430 | background-color: #fafafa; 431 | border: 1px solid #bbb; 432 | overflow: auto; 433 | } 434 | 435 | pre.prettyprint { 436 | padding: 6px 10px !important; 437 | border: 1px solid #bbb !important; 438 | } 439 | 440 | code.bad, 441 | code.badcode { 442 | color: magenta; 443 | } 444 | 445 | pre.bad, 446 | pre.badcode { 447 | background-color: #ffe6d8; 448 | border-top: 1px inset #a03; 449 | border-left: 1px inset #a03; 450 | } 451 | 452 | .tip { 453 | background-color: #fffbd9; 454 | padding: 6px 8px 6px 10px; 455 | border-left: 6px solid #ffef70; 456 | } 457 | 458 | .note { 459 | background-color: #e5ecf9; 460 | padding: 6px 8px 6px 10px; 461 | border-left: 6px solid #36c; 462 | } 463 | 464 | @media print { 465 | .str { 466 | color: #060; 467 | } 468 | 469 | .kwd { 470 | color: #006; 471 | font-weight: bold; 472 | } 473 | 474 | .com { 475 | color: #600; 476 | font-style: italic; 477 | } 478 | 479 | .typ { 480 | color: #404; 481 | font-weight: bold; 482 | } 483 | 484 | .lit { 485 | color: #044; 486 | } 487 | 488 | .pun, 489 | .opn, 490 | .clo { 491 | color: #440; 492 | } 493 | 494 | .pln { 495 | color: #000; 496 | } 497 | 498 | .tag { 499 | color: #006; 500 | font-weight: bold; 501 | } 502 | 503 | .atn { 504 | color: #404; 505 | } 506 | 507 | .atv { 508 | color: #060; 509 | } 510 | 511 | h1 { 512 | font-style: italic; 513 | } 514 | } 515 | 516 | ol.linenums { 517 | margin-top: 0; 518 | margin-bottom: 0; 519 | } 520 | 521 | code { 522 | background-color: #fafafa; 523 | padding: 0.25em 0.5em; 524 | white-space: nowrap; 525 | } 526 | 527 | /* TOC CSS */ 528 | 529 | table.columns { 530 | border: none; 531 | } 532 | 533 | td.two_columns { 534 | -webkit-column-count: 2; 535 | column-count: 2; 536 | } 537 | 538 | .toc_category { 539 | font-size: 10pt; 540 | padding-top: 1em; 541 | padding-bottom: 1em; 542 | border-left-width: 2px; 543 | border-right-width: 2px; 544 | border-color: grey; 545 | } 546 | 547 | .toc_stylepoint { 548 | font-size: 10pt; 549 | padding-top: 1em; 550 | padding-bottom: 1em; 551 | } 552 | 553 | li.toc_entry { 554 | padding-right: 1em; 555 | display: inline; 556 | list-style-type: none; 557 | } 558 | 559 | /* 560 | * This space is required to trigger the linewrap on the links 561 | * at href boundaries 562 | */ 563 | li.toc_entry::after { 564 | content: ' '; 565 | } 566 | 567 | li.toc_entry a { 568 | white-space: nowrap; 569 | } 570 | 571 | /* Horizontal TOC */ 572 | .toc td, 573 | .toc th { 574 | border-width: 1px 5px; 575 | overflow: hidden; 576 | } 577 | 578 | /* Vertical TOC */ 579 | 580 | .toc td.two_columns { 581 | border-width: 0; 582 | } 583 | 584 | /* Numbered sections */ 585 | 586 | h1 { 587 | counter-reset: h2; 588 | } 589 | 590 | h2.numbered { 591 | counter-reset: h3; 592 | } 593 | 594 | h3.numbered { 595 | counter-reset: h4; 596 | } 597 | 598 | h2.numbered::before { 599 | content: counter(h2) ' '; 600 | counter-increment: h2; 601 | } 602 | 603 | h3.numbered::before { 604 | content: counter(h2) '.' counter(h3) ' '; 605 | counter-increment: h3; 606 | } 607 | 608 | h4.numbered::before { 609 | content: counter(h2) '.' counter(h3) '.' counter(h4) ' '; 610 | counter-increment: h4; 611 | } 612 | -------------------------------------------------------------------------------- /javaguidelink.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/google/styleguide/1ab9120f856901f5cca56ca8947985628221b583/javaguidelink.png -------------------------------------------------------------------------------- /jsoncstyleguide.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Redirecting 8 | 9 | 15 | 16 | Redirecting you to jsoncstyleguide.xml. 17 | 18 | 19 | -------------------------------------------------------------------------------- /jsoncstyleguide_example_01.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/google/styleguide/1ab9120f856901f5cca56ca8947985628221b583/jsoncstyleguide_example_01.png -------------------------------------------------------------------------------- /jsoncstyleguide_example_02.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/google/styleguide/1ab9120f856901f5cca56ca8947985628221b583/jsoncstyleguide_example_02.png -------------------------------------------------------------------------------- /objcguide.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |

5 | The style guide has moved to 6 | objcguide.md 7 |

8 |
9 | -------------------------------------------------------------------------------- /pylintrc: -------------------------------------------------------------------------------- 1 | # This Pylint rcfile contains a best-effort configuration to uphold the 2 | # best-practices and style described in the Google Python style guide: 3 | # https://google.github.io/styleguide/pyguide.html 4 | # 5 | # Its canonical open-source location is: 6 | # https://google.github.io/styleguide/pylintrc 7 | 8 | # Copyright 2018 Google LLC 9 | # 10 | # Licensed under the Apache License, Version 2.0 (the "License"); 11 | # you may not use this file except in compliance with the License. 12 | # You may obtain a copy of the License at 13 | # 14 | # http://www.apache.org/licenses/LICENSE-2.0 15 | # 16 | # Unless required by applicable law or agreed to in writing, software 17 | # distributed under the License is distributed on an "AS IS" BASIS, 18 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 19 | # See the License for the specific language governing permissions and 20 | # limitations under the License. 21 | 22 | [MAIN] 23 | 24 | # Files or directories to be skipped. They should be base names, not paths. 25 | ignore=third_party 26 | 27 | # Files or directories matching the regex patterns are skipped. The regex 28 | # matches against base names, not paths. 29 | ignore-patterns= 30 | 31 | # Pickle collected data for later comparisons. 32 | persistent=no 33 | 34 | # List of plugins (as comma separated values of python modules names) to load, 35 | # usually to register additional checkers. 36 | load-plugins= 37 | 38 | # Use multiple processes to speed up Pylint. 39 | jobs=4 40 | 41 | # Allow loading of arbitrary C extensions. Extensions are imported into the 42 | # active Python interpreter and may run arbitrary code. 43 | unsafe-load-any-extension=no 44 | 45 | 46 | [MESSAGES CONTROL] 47 | 48 | # Only show warnings with the listed confidence levels. Leave empty to show 49 | # all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED 50 | confidence= 51 | 52 | # Enable the message, report, category or checker with the given id(s). You can 53 | # either give multiple identifier separated by comma (,) or put this option 54 | # multiple time (only on the command line, not in the configuration file where 55 | # it should appear only once). See also the "--disable" option for examples. 56 | #enable= 57 | 58 | # Disable the message, report, category or checker with the given id(s). You 59 | # can either give multiple identifiers separated by comma (,) or put this 60 | # option multiple times (only on the command line, not in the configuration 61 | # file where it should appear only once).You can also use "--disable=all" to 62 | # disable everything first and then reenable specific checks. For example, if 63 | # you want to run only the similarities checker, you can use "--disable=all 64 | # --enable=similarities". If you want to run only the classes checker, but have 65 | # no Warning level messages displayed, use"--disable=all --enable=classes 66 | # --disable=W" 67 | disable=R, 68 | abstract-method, 69 | apply-builtin, 70 | arguments-differ, 71 | attribute-defined-outside-init, 72 | backtick, 73 | bad-option-value, 74 | basestring-builtin, 75 | buffer-builtin, 76 | c-extension-no-member, 77 | consider-using-enumerate, 78 | cmp-builtin, 79 | cmp-method, 80 | coerce-builtin, 81 | coerce-method, 82 | delslice-method, 83 | div-method, 84 | eq-without-hash, 85 | execfile-builtin, 86 | file-builtin, 87 | filter-builtin-not-iterating, 88 | fixme, 89 | getslice-method, 90 | global-statement, 91 | hex-method, 92 | idiv-method, 93 | implicit-str-concat, 94 | import-error, 95 | import-self, 96 | import-star-module-level, 97 | input-builtin, 98 | intern-builtin, 99 | invalid-str-codec, 100 | locally-disabled, 101 | long-builtin, 102 | long-suffix, 103 | map-builtin-not-iterating, 104 | misplaced-comparison-constant, 105 | missing-function-docstring, 106 | metaclass-assignment, 107 | next-method-called, 108 | next-method-defined, 109 | no-absolute-import, 110 | no-init, # added 111 | no-member, 112 | no-name-in-module, 113 | no-self-use, 114 | nonzero-method, 115 | oct-method, 116 | old-division, 117 | old-ne-operator, 118 | old-octal-literal, 119 | old-raise-syntax, 120 | parameter-unpacking, 121 | print-statement, 122 | raising-string, 123 | range-builtin-not-iterating, 124 | raw_input-builtin, 125 | rdiv-method, 126 | reduce-builtin, 127 | relative-import, 128 | reload-builtin, 129 | round-builtin, 130 | setslice-method, 131 | signature-differs, 132 | standarderror-builtin, 133 | suppressed-message, 134 | sys-max-int, 135 | trailing-newlines, 136 | unichr-builtin, 137 | unicode-builtin, 138 | unnecessary-pass, 139 | unpacking-in-except, 140 | useless-else-on-loop, 141 | useless-suppression, 142 | using-cmp-argument, 143 | wrong-import-order, 144 | xrange-builtin, 145 | zip-builtin-not-iterating, 146 | 147 | 148 | [REPORTS] 149 | 150 | # Set the output format. Available formats are text, parseable, colorized, msvs 151 | # (visual studio) and html. You can also give a reporter class, eg 152 | # mypackage.mymodule.MyReporterClass. 153 | output-format=text 154 | 155 | # Tells whether to display a full report or only the messages 156 | reports=no 157 | 158 | # Activate the evaluation score. 159 | score=no 160 | 161 | # Python expression which should return a note less than 10 (10 is the highest 162 | # note). You have access to the variables errors warning, statement which 163 | # respectively contain the number of errors / warnings messages and the total 164 | # number of statements analyzed. This is used by the global evaluation report 165 | # (RP0004). 166 | evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) 167 | 168 | # Template used to display messages. This is a python new-style format string 169 | # used to format the message information. See doc for all details 170 | #msg-template= 171 | 172 | 173 | [BASIC] 174 | 175 | # Good variable names which should always be accepted, separated by a comma 176 | good-names=main,_ 177 | 178 | # Bad variable names which should always be refused, separated by a comma 179 | bad-names= 180 | 181 | # Colon-delimited sets of names that determine each other's naming style when 182 | # the name regexes allow several styles. 183 | name-group= 184 | 185 | # Include a hint for the correct naming format with invalid-name 186 | include-naming-hint=no 187 | 188 | # List of decorators that produce properties, such as abc.abstractproperty. Add 189 | # to this list to register other decorators that produce valid properties. 190 | property-classes=abc.abstractproperty,cached_property.cached_property,cached_property.threaded_cached_property,cached_property.cached_property_with_ttl,cached_property.threaded_cached_property_with_ttl 191 | 192 | # Regular expression matching correct function names 193 | function-rgx=^(?:(?PsetUp|tearDown|setUpModule|tearDownModule)|(?P_?[A-Z][a-zA-Z0-9]*)|(?P_?[a-z][a-z0-9_]*))$ 194 | 195 | # Regular expression matching correct variable names 196 | variable-rgx=^[a-z][a-z0-9_]*$ 197 | 198 | # Regular expression matching correct constant names 199 | const-rgx=^(_?[A-Z][A-Z0-9_]*|__[a-z0-9_]+__|_?[a-z][a-z0-9_]*)$ 200 | 201 | # Regular expression matching correct attribute names 202 | attr-rgx=^_{0,2}[a-z][a-z0-9_]*$ 203 | 204 | # Regular expression matching correct argument names 205 | argument-rgx=^[a-z][a-z0-9_]*$ 206 | 207 | # Regular expression matching correct class attribute names 208 | class-attribute-rgx=^(_?[A-Z][A-Z0-9_]*|__[a-z0-9_]+__|_?[a-z][a-z0-9_]*)$ 209 | 210 | # Regular expression matching correct inline iteration names 211 | inlinevar-rgx=^[a-z][a-z0-9_]*$ 212 | 213 | # Regular expression matching correct class names 214 | class-rgx=^_?[A-Z][a-zA-Z0-9]*$ 215 | 216 | # Regular expression matching correct module names 217 | module-rgx=^(_?[a-z][a-z0-9_]*|__init__)$ 218 | 219 | # Regular expression matching correct method names 220 | method-rgx=(?x)^(?:(?P_[a-z0-9_]+__|runTest|setUp|tearDown|setUpTestCase|tearDownTestCase|setupSelf|tearDownClass|setUpClass|(test|assert)_*[A-Z0-9][a-zA-Z0-9_]*|next)|(?P_{0,2}[A-Z][a-zA-Z0-9_]*)|(?P_{0,2}[a-z][a-z0-9_]*))$ 221 | 222 | # Regular expression which should only match function or class names that do 223 | # not require a docstring. 224 | no-docstring-rgx=(__.*__|main|test.*|.*test|.*Test)$ 225 | 226 | # Minimum line length for functions/classes that require docstrings, shorter 227 | # ones are exempt. 228 | docstring-min-length=12 229 | 230 | 231 | [TYPECHECK] 232 | 233 | # List of decorators that produce context managers, such as 234 | # contextlib.contextmanager. Add to this list to register other decorators that 235 | # produce valid context managers. 236 | contextmanager-decorators=contextlib.contextmanager,contextlib2.contextmanager 237 | 238 | # List of module names for which member attributes should not be checked 239 | # (useful for modules/projects where namespaces are manipulated during runtime 240 | # and thus existing member attributes cannot be deduced by static analysis. It 241 | # supports qualified module names, as well as Unix pattern matching. 242 | ignored-modules= 243 | 244 | # List of class names for which member attributes should not be checked (useful 245 | # for classes with dynamically set attributes). This supports the use of 246 | # qualified names. 247 | ignored-classes=optparse.Values,thread._local,_thread._local 248 | 249 | # List of members which are set dynamically and missed by pylint inference 250 | # system, and so shouldn't trigger E1101 when accessed. Python regular 251 | # expressions are accepted. 252 | generated-members= 253 | 254 | 255 | [FORMAT] 256 | 257 | # Maximum number of characters on a single line. 258 | max-line-length=80 259 | 260 | # TODO(https://github.com/pylint-dev/pylint/issues/3352): Direct pylint to exempt 261 | # lines made too long by directives to pytype. 262 | 263 | # Regexp for a line that is allowed to be longer than the limit. 264 | ignore-long-lines=(?x)( 265 | ^\s*(\#\ )??$| 266 | ^\s*(from\s+\S+\s+)?import\s+.+$) 267 | 268 | # Allow the body of an if to be on the same line as the test if there is no 269 | # else. 270 | single-line-if-stmt=yes 271 | 272 | # Maximum number of lines in a module 273 | max-module-lines=99999 274 | 275 | # String used as indentation unit. The internal Google style guide mandates 2 276 | # spaces. Google's externaly-published style guide says 4, consistent with 277 | # PEP 8. 278 | indent-string=' ' 279 | 280 | # Number of spaces of indent required inside a hanging or continued line. 281 | indent-after-paren=4 282 | 283 | # Expected format of line ending, e.g. empty (any line ending), LF or CRLF. 284 | expected-line-ending-format= 285 | 286 | 287 | [MISCELLANEOUS] 288 | 289 | # List of note tags to take in consideration, separated by a comma. 290 | notes=TODO 291 | 292 | 293 | [STRING] 294 | 295 | # This flag controls whether inconsistent-quotes generates a warning when the 296 | # character used as a quote delimiter is used inconsistently within a module. 297 | check-quote-consistency=yes 298 | 299 | 300 | [VARIABLES] 301 | 302 | # Tells whether we should check for unused import in __init__ files. 303 | init-import=no 304 | 305 | # A regular expression matching the name of dummy variables (i.e. expectedly 306 | # not used). 307 | dummy-variables-rgx=^\*{0,2}(_$|unused_|dummy_) 308 | 309 | # List of additional names supposed to be defined in builtins. Remember that 310 | # you should avoid to define new builtins when possible. 311 | additional-builtins= 312 | 313 | # List of strings which can identify a callback function by name. A callback 314 | # name must start or end with one of those strings. 315 | callbacks=cb_,_cb 316 | 317 | # List of qualified module names which can have objects that can redefine 318 | # builtins. 319 | redefining-builtins-modules=six,six.moves,past.builtins,future.builtins,functools 320 | 321 | 322 | [LOGGING] 323 | 324 | # Logging modules to check that the string format arguments are in logging 325 | # function parameter format 326 | logging-modules=logging,absl.logging,tensorflow.io.logging 327 | 328 | 329 | [SIMILARITIES] 330 | 331 | # Minimum lines number of a similarity. 332 | min-similarity-lines=4 333 | 334 | # Ignore comments when computing similarities. 335 | ignore-comments=yes 336 | 337 | # Ignore docstrings when computing similarities. 338 | ignore-docstrings=yes 339 | 340 | # Ignore imports when computing similarities. 341 | ignore-imports=no 342 | 343 | 344 | [SPELLING] 345 | 346 | # Spelling dictionary name. Available dictionaries: none. To make it working 347 | # install python-enchant package. 348 | spelling-dict= 349 | 350 | # List of comma separated words that should not be checked. 351 | spelling-ignore-words= 352 | 353 | # A path to a file that contains private dictionary; one word per line. 354 | spelling-private-dict-file= 355 | 356 | # Tells whether to store unknown words to indicated private dictionary in 357 | # --spelling-private-dict-file option instead of raising a message. 358 | spelling-store-unknown-words=no 359 | 360 | 361 | [IMPORTS] 362 | 363 | # Deprecated modules which should not be used, separated by a comma 364 | deprecated-modules=regsub, 365 | TERMIOS, 366 | Bastion, 367 | rexec, 368 | sets 369 | 370 | # Create a graph of every (i.e. internal and external) dependencies in the 371 | # given file (report RP0402 must not be disabled) 372 | import-graph= 373 | 374 | # Create a graph of external dependencies in the given file (report RP0402 must 375 | # not be disabled) 376 | ext-import-graph= 377 | 378 | # Create a graph of internal dependencies in the given file (report RP0402 must 379 | # not be disabled) 380 | int-import-graph= 381 | 382 | # Force import order to recognize a module as part of the standard 383 | # compatibility libraries. 384 | known-standard-library= 385 | 386 | # Force import order to recognize a module as part of a third party library. 387 | known-third-party=enchant, absl 388 | 389 | # Analyse import fallback blocks. This can be used to support both Python 2 and 390 | # 3 compatible code, which means that the block might have code that exists 391 | # only in one or another interpreter, leading to false positives when analysed. 392 | analyse-fallback-blocks=no 393 | 394 | 395 | [CLASSES] 396 | 397 | # List of method names used to declare (i.e. assign) instance attributes. 398 | defining-attr-methods=__init__, 399 | __new__, 400 | setUp 401 | 402 | # List of member names, which should be excluded from the protected access 403 | # warning. 404 | exclude-protected=_asdict, 405 | _fields, 406 | _replace, 407 | _source, 408 | _make 409 | 410 | # List of valid names for the first argument in a class method. 411 | valid-classmethod-first-arg=cls, 412 | class_ 413 | 414 | # List of valid names for the first argument in a metaclass class method. 415 | valid-metaclass-classmethod-first-arg=mcs 416 | -------------------------------------------------------------------------------- /shell.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | The guide has been moved to shellguide.html. 6 | 7 | 8 | -------------------------------------------------------------------------------- /shell.xsl: -------------------------------------------------------------------------------- 1 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | <xsl:value-of select="@title"/> 25 | 26 | 27 | 28 | 30 | 32 | 33 | 160 | 161 | 162 |

163 | 164 | 165 | 166 |
167 | 168 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 |
178 | 179 | -------------------------------------------------------------------------------- /styleguide.css: -------------------------------------------------------------------------------- 1 | body { 2 | background-color: #fff; 3 | color: #333; 4 | font-family: sans-serif; 5 | font-size: 10pt; 6 | margin-right: 100px; 7 | margin-left: 100px; 8 | } 9 | 10 | h1, 11 | h2, 12 | h3, 13 | h4, 14 | h5, 15 | h6, 16 | .toc_title { 17 | color: #06c; 18 | margin-top: 2em; 19 | margin-bottom: 1em; 20 | } 21 | 22 | h1 { 23 | text-align: center; 24 | font-size: 18pt; 25 | } 26 | 27 | h2, 28 | .toc_title { 29 | font-weight: bold; 30 | font-size: 12pt; 31 | margin-left: -40px; 32 | } 33 | 34 | h3, 35 | h4, 36 | h5, 37 | h6 { 38 | font-size: 10pt; 39 | margin-left: -20px; 40 | } 41 | 42 | .toc_category, 43 | .toc_stylepoint { 44 | font-size: 10pt; 45 | padding-top: 0.3em; 46 | padding-bottom: 0.3em; 47 | } 48 | 49 | table { 50 | border-collapse: collapse; 51 | } 52 | 53 | td, 54 | th { 55 | border: 1px solid #ccc; 56 | padding: 2px 12px; 57 | font-size: 10pt; 58 | } 59 | 60 | .toc td, 61 | .toc th { 62 | border-width: 1px 5px; 63 | } 64 | 65 | code, 66 | samp, 67 | var { 68 | color: #060; 69 | } 70 | 71 | pre { 72 | font-size: 10pt; 73 | display: block; 74 | color: #060; 75 | background-color: #f8fff8; 76 | border: 1px solid #f0fff0; 77 | border-left-width: 5px; 78 | padding: 4px 12px; 79 | } 80 | 81 | pre.badcode { 82 | color: #c00; 83 | background-color: #fff8f8; 84 | border-color: #fff0f0; 85 | } 86 | 87 | .showhide_button { 88 | float: left; 89 | cursor: pointer; 90 | border: 1px solid; 91 | border-color: #ddd #aaa #aaa #ddd; 92 | padding: 0 3px 1px; 93 | margin: 0 4px 8px 0; 94 | border-radius: 3px; 95 | -webkit-border-radius: 3px; 96 | -moz-border-radius: 3px; 97 | } 98 | 99 | .link_button { 100 | float: left; 101 | display: none; 102 | background-color: #f8f8ff; 103 | border: 1px solid #f0f0ff; 104 | font-size: 75%; 105 | margin-top: 0; 106 | margin-left: -50px; 107 | padding: 4px; 108 | border-radius: 3px; 109 | -webkit-border-radius: 3px; 110 | -moz-border-radius: 3px; 111 | } 112 | 113 | address { 114 | text-align: right; 115 | } 116 | 117 | hr { 118 | margin-top: 3.5em; 119 | border-width: 1px; 120 | color: #fff; 121 | } 122 | 123 | .stylepoint_section { 124 | display: block; 125 | margin-bottom: 1em; 126 | color: #58f; 127 | font-family: sans-serif; 128 | font-size: 90%; 129 | font-weight: bold; 130 | margin-left: -2%; 131 | } 132 | 133 | .stylepoint_subsection { 134 | color: #679; 135 | font-family: sans-serif; 136 | font-size: 90%; 137 | font-weight: bold; 138 | margin-left: -1%; 139 | } 140 | 141 | .stylepoint_subsubsection { 142 | color: #679; 143 | font-family: sans-serif; 144 | font-size: 80%; 145 | font-weight: bold; 146 | margin-left: 0; 147 | } 148 | 149 | .revision { 150 | text-align: right; 151 | } 152 | -------------------------------------------------------------------------------- /vimscriptguide.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |

5 | 6 | Revision 1.1 7 |

8 | 9 | 10 |
11 | Nate Soares
12 | Artemis Sparks
13 | David Barnett
14 |
15 | 16 | 17 | 18 |

19 | This is a casual version of the vimscript style guide, because 20 | vimscript is a casual language. When submitting vim plugin code, you 21 | must adhere to these rules. For clarifications, justifications, and 22 | explanations about the finer points of vimscript, please refer to the 23 | heavy guide. 24 |

25 |
26 |
27 | 28 | 29 |

30 | It's hard to get vimscript right. Many commands depend upon the user's 31 | settings. By following these guidelines, you can hope to make your 32 | scripts portable. 33 |

34 | 35 | Prefer single quoted strings 36 | 37 |

38 | Double quoted strings are semantically different in vimscript, and 39 | you probably don't want them (they break regexes). 40 |

41 |

42 | Use double quoted strings when you need an escape sequence (such as 43 | "\n") or if you know it doesn't matter and you need to 44 | embed single quotes. 45 |

46 | 47 |
48 | 49 | 50 | Use the =~# or =~? operator families over the 51 | =~ family. 52 | 53 | 54 |

55 | The matching behavior depends upon the user's ignorecase and smartcase 56 | settings and on whether you compare them with the =~, 57 | =~#, or =~? family of operators. Use the 58 | =~# and =~? operator families explicitly 59 | when comparing strings unless you explicitly need to honor the user's 60 | case sensitivity settings. 61 |

62 | 63 |
64 | 65 | Prefix all regexes with \m\C. 66 | 67 |

68 | In addition to the case sensitivity settings, regex behavior depends 69 | upon the user's nomagic setting. To make regexes act like nomagic and 70 | noignorecase are set, prepend all regexes with \m\C. 71 |

72 |

73 | You are welcome to use other magic levels (\v) and case 74 | sensitivities (\c) so long as they are intentional and 75 | explicit. 76 |

77 | 78 |
79 | 80 | Avoid commands with unintended side effects. 81 | 82 |

83 | Avoid using :s[ubstitute] as it moves the cursor and 84 | prints error messages. Prefer functions (such as 85 | search()) better suited to scripts. 86 |

87 |

88 | For many vim commands, functions exist that do the same thing with 89 | fewer side effects. See :help functions() for a list of 90 | built-in functions. 91 |

92 | 93 |
94 | 95 | Avoid commands that rely on user settings. 96 | 97 |

98 | Always use normal! instead of normal. The 99 | latter depends upon the user's key mappings and could do anything. 100 |

101 |

102 | Avoid :s[ubstitute], as its behavior depends upon a 103 | number of local settings. 104 |

105 |

106 | The same applies to other commands not listed here. 107 |

108 | 109 |
110 | 111 | Match error codes, not error text. 112 | 113 |

Error text may be locale dependent.

114 | 115 |
116 |
117 | 118 | 119 | 120 | 121 | 122 | Message the user infrequently. 123 | 124 |

125 | Loud scripts are annoying. Message the user only when: 126 |

    127 |
  • A long-running process has kicked off.
  • 128 |
  • An error has occurred.
  • 129 |
130 |

131 | 132 |
133 | 134 | Use strict and explicit checks where possible. 135 | 136 |

137 | Vimscript has unsafe, unintuitive behavior when dealing with some 138 | types. For instance, 0 == 'foo' evaluates to true. 139 |

140 |

141 | Use strict comparison operators where possible. When comparing against 142 | a string literal, use the is# operator. Otherwise, prefer 143 | maktaba#value#IsEqual or check type() 144 | explicitly. 145 |

146 |

147 | Check variable types explicitly before using them. Use functions from 148 | maktaba#ensure, or check maktaba#value or 149 | type() and throw your own errors. 150 |

151 |

152 | Use :unlet for variables that may change types, 153 | particularly those assigned inside loops. 154 |

155 | 156 |
157 | 158 | Use sparingly. 159 | 160 |

161 | Use python only when it provides critical functionality, for example 162 | when writing threaded code. 163 |

164 | 165 |
166 | 167 | Use vimscript instead. 168 | 169 |

170 | Avoid using other scripting languages such as ruby and lua. We can 171 | not guarantee that the end user's vim has been compiled with support 172 | for non-vimscript languages. 173 |

174 | 175 |
176 | 177 | 178 | Use maktaba. 179 | 180 | 181 |

182 | maktaba removes boilerplate, including: 183 |

    184 |
  • Plugin creation
  • 185 |
  • Error handling
  • 186 |
  • Dependency checking
  • 187 |
188 |

189 | 190 |
191 | 192 | Organize functionality into modular plugins 193 | 194 |

195 | Group your functionality as a plugin, unified in one directory (or 196 | code repository) which shares your plugin's name (with a "vim-" prefix 197 | or ".vim" suffix if desired). It should be split into plugin/, 198 | autoload/, etc. subdirectories as necessary, and it should declare 199 | metadata in the addon-info.json format (see the 200 | VAM documentation for details). 201 |

202 | 203 |
204 | 205 | 206 | In the autoload/ directory, defined with [!] and 207 | [abort]. 208 | 209 | 210 |

211 | Autoloading allows functions to be loaded on demand, which makes 212 | startuptime faster and enforces function namespacing. 213 |

214 |

215 | Script-local functions are welcome, but should also live in autoload/ 216 | and be called by autoloaded functions. 217 |

218 |

219 | Non-library plugins should expose commands instead of functions. 220 | Command logic should be extracted into functions and autoloaded. 221 |

222 |

223 | [!] allows developers to reload their functions 224 | without complaint. 225 |

226 |

227 | [abort] forces the function to halt when it encounters 228 | an error. 229 |

230 | 231 |
232 | 233 | 234 | In the plugin/commands.vim or under the ftplugin/ directory, defined 235 | without [!]. 236 | 237 | 238 |

239 | General commands go in plugin/commands.vim. 240 | Filetype-specific commands go in ftplugin/. 241 |

242 |

243 | Excluding [!] prevents your plugin from silently 244 | clobbering existing commands. Command conflicts should be resolved by 245 | the user. 246 |

247 | 248 |
249 | 250 | 251 | Place them in plugin/autocmds.vim, within augroups. 252 | 253 | 254 |

255 | Place all autocommands in augroups. 256 |

257 |

258 | The augroup name should be unique. It should either be, or be prefixed 259 | with, the plugin name. 260 |

261 |

262 | Clear the augroup with autocmd! before defining new 263 | autocommands in the augroup. This makes your plugin re-entrable. 264 |

265 | 266 |
267 | 268 | 269 | Place them in plugin/mappings.vim, using 270 | maktaba#plugin#MapPrefix to get a prefix. 271 | 272 | 273 |

274 | All key mappings should be defined in 275 | plugin/mappings.vim. 276 |

277 |

278 | Partial mappings (see :help using-<Plug>.) should be defined in 279 | plugin/plugs.vim. 280 |

281 | 282 |
283 | 284 | Change settings locally 285 | 286 |

287 | Use :setlocal and &l: instead of 288 | :set and & unless you have explicit 289 | reason to do otherwise. 290 |

291 | 292 |
293 |
294 | 295 | 296 |

297 | Follow google style conventions. When in doubt, treat vimscript style 298 | like python style. 299 |

300 | 301 | 302 | 303 | Similar to python. 304 | 305 |
306 |
307 |
308 | 309 |
    310 |
  • Use two spaces for indents
  • 311 |
  • Do not use tabs
  • 312 |
  • Use spaces around operators 313 |

    This does not apply to arguments to commands.

    314 | 315 | let s:variable = "concatenated " . "strings" 316 | command -range=% MyCommand 317 | 318 |
  • 319 |
  • Do not introduce trailing whitespace 320 |

    You need not go out of your way to remove it.

    321 |

    322 | Trailing whitespace is allowed in mappings which prep commands 323 | for user input, such as 324 | "noremap <leader>gf :grep -f ". 325 |

    326 |
  • 327 |
  • Restrict lines to 80 columns wide
  • 328 |
  • Indent continued lines by four spaces
  • 329 |
  • Do not align arguments of commands 330 | 331 | command -bang MyCommand call myplugin#foo() 332 | command MyCommand2 call myplugin#bar() 333 | 334 | 335 | command -bang MyCommand call myplugin#foo() 336 | command MyCommand2 call myplugin#bar() 337 | 338 |
  • 339 |
340 | 341 |
342 | 343 | 344 | 345 |

346 | In general, use 347 | plugin-names-like-this, 348 | FunctionNamesLikeThis, 349 | CommandNamesLikeThis, 350 | augroup_names_like_this, 351 | variable_names_like_this. 352 |

353 |

Always prefix variables with their scope.

354 |
355 | 356 | 357 |

Keep them short and sweet.

358 | 359 |
360 | 361 |

Prefix script-local functions with s:

362 |

Autoloaded functions may not have a scope prefix.

363 |

364 | Do not create global functions. Use autoloaded functions 365 | instead. 366 |

367 |
368 | 369 |

Prefer succinct command names over common command prefixes.

370 |
371 | 372 |

Augroup names count as variables for naming purposes.

373 |
374 | 375 |
    376 |
  • Global variables with g:
  • 377 |
  • Script-local variables with s:
  • 378 |
  • Function arguments with a:
  • 379 |
  • Function-local variables with l:
  • 380 |
  • Vim-predefined variables with v:
  • 381 |
  • Buffer-local variables with b:
  • 382 |
383 |

384 | g:, s:, and a: must always 385 | be used. 386 |

387 |

388 | b: changes the variable semantics; use it when you 389 | want buffer-local semantics. 390 |

391 |

392 | l: and v: should be used for consistency, 393 | future proofing, and to avoid subtle bugs. They are not strictly 394 | required. Add them in new code but don’t go out of your way to add 395 | them elsewhere. 396 |

397 |
398 | 399 |
400 |
401 | 402 |

403 | Revision 1.1 404 |

405 | 406 | 407 |
408 | Nate Soares
409 | Artemis Sparks
410 | David Barnett
411 |
412 |
413 | --------------------------------------------------------------------------------