Total Pageviews

Showing posts with label atom. Show all posts
Showing posts with label atom. Show all posts

Saturday, 20 April 2024

将 Atom 改造为一个简单的 C/C++ IDE

 如果你符合以下这些特点,这篇文章会很有用:

  • 单纯喜欢 Atom 的人
  • 单纯觉得 VS 难用的人
  • 有洁癖,不愿使用闭源软件的人
  • 讨厌微软的人
  • 喜欢折腾的人(其实折腾 Atom 也不是非常难)

当然,即使你不属于上面这几类人,也应该体验一下使用 Atom 的感觉,因为只有对比过后才能知道哪个更适合自己。

最近在学校修 cpp 课程,授课老师要求用 VS,然而我翻了一下教材,发现其实没有用 VS 的必要,所以准备把我一直在用的 Atom 改造为一个 cpp 的 IDE。

成品可以实现 C/C++ 程序的实时检查代码中的错误,可以一键编译,还可以和 VS 一样用图形化界面打断点、逐行运行来 Debug。

Atom 有如下几个有点,让它比 VS 高到不知道哪里去:

  • 开源,且跨平台,这意味着如果你是一个使用 Atom 的 Linuxer,在某些情况下被迫要用 Windows,你可以很简单地打包一份相同配置的 Windows 版 Atom,即插即用
  • 高度可定制化,每个人的 Atom 都可以完全不一样
  • 原生高度集成图形化的 Git
  • 基于 Electron,运用了大量 Web 技术,原生对前端编写的支持优秀
  • 极度模块化,真正的 Atom 只是一个用来实现插件功能的核心,没有任何功能,全部功能都是由插件提供的
  • 庞大的社区,数不胜数的插件,与上一条搭配意味着 Atom 的改造难度极低,这让 Atom 可以轻松充当多面手,不只前端,C 家族、Python 等众多语言的 IDE 也可胜任,同时它还是一个优秀的 Markdown 编辑器。
  • 自从某次更新后,Atom 的运行速度有了很大的改善。到现在,Atom 已经是一个轻快的编辑器了。

什么?你说 VS Code?那不就是微软给 Atom 披了个马甲吗?

准备原材料

即使不考虑 Atom,想要编译、Debug C/C++ 程序,首选也一定是 gcc、g++ 和 gdb,所以我们要做的就是把 Atom 和上面三个程序结合起来,结合的媒介就是 Atom 的插件。

安装 Atom

对于 Unix-Like 系统,一般发行版的仓库都会有 atom,就算没有,也可以去项目的 Releases 页下载对应版本,甚至可以直接下载打包好的压缩包,解压后运行主程序文件。

对于 Windows,你可以选择去项目的 Releases 页下载对应的 exe 安装包,但安装过程中你无法选择安装路径,所以我一般会下载 zip 包直接解压使用。

安装 gcc、g++ 和 gdb

对于 Unix-Like,不用多说,大家都会。

对于 Windows,这里要用到 MinGW,这是一个 Windows 下 GNU 家软件的安装器,使用起来非常方便。我们需要的是 mingw32-gcc-bin、mingw32-gcc-g++-bin 和 mingw32-gdb-bin 这三个软件包,其它依赖会自动下载。 MinGW 的食用方法网上一搜一大把,我就不在赘述了。 注意 MinGW 只提供 32 位版的软件包,如果你有什么特殊需求或者是强迫症必须要 64 位版本的软件,可以使用 Mingw-w64,道理都是一样的。

在安装过 gcc、g++、gdb 后,需要将 MinGW 安装目录下的 bin 文件夹(里面有一大堆可执行文件)添加到 Windows 的环境变量 PATH 中。环境变量的添加方法网上也有一大堆,不再重复。 添加到 PATH 后需要重启 Windows 以使做过的更改生效。

安装插件

下面的步骤都是所有平台通用的。

进入 Atom 的设置,进入插件查找安装选项卡,装上以下几个插件:

  • linter
  • linter-gcc2(原版 linter-gcc 停止开发了,这是另一位开发者接手后的版本)
  • gcc-make-run
  • dbg
  • dbg-gdb

确保以上插件全部安装成功后重启 Atom,会弹出一些窗口让你安装这些插件的依赖,全部安装即可。

设置插件

打开插件管理面板,这里能看到你安装过的所有插件。

首先是 linter-gcc2 插件 需要在它的设置中打开 Lint on-the-fly,这是实时查错功能。

之后是 gcc-make-run 需要在它的设置中的编译参数(Compiler Flags)里增加-g参数,以使 gdb 可以正常 debug 编译好的 binary 文件。

在这里,对于 Linux 用户还有一步额外的操作。在 Linux 下,gcc-make-run 默认调用的终端是 xterm。我相信很大一部分 Linuxer 们都没有装这个又老又丑的终端,即使装了也大概率是因为某些依赖问题,不会日常使用。所以我们需要修改默认调用的终端。 gcc-make-run 插件设置中的最后一项 Terminal Start Command (only Linux platform) 就是自定义终端调用命令,你可以查看你使用的终端的帮助或者问问“好男人” (man) 来自行设置调用命令。注意要用 bash 的 -c 参数来使程序执行完后终端保持打开状态。 举个例子,我用的是 xfce4-terminal:xfce4-terminal -T $title -x bash -c


以上就是改造的步骤,下面说一说如何使用。

快捷键

在这套配置中,默认下,F6 键是编译并运行,F5 键是打开 Debug 窗口,F9 键是对选中的行打断点。

如何 Debug?

首先,你要保证代码没有被 linter 查出错误,这是最基本的; 然后对着你想打断点的行的行数左侧点一下,出现的红色按钮就是断点标识,用 F9 键也是同样的效果; 之后,按下 F6 键,也就是编译出代码的可执行文件; 紧接着在左侧 Tree View 中右键点击编译好的二进制文件,选择 Debug this File; 最后点击右下角的 Debug 按钮,就能开始 Debug 了。

同时,dbg 插件还可以保存断点之类的调试信息,按钮就在 Debug 按钮的下方。

最后推荐几个 Atom 插件

minimap

可以说是 Atom 的必装插件之一,提供整个文件的缩略图预览。

autocomplete-clang

依赖于 autocomplete-plus(atom 自带),且系统中需要有 clang 软件包。 可以提供非常强大的自动补全功能。

autocomplete-paths

顾名思义,是一个自动补全 path 的插件,也依赖于 autocomplete-plus。

atom-beautify

只需按一下快捷键,自动规范格式化你的代码。 Beautify C 语言依赖于 Uncrustify,但安装配置起来很简单。

activate-power-mode

越写越爽

atom-miku

(引述原作者的话:)

  • 做工粗糙
  • 仅供娱乐
q; 大佬,请问在装了这些插件之后,应该怎么实现同时编译多个文件?

a; “同时编译多个文件”指的是什么?可能你需要的是cmake,atom有个配套的插件build-cmake你可以试一试。 另外还有Atom IDE可以提供类似IDE的功能。 

from https://www.eaimty.com/2019/atom-c-ide/

Tuesday, 12 April 2022

Atom-Build

Build your project directly from the Atom editor.

https://atom.io/packages/build

Release notes

Plugin installs Package version

Travis.ci Shield AppVeyor Shield

Gitter chat Slack Badge

Automatically build your project inside your new favorite editor Atom.

  • Cmd Alt B / Ctrl Alt B / F9 builds your project.
  • Cmd Alt G / Ctrl Alt G / F4 cycles through causes of build error. See Error Matching.
  • Cmd Alt G / Ctrl Alt H / Shift F4 goes to the first build error. See Error Matching.
  • Cmd Alt V / Ctrl Alt V / F8 Toggles the build panel.
  • Cmd Alt T / Ctrl Alt T / F7 Displays the available build targets.
  • Esc terminates build / closes the build window.

Builds your project - configure it your way

work work

Automatically extract targets - here with build-make.

targets

Match errors and go directly to offending code - with Atom Linter.

error matching

(You can also use keyboard shortcuts to go to errors if you don't like Atom Linter, or want to keep package dependencies to a minimum).

Quick start

Install the build package using apm (apm can be installed using the install shell commands tool in Atom)(Linux/Mac):

$ apm install build

Create a file called .atom-build.yml (note the inital dot):

cmd: echo Hello world

Save it, and press Cmd Alt B (OS X) / Ctrl Alt B (Linux/Windows) and you should see the output of echo Hello world, which should be Hello world if all is correct.

Build providers

Instead of specifying commands manually, you can use a build provider. They often include functionality such as parsing targets (for instance all tasks from gulpfile.js or Makefile).

Full list of build providers

Specify a custom build command

If no build provider is enough to suit your needs, you can configure the custom build command extensively.

Supported formats and the name of the configuration file is

  • JSON: .atom-build.json
  • CSON: .atom-build.cson
  • YAML: .atom-build.yaml or .atom-build.yml
  • JS: .atom-build.js

Pick your favorite format, save that file in your project root, and specify exactly how your project is built (example in yml)

cmd: "<command to execute>"
name: "<name of target>"
args:
  - <argument1>
  - <argument2>
sh: true,
cwd: <current working directory for `cmd`>
env:
  VARIABLE1: "VALUE1"
  VARIABLE2: "VALUE2"
errorMatch:
  - ^regexp1$
  - ^regexp2$
warningMatch:
  - ^regexp1$
  - ^regexp2$
keymap: <keymap string>
atomCommandName: namespace:command
targets:
  extraTargetName:
      cmd: "<command to execute>"
      args:
      # (any previous options are viable here except `targets` itself)

Note that if sh is false cmd must only be the executable - no arguments here. If the executable is not in your path, either fully qualify it or specify the path in you environment (e.g. by setting the PATH var appropriately on UNIX-like systems).

If sh is true, it will use a shell (e.g. /bin/sh -c) on unix/linux, and command (cmd /S /C) on windows.

Programmatic Build commands (Javascript)

Using a JavaScript (JS) file gives you the additional benefit of being able to specify preBuild and postBuild and being able to run arbitrary match functions instead of regex-matching. The javascript function needs to return an array of matches. The fields of the matches must be the same as those that the regex can set.

Keep in mind that the JavaScript file must export the configuration

module.exports = {
  cmd: "myCommand",
  preBuild: function () {
    console.log('This is run **before** the build command');
  },
  postBuild: function () {
    console.log('This is run **after** the build command');
  },
  functionMatch: function (terminal_output) {
    // this is the array of matches that we create
    var matches = [];
    terminal_output.split(/\n/).forEach(function (line, line_number, terminal_output) {
      // all lines starting with a slash
      if line[0] == '/' {
        this.push({
          file: 'x.txt',
          line: line_number.toString(),
          message: line
        });
      }
    }.bind(matches));
    return matches;
  }
};

A major advantage of the functionMatch method is that you can keep state while parsing the output. For example, if you have a Makefile output like this:

make[1]: Entering directory 'foo'
make[2]: Entering directory 'foo/src'
testmake.c: In function 'main':
testmake.c:3:5: error: unknown type name 'error'

then you can't use a regex to match the filename, because the regex doesn't have the information about the directory changes. The following functionMatch can handle this case. Explanations are in the comments:

module.exports = {
  cmd: 'make',
  name: 'Makefile',
  sh: true,
  functionMatch: function (output) {
    const enterDir = /^make\[\d+\]: Entering directory '([^']+)'$/;
    const error = /^([^:]+):(\d+):(\d+): error: (.+)$/;
    // this is the list of error matches that atom-build will process
    const array = [];
    // stores the current directory
    var dir = null;
    // iterate over the output by lines
    output.split(/\r?\n/).forEach(line => {
      // update the current directory on lines with `Entering directory`
      const dir_match = enterDir.exec(line);
      if (dir_match) {
        dir = dir_match[1];
      } else {
        // process possible error messages
        const error_match = error.exec(line);
        if (error_match) {
          // map the regex match to the error object that atom-build expects
          array.push({
            file: dir ? dir + '/' + error_match[1] : error_match[1],
            line: error_match[2],
            col: error_match[3],
            message: error_match[4]
          });
        }
      }
    });
    return array;
  }
};

Another feature of functionMatch is that you can attach informational messages to the error messages:

pic of traces and custom error types

You can add these additional messages by setting the trace field of the error object. It needs to be an array of objects with the same fields as the error. Instead of adding squiggly lines at the location given by the fileline and col fields, a link is added to the popup message, so you can conveniently jump to the location given in the trace.

One more feature provided by functionMatch is the ability to use HTML in the message text by setting html_message instead of message. If both html_message and message are set, the latter takes priority.

Configuration options

OptionRequiredDescription
cmd[required]The executable command
name[optional]The name of the target. Viewed in the targets list (toggled by build:select-active-target).
args[optional]An array of arguments for the command
sh[optional]If true, the combined command and arguments will be passed to /bin/sh. Default true.
cwd[optional]The working directory for the command. E.g. what . resolves to.
env[optional]An object of environment variables and their values to set
errorMatch[optional]A (list of) regular expressions to match output to a file, row and col. See Error matching for details.
warningMatch[optional]Like errorMatch, but is reported as just a warning
functionMatch[optional]A (list of) javascript functions that return a list of match objects
keymap[optional]A keymap string as defined by Atom. Pressing this key combination will trigger the target. Examples: ctrl-alt-k or cmd-U.
killSignals[optional]An array of signals. The signals will be sent, one after each time Escape is pressed until the process has been terminated. The default value is SIGINT -> SIGTERM -> SIGKILL. The only signal which is guaranteed to terminate the process is SIGKILL so it is recommended to include that in the list.
atomCommandName[optional]Command name to register which should be on the form of namespace:command. Read more about Atom CommandRegistry. The command will be available in the command palette and can be trigger from there. If this is returned by a build provider, the command can programatically be triggered by dispatching.
targets[optional]Additional targets which can be used to build variations of your project.
preBuild[optional]JS only. A function which will be called before executing cmd. No arguments. this will be the build configuration.
postBuild[optional]JS only. A function which will be called after executing cmd. It will be passed 3 arguments: bool buildOutcome indicating outcome of the running cmdstring stdout containing the contents of stdout, and string stderr containing the contents of stderrthis will be the build configuration.

Replacements

The following parameters will be replaced in cmd, any entry in argscwd and values of env. They should all be enclosed in curly brackets {}

  • {FILE_ACTIVE} - Full path to the currently active file in Atom. E.g. /home/noseglid/github/atom-build/lib/build.js
  • {FILE_ACTIVE_PATH} - Full path to the folder where the currently active file is. E.g. /home/noseglid/github/atom-build/lib
  • {FILE_ACTIVE_NAME} - Full name and extension of active file. E.g., build.js
  • {FILE_ACTIVE_NAME_BASE} - Name of active file WITHOUT extension. E.g., build
  • {FILE_ACTIVE_CURSOR_ROW} - Line number where the last inserted cursor sits. E.g, 21
  • {FILE_ACTIVE_CURSOR_COLUMN} - Column number where the last inserted cursor sits. E.g, 42
  • {PROJECT_PATH} - Full path to the root of the project. This is normally the path Atom has as root. E.g /home/noseglid/github/atom-build
  • {REPO_BRANCH_SHORT} - Short name of the current active branch (if project is backed by git). E.g master or v0.9.1
  • {SELECTION} - Selected text.

Creating a build provider

Creating a build provider require very little code in the easiest case, and can be as complicated as necessary to achieve the correct functionality. Read more about building your own provider in the create provider documentation.

Error matching

Error matching lets you specify a single regular expression or a list of regular expressions, which capture the output of your build command and open the correct file, row and column of the error. For instance:

../foo/bar/a.c:4:26: error: expected ';' after expression
  printf("hello world\n")
                         ^
                         ;
1 error generated.

Would be matched with the regular expression: (?<file>[\\/0-9a-zA-Z\\._]+):(?<line>\\d+):(?<col>\\d+):\\s+(?<message>.+). After the build has failed, pressing Cmd Alt G (OS X) or Ctrl Alt G (Linux/Windows) (or F4 on either platform), a.c would be opened and the cursor would be placed at row 4, column 26.

Note the syntax for match groups. This is from the XRegExp package and has the syntax for named groups: (?<name> RE ) where name would be the name of the group matched by the regular expression RE.

The following named groups can be matched from the output:

  • file - [required] the file to open. May be relative cwd or absolute. (?<file> RE).
  • line - [optional] the line the error starts on. (?<line> RE).
  • col - [optional] the column the error starts on. (?<col> RE).
  • line_end - [optional] the line the error ends on. (?<line_end> RE).
  • col_end - [optional] the column the error ends on. (?<col_end> RE).
  • message - [optional] Catch the humanized error message. (?<message> RE).

The file should be relative the cwd specified. If no cwd has been specified, then the file should be relative the project root (e.g. the top most directory shown in the Atom Editor).

If your build outputs multiple errors, all will be matched. Press Cmd Alt G (OS X) or Ctrl Alt G (Linux/Windows) to cycle through the errors (in the order they appear, first on stderr then on stdout), or you can use the Atom Linter integration discussed in the next section.

Often, the first error is the most interesting since other errors tend to be secondary faults caused by that first one. To jump to the first error you can use Cmd Alt H (OS X) or Shift F4 (Linux/Windows) at any point to go to the first error.

Error matching and Atom Linter

Install Atom Linter and all your matched errors will listed in a neat panel.

Linter integration

Analytics

The atom-build package uses google analytics to keep track of which features are in use and at what frequency. This gives the maintainers a sense of what parts of the package is most important and what parts can be removed.

The data is fully anonymous and can not be tracked back to you in any way. This is what is collected

  • Version of package used.
  • Build triggered, succeeded or failed.
  • Which build tool was used.
  • Visibility of UI components.

If you really do not want to share this information, you can opt out by disabling the metrics package. This will disable all analytics collection, including the one from atom-build.


from  https://github.com/noseglid/atom-build